/home/koen/project/wt/cvs/wt/examples/simplechat/SimpleChatServer.C

Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2007 Koen Deforche
00003  *
00004  * See the LICENSE file for terms of use.
00005  */
00006 
00007 #include "SimpleChatServer.h"
00008 
00009 #include <iostream>
00010 #include <boost/lexical_cast.hpp>
00011 
00012 using namespace Wt;
00013 
00014 const WString ChatEvent::formattedHTML(const WString& user) const
00015 {
00016   switch (type_) {
00017   case Login:
00018     return "<span class='chat-info'>"
00019       + user_ + " joined the conversation.</span>";
00020   case Logout:
00021     return "<span class='chat-info'>"
00022       + ((user == user_) ? "You" : user_)
00023       + " logged out.</span>";
00024   case Message:{
00025     WString result;
00026 
00027     result = WString("<span class='")
00028       + ((user == user_) ? "chat-self" : "chat-user")
00029       + "'>" + user_ + ":</span>";
00030 
00031     if (message_.toUTF8().find(user.toUTF8()) != std::string::npos)
00032       return result + "<span class='chat-highlight'>" + message_ + "</span>";
00033     else
00034       return result + message_;
00035   }
00036   default:
00037     return "";
00038   }
00039 }
00040 
00041 
00042 SimpleChatServer::SimpleChatServer()
00043 { }
00044 
00045 bool SimpleChatServer::login(const WString& user)
00046 {
00047   boost::mutex::scoped_lock lock(mutex_);
00048   
00049   if (users_.find(user) == users_.end()) {
00050     users_.insert(user);
00051 
00052     chatEvent.emit(ChatEvent(ChatEvent::Login, user));
00053 
00054     return true;
00055   } else
00056     return false;
00057 }
00058 
00059 void SimpleChatServer::logout(const WString& user)
00060 {
00061   boost::mutex::scoped_lock lock(mutex_);
00062   
00063   UserSet::iterator i = users_.find(user);
00064 
00065   if (i != users_.end()) {
00066     users_.erase(i);
00067 
00068     chatEvent.emit(ChatEvent(ChatEvent::Logout, user));
00069   }
00070 }
00071 
00072 WString SimpleChatServer::suggestGuest()
00073 {
00074   boost::mutex::scoped_lock lock(mutex_);
00075 
00076   for (int i = 1;; ++i) {
00077     std::string s = "guest " + boost::lexical_cast<std::string>(i);
00078     WString ss = s;
00079 
00080     if (users_.find(ss) == users_.end())
00081       return ss;
00082   }
00083 }
00084 
00085 void SimpleChatServer::sendMessage(const WString& user, const WString& message)
00086 {
00087   boost::mutex::scoped_lock lock(mutex_);
00088 
00089   chatEvent.emit(ChatEvent(user, message));
00090 }
00091 
00092 SimpleChatServer::UserSet SimpleChatServer::users()
00093 {
00094   return users_;
00095 }

Generated on Mon Apr 14 15:15:04 2008 for Wt by doxygen 1.5.3