The client network code was rewritten to use boost::asio. Some optimization is still required, and some code files can now be removed.

This commit is contained in:
lotodore
2009-06-14 22:07:41 +00:00
parent 7048c19305
commit 4b5d78af81
16 changed files with 1186 additions and 1193 deletions
+1 -2
View File
@@ -4,7 +4,7 @@ TEMPLATE = app
CODECFORSRC = UTF-8
CONFIG += qt thread embed_manifest_exe exceptions rtti stl warn_on release
# CONFIG += qt thread embed_manifest_exe exceptions rtti stl warn_on debug
#CONFIG += qt thread embed_manifest_exe exceptions rtti stl warn_on debug
# ####Uncomment this for RELEASE on Linux/Unix/BSD (only for static Qt)
#QTPLUGIN += qjpeg qgif
@@ -118,7 +118,6 @@ HEADERS += src/game.h \
src/net/clientthread.h \
src/net/genericsocket.h \
src/net/netpacket.h \
src/net/resolverthread.h \
src/net/senderhelper.h \
src/net/serveraccepthelper.h \
src/net/serverlobbythread.h \
-4
View File
@@ -72,10 +72,8 @@ HEADERS += \
src/net/clientthread.h \
src/net/genericsocket.h \
src/net/netpacket.h \
src/net/resolverthread.h \
src/net/senderhelper.h \
src/net/sendercallback.h \
src/net/servercontext.h \
src/net/serverexception.h \
src/net/serveraccepthelper.h \
src/net/servergame.h \
@@ -172,10 +170,8 @@ SOURCES += \
src/net/common/downloadhelper.cpp \
src/net/common/downloaderthread.cpp \
src/net/common/netpacket.cpp \
src/net/common/resolverthread.cpp \
src/net/common/senderhelper.cpp \
src/net/common/sendercallback.cpp \
src/net/common/servercontext.cpp \
src/net/common/serverexception.cpp \
src/net/common/serveraccepthelper.cpp \
src/net/common/servergame.cpp \
-1
View File
@@ -70,7 +70,6 @@ HEADERS += \
src/net/clientthread.h \
src/net/genericsocket.h \
src/net/netpacket.h \
src/net/resolverthread.h \
src/net/senderhelper.h \
src/net/serveraccepthelper.h \
src/net/serverlobbythread.h \
+4 -12
View File
@@ -23,21 +23,20 @@
#include <boost/shared_ptr.hpp>
#include <net/netcontext.h>
#include <net/receivebuffer.h>
#include <net/sessiondata.h>
class ClientContext : public NetContext
class ClientContext
{
public:
ClientContext();
virtual ~ClientContext();
virtual SOCKET GetSocket() const;
boost::shared_ptr<SessionData> GetSessionData() const;
void SetSessionData(boost::shared_ptr<SessionData> sessionData);
boost::shared_ptr<boost::asio::ip::tcp::resolver> GetResolver() const;
void SetResolver(boost::shared_ptr<boost::asio::ip::tcp::resolver> resolver);
int GetProtocol() const
{return m_protocol;}
void SetProtocol(int protocol)
@@ -70,10 +69,6 @@ public:
{return m_password;}
void SetPassword(const std::string &password)
{m_password = password;}
const sockaddr_storage *GetClientSockaddr() const
{return &m_clientSockaddr;}
sockaddr_storage *GetClientSockaddr()
{return &m_clientSockaddr;}
const std::string &GetPlayerName() const
{return m_playerName;}
void SetPlayerName(const std::string &playerName)
@@ -91,14 +86,12 @@ public:
void SetSubscribeLobbyMsg(bool setSubscribe)
{m_hasSubscribedLobbyMsg = setSubscribe;}
int GetClientSockaddrSize() const
{return m_addrFamily == AF_INET6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in);}
ReceiveBuffer &GetReceiveBuffer()
{return m_receiveBuffer;}
private:
boost::shared_ptr<SessionData> m_sessionData;
boost::shared_ptr<boost::asio::ip::tcp::resolver> m_resolver;
int m_protocol;
int m_addrFamily;
std::string m_serverAddr;
@@ -107,7 +100,6 @@ private:
unsigned m_serverPort;
std::string m_avatarServerAddr;
std::string m_password;
sockaddr_storage m_clientSockaddr;
std::string m_playerName;
std::string m_avatarFile;
std::string m_cacheDir;
+95 -117
View File
@@ -21,11 +21,9 @@
#ifndef _CLIENTSTATE_H_
#define _CLIENTSTATE_H_
#include <third_party/boost/timers.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <string>
#include <memory>
#include <net/socket_helper.h> // needed for correct order of header files.
#define CLIENT_INITIAL_STATE ClientStateInit
@@ -41,8 +39,10 @@ class ClientState
public:
virtual ~ClientState();
// Main processing function of the current state.
virtual int Process(ClientThread &client) = 0;
virtual void Enter(boost::shared_ptr<ClientThread> client) = 0;
virtual void Exit(boost::shared_ptr<ClientThread> client) = 0;
virtual void HandleRead(const boost::system::error_code& ec, boost::shared_ptr<ClientThread> client, size_t bytesRead) = 0;
};
// State: Initialization.
@@ -51,14 +51,15 @@ class ClientStateInit : public ClientState
public:
// Access the state singleton.
static ClientStateInit &Instance();
virtual ~ClientStateInit();
// Some basic initialization (socket creation, basic checks).
virtual int Process(ClientThread &client);
virtual void Enter(boost::shared_ptr<ClientThread> client);
virtual void Exit(boost::shared_ptr<ClientThread> client);
virtual void HandleRead(const boost::system::error_code& /*ec*/, boost::shared_ptr<ClientThread> /*client*/, size_t /*bytesRead*/) {}
protected:
// Protected constructor - this is a singleton.
ClientStateInit();
};
@@ -69,55 +70,36 @@ class ClientStateStartResolve : public ClientState
public:
// Access the state singleton.
static ClientStateStartResolve &Instance();
virtual ~ClientStateStartResolve();
// Initiate the name resolution.
virtual int Process(ClientThread &client);
virtual void Enter(boost::shared_ptr<ClientThread> client);
virtual void Exit(boost::shared_ptr<ClientThread> client);
virtual void HandleRead(const boost::system::error_code& /*ec*/, boost::shared_ptr<ClientThread> /*client*/, size_t /*bytesRead*/) {}
protected:
void HandleResolve(
const boost::system::error_code& ec, boost::asio::ip::tcp::resolver::iterator endpoint_iterator,
boost::shared_ptr<ClientThread> client);
// Protected constructor - this is a singleton.
ClientStateStartResolve();
};
// State: Name resolution.
class ClientStateResolving : public ClientState
{
public:
// Access the state singleton.
static ClientStateResolving &Instance();
virtual ~ClientStateResolving();
void SetResolver(ResolverThread *resolver);
// Poll for the completion of the name resolution.
virtual int Process(ClientThread &client);
protected:
// Protected constructor - this is a singleton.
ClientStateResolving();
void Cleanup();
private:
ResolverThread *m_resolver;
};
// State: Start download of the server list.
class ClientStateStartServerListDownload : public ClientState
{
public:
// Access the state singleton.
static ClientStateStartServerListDownload &Instance();
virtual ~ClientStateStartServerListDownload();
// Initiate the name resolution.
virtual int Process(ClientThread &client);
virtual void Enter(boost::shared_ptr<ClientThread> client);
virtual void Exit(boost::shared_ptr<ClientThread> client);
virtual void HandleRead(const boost::system::error_code& /*ec*/, boost::shared_ptr<ClientThread> /*client*/, size_t /*bytesRead*/) {}
protected:
@@ -131,22 +113,26 @@ class ClientStateSynchronizingServerList : public ClientState
public:
// Access the state singleton.
static ClientStateSynchronizingServerList &Instance();
virtual ~ClientStateSynchronizingServerList();
void SetDownloadHelper(DownloadHelper *helper);
virtual void Enter(boost::shared_ptr<ClientThread> client);
virtual void Exit(boost::shared_ptr<ClientThread> client);
// Poll for the completion of the download.
virtual int Process(ClientThread &client);
virtual void HandleRead(const boost::system::error_code& /*ec*/, boost::shared_ptr<ClientThread> /*client*/, size_t /*bytesRead*/) {}
void SetDownloadHelper(boost::shared_ptr<DownloadHelper> helper);
protected:
// Protected constructor - this is a singleton.
ClientStateSynchronizingServerList();
// Poll for the completion of the download.
void TimerLoop(const boost::system::error_code& ec, boost::shared_ptr<ClientThread> client);
private:
std::auto_ptr<DownloadHelper> m_downloadHelper;
boost::shared_ptr<DownloadHelper> m_downloadHelper;
};
// State: Downloading the server list.
@@ -155,22 +141,26 @@ class ClientStateDownloadingServerList : public ClientState
public:
// Access the state singleton.
static ClientStateDownloadingServerList &Instance();
virtual ~ClientStateDownloadingServerList();
void SetDownloadHelper(DownloadHelper *helper);
virtual void Enter(boost::shared_ptr<ClientThread> client);
virtual void Exit(boost::shared_ptr<ClientThread> client);
// Poll for the completion of the download.
virtual int Process(ClientThread &client);
virtual void HandleRead(const boost::system::error_code& /*ec*/, boost::shared_ptr<ClientThread> /*client*/, size_t /*bytesRead*/) {}
void SetDownloadHelper(boost::shared_ptr<DownloadHelper> helper);
protected:
// Protected constructor - this is a singleton.
ClientStateDownloadingServerList();
// Poll for the completion of the download.
void TimerLoop(const boost::system::error_code& ec, boost::shared_ptr<ClientThread> client);
private:
std::auto_ptr<DownloadHelper> m_downloadHelper;
boost::shared_ptr<DownloadHelper> m_downloadHelper;
};
// State: Reading the server list.
@@ -178,10 +168,12 @@ class ClientStateReadingServerList : public ClientState
{
public:
static ClientStateReadingServerList &Instance();
virtual ~ClientStateReadingServerList();
virtual int Process(ClientThread &client);
virtual void Enter(boost::shared_ptr<ClientThread> client);
virtual void Exit(boost::shared_ptr<ClientThread> client);
virtual void HandleRead(const boost::system::error_code& /*ec*/, boost::shared_ptr<ClientThread> /*client*/, size_t /*bytesRead*/) {}
protected:
@@ -194,15 +186,19 @@ class ClientStateWaitChooseServer : public ClientState
{
public:
static ClientStateWaitChooseServer &Instance();
virtual ~ClientStateWaitChooseServer();
virtual int Process(ClientThread &client);
virtual void Enter(boost::shared_ptr<ClientThread> client);
virtual void Exit(boost::shared_ptr<ClientThread> client);
virtual void HandleRead(const boost::system::error_code& /*ec*/, boost::shared_ptr<ClientThread> /*client*/, size_t /*bytesRead*/) {}
protected:
// Protected constructor - this is a singleton.
ClientStateWaitChooseServer();
void TimerLoop(const boost::system::error_code& ec, boost::shared_ptr<ClientThread> client);
};
// State: Initiate server connection.
@@ -211,40 +207,29 @@ class ClientStateStartConnect : public ClientState
public:
// Access the state singleton.
static ClientStateStartConnect &Instance();
virtual ~ClientStateStartConnect();
// Call connect.
virtual int Process(ClientThread &client);
virtual void Enter(boost::shared_ptr<ClientThread> client);
virtual void Exit(boost::shared_ptr<ClientThread> client);
virtual void HandleRead(const boost::system::error_code& /*ec*/, boost::shared_ptr<ClientThread> /*client*/, size_t /*bytesRead*/) {}
void SetRemoteEndpoint(boost::asio::ip::tcp::resolver::iterator endpointIterator);
protected:
// Protected constructor - this is a singleton.
ClientStateStartConnect();
};
// State: Connecting to server.
class ClientStateConnecting : public ClientState
{
public:
// Access the state singleton.
static ClientStateConnecting &Instance();
void HandleConnect(const boost::system::error_code& ec,
boost::asio::ip::tcp::resolver::iterator endpoint_iterator,
boost::shared_ptr<ClientThread> client);
virtual ~ClientStateConnecting();
void SetTimer(const boost::timers::portable::microsec_timer &timer);
// "Poll" for the completion of the TCP/IP connect call.
virtual int Process(ClientThread &client);
protected:
// Protected constructor - this is a singleton.
ClientStateConnecting();
void TimerTimeout(const boost::system::error_code& ec, boost::shared_ptr<ClientThread> client);
private:
boost::timers::portable::microsec_timer m_connectTimer;
boost::asio::ip::tcp::resolver::iterator m_remoteEndpointIterator;
};
// State: Session init.
@@ -253,11 +238,12 @@ class ClientStateStartSession : public ClientState
public:
// Access the state singleton.
static ClientStateStartSession &Instance();
virtual ~ClientStateStartSession();
// sleep.
virtual int Process(ClientThread &client);
virtual void Enter(boost::shared_ptr<ClientThread> client);
virtual void Exit(boost::shared_ptr<ClientThread> client);
virtual void HandleRead(const boost::system::error_code& /*ec*/, boost::shared_ptr<ClientThread> /*client*/, size_t /*bytesRead*/) {}
protected:
@@ -271,14 +257,13 @@ class AbstractClientStateReceiving : public ClientState
public:
virtual ~AbstractClientStateReceiving();
// select on socket.
virtual int Process(ClientThread &client);
virtual void HandleRead(const boost::system::error_code& ec, boost::shared_ptr<ClientThread> client, size_t bytesRead);
protected:
virtual int InternalProcess(ClientThread &client, boost::shared_ptr<NetPacket> packet) = 0;
AbstractClientStateReceiving();
void HandlePacket(boost::shared_ptr<ClientThread> client, boost::shared_ptr<NetPacket> tmpPacket);
virtual void InternalHandlePacket(boost::shared_ptr<ClientThread> client, boost::shared_ptr<NetPacket> tmpPacket) = 0;
};
// State: Wait for Session ACK.
@@ -287,16 +272,16 @@ class ClientStateWaitSession : public AbstractClientStateReceiving
public:
// Access the state singleton.
static ClientStateWaitSession &Instance();
virtual ~ClientStateWaitSession();
virtual void Enter(boost::shared_ptr<ClientThread> client);
virtual void Exit(boost::shared_ptr<ClientThread> client);
protected:
// Protected constructor - this is a singleton.
ClientStateWaitSession();
virtual int InternalProcess(ClientThread &client, boost::shared_ptr<NetPacket> packet);
virtual void InternalHandlePacket(boost::shared_ptr<ClientThread> client, boost::shared_ptr<NetPacket> tmpPacket);
};
// State: Wait for Join.
@@ -305,16 +290,17 @@ class ClientStateWaitJoin : public AbstractClientStateReceiving
public:
// Access the state singleton.
static ClientStateWaitJoin &Instance();
virtual ~ClientStateWaitJoin();
virtual void Enter(boost::shared_ptr<ClientThread> client);
virtual void Exit(boost::shared_ptr<ClientThread> client);
protected:
// Protected constructor - this is a singleton.
ClientStateWaitJoin();
virtual int InternalProcess(ClientThread &client, boost::shared_ptr<NetPacket> packet);
virtual void InternalHandlePacket(boost::shared_ptr<ClientThread> client, boost::shared_ptr<NetPacket> tmpPacket);
};
// State: Wait for start of the game or start info.
@@ -323,15 +309,17 @@ class ClientStateWaitGame : public AbstractClientStateReceiving
public:
// Access the state singleton.
static ClientStateWaitGame &Instance();
virtual ~ClientStateWaitGame();
virtual void Enter(boost::shared_ptr<ClientThread> client);
virtual void Exit(boost::shared_ptr<ClientThread> client);
protected:
// Protected constructor - this is a singleton.
ClientStateWaitGame();
virtual int InternalProcess(ClientThread &client, boost::shared_ptr<NetPacket> packet);
virtual void InternalHandlePacket(boost::shared_ptr<ClientThread> client, boost::shared_ptr<NetPacket> tmpPacket);
};
// State: Synchronize on game start.
@@ -340,16 +328,18 @@ class ClientStateSynchronizeStart : public AbstractClientStateReceiving
public:
// Access the state singleton.
static ClientStateSynchronizeStart &Instance();
virtual ~ClientStateSynchronizeStart();
virtual int Process(ClientThread &client);
virtual void Enter(boost::shared_ptr<ClientThread> client);
virtual void Exit(boost::shared_ptr<ClientThread> client);
protected:
// Protected constructor - this is a singleton.
ClientStateSynchronizeStart();
virtual int InternalProcess(ClientThread &client, boost::shared_ptr<NetPacket> packet);
void TimerLoop(const boost::system::error_code& ec, boost::shared_ptr<ClientThread> client);
virtual void InternalHandlePacket(boost::shared_ptr<ClientThread> client, boost::shared_ptr<NetPacket> tmpPacket);
};
// State: Wait for game start.
@@ -358,15 +348,17 @@ class ClientStateWaitStart : public AbstractClientStateReceiving
public:
// Access the state singleton.
static ClientStateWaitStart &Instance();
virtual ~ClientStateWaitStart();
virtual void Enter(boost::shared_ptr<ClientThread> client);
virtual void Exit(boost::shared_ptr<ClientThread> client);
protected:
// Protected constructor - this is a singleton.
ClientStateWaitStart();
virtual int InternalProcess(ClientThread &client, boost::shared_ptr<NetPacket> packet);
virtual void InternalHandlePacket(boost::shared_ptr<ClientThread> client, boost::shared_ptr<NetPacket> tmpPacket);
};
// State: Wait for start of the next hand.
@@ -375,15 +367,17 @@ class ClientStateWaitHand : public AbstractClientStateReceiving
public:
// Access the state singleton.
static ClientStateWaitHand &Instance();
virtual ~ClientStateWaitHand();
virtual void Enter(boost::shared_ptr<ClientThread> client);
virtual void Exit(boost::shared_ptr<ClientThread> client);
protected:
// Protected constructor - this is a singleton.
ClientStateWaitHand();
virtual int InternalProcess(ClientThread &client, boost::shared_ptr<NetPacket> packet);
virtual void InternalHandlePacket(boost::shared_ptr<ClientThread> client, boost::shared_ptr<NetPacket> tmpPacket);
};
// State: Hand Loop.
@@ -392,36 +386,20 @@ class ClientStateRunHand : public AbstractClientStateReceiving
public:
// Access the state singleton.
static ClientStateRunHand &Instance();
virtual ~ClientStateRunHand();
virtual void Enter(boost::shared_ptr<ClientThread> client);
virtual void Exit(boost::shared_ptr<ClientThread> client);
protected:
// Protected constructor - this is a singleton.
ClientStateRunHand();
virtual int InternalProcess(ClientThread &client, boost::shared_ptr<NetPacket> packet);
virtual void InternalHandlePacket(boost::shared_ptr<ClientThread> client, boost::shared_ptr<NetPacket> tmpPacket);
static void ResetPlayerActions(Game &curGame);
static void ResetPlayerSets(Game &curGame);
};
// State: Final (just for testing, should not be used).
class ClientStateFinal : public ClientState
{
public:
// Access the state singleton.
static ClientStateFinal &Instance();
virtual ~ClientStateFinal();
// sleep.
virtual int Process(ClientThread &client);
protected:
// Protected constructor - this is a singleton.
ClientStateFinal();
};
#endif
+16 -3
View File
@@ -23,6 +23,7 @@
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <string>
#include <core/thread.h>
@@ -42,7 +43,7 @@ class NetPacket;
class AvatarManager;
class QtToolsInterface;
class ClientThread : public Thread
class ClientThread : public Thread, public boost::enable_shared_from_this<ClientThread>
{
public:
ClientThread(GuiInterface &gui, AvatarManager &avatarManager);
@@ -63,6 +64,7 @@ public:
const std::string &playerName,
const std::string &avatarFile,
const std::string &cacheDir);
virtual void SignalTermination();
void SendKickPlayer(unsigned playerId);
void SendLeaveCurrentGame();
@@ -76,6 +78,9 @@ public:
void SendAskKickPlayer(unsigned playerId);
void SendVoteKick(bool doKick);
void StartAsyncRead();
void HandleRead(const boost::system::error_code& ec, size_t bytesRead);
void SelectServer(unsigned serverId);
ServerInfo GetServerInfo(unsigned serverId) const;
@@ -98,9 +103,12 @@ protected:
// Main function of the thread.
virtual void Main();
void RegisterTimers();
void CancelTimers();
void InitGame();
void AddPacket(boost::shared_ptr<NetPacket> packet);
void SendPacketLoop();
void TimerSendPacketLoop(const boost::system::error_code &ec);
bool GetCachedPlayerInfo(unsigned id, PlayerInfo &info) const;
void RequestPlayerInfo(unsigned id, bool requestAvatar = false);
@@ -115,7 +123,7 @@ protected:
void PassAvatarDataToManager(unsigned playerId, boost::shared_ptr<AvatarData> avatarData);
void SetUnknownAvatar(unsigned playerId);
void CheckAvatarDownloads();
void TimerCheckAvatarDownloads(const boost::system::error_code& ec);
void UnsubscribeLobbyMsg();
void ResubscribeLobbyMsg();
@@ -126,6 +134,7 @@ protected:
ClientState &GetState();
void SetState(ClientState &newState);
boost::asio::deadline_timer &GetStateTimer();
SenderHelper &GetSender();
ReceiverHelper &GetReceiver();
@@ -235,6 +244,10 @@ private:
mutable boost::mutex m_curStatsMutex;
ServerStats m_curStats;
boost::asio::deadline_timer m_stateTimer;
boost::asio::deadline_timer m_avatarTimer;
boost::asio::deadline_timer m_sendTimer;
friend class AbstractClientStateReceiving;
friend class ClientStateInit;
friend class ClientStateStartResolve;
+12 -8
View File
@@ -24,7 +24,6 @@ ClientContext::ClientContext()
: m_protocol(0), m_addrFamily(AF_INET), m_useServerList(false), m_serverPort(0),
m_hasSubscribedLobbyMsg(true)
{
bzero(&m_clientSockaddr, sizeof(m_clientSockaddr));
}
ClientContext::~ClientContext()
@@ -32,13 +31,6 @@ ClientContext::~ClientContext()
m_sessionData.reset();
}
SOCKET
ClientContext::GetSocket() const
{
assert(m_sessionData.get());
return m_sessionData->GetSocket();
}
boost::shared_ptr<SessionData>
ClientContext::GetSessionData() const
{
@@ -51,3 +43,15 @@ ClientContext::SetSessionData(boost::shared_ptr<SessionData> sessionData)
m_sessionData = sessionData;
}
boost::shared_ptr<boost::asio::ip::tcp::resolver>
ClientContext::GetResolver() const
{
return m_resolver;
}
void
ClientContext::SetResolver(boost::shared_ptr<boost::asio::ip::tcp::resolver> resolver)
{
m_resolver = resolver;
}
File diff suppressed because it is too large Load Diff
+132 -52
View File
@@ -39,6 +39,8 @@
#include <cassert>
#define TEMP_AVATAR_FILENAME "avatar.tmp"
#define CLIENT_AVATAR_LOOP_MSEC 100
#define CLIENT_SEND_LOOP_MSEC 50
using namespace std;
using boost::asio::ip::tcp;
@@ -62,10 +64,11 @@ private:
};
ClientThread::ClientThread(GuiInterface &gui, AvatarManager &avatarManager)
: m_curState(NULL), m_gui(gui), m_avatarManager(avatarManager), m_isServerSelected(false),
m_curGameId(0), m_curGameNum(1), m_guiPlayerId(0), m_sessionEstablished(false)
: m_ioService(new boost::asio::io_service), m_curState(NULL), m_gui(gui),
m_avatarManager(avatarManager), m_isServerSelected(false),
m_curGameId(0), m_curGameNum(1), m_guiPlayerId(0), m_sessionEstablished(false),
m_stateTimer(*m_ioService), m_avatarTimer(*m_ioService), m_sendTimer(*m_ioService)
{
m_ioService.reset(new boost::asio::io_service());
m_context.reset(new ClientContext);
m_receiver.reset(new ReceiverHelper);
myQtToolsInterface.reset(CreateQtToolsWrapper());
@@ -106,6 +109,13 @@ ClientThread::Init(
context.SetCacheDir(cacheDir);
}
void
ClientThread::SignalTermination()
{
Thread::SignalTermination();
m_ioService->stop();
}
void
ClientThread::SendKickPlayer(unsigned playerId)
{
@@ -286,6 +296,27 @@ ClientThread::SendVoteKick(bool doKick)
m_outPacketList.push_back(vote);
}
void
ClientThread::StartAsyncRead()
{
ReceiveBuffer &buf = GetContext().GetSessionData()->GetReceiveBuffer();
GetContext().GetSessionData()->GetAsioSocket()->async_read_some(
boost::asio::buffer(buf.recvBuf + buf.recvBufUsed, RECV_BUF_SIZE - buf.recvBufUsed),
boost::bind(
&ClientThread::HandleRead,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void
ClientThread::HandleRead(const boost::system::error_code& ec, size_t bytesRead)
{
GetState().HandleRead(ec, shared_from_this(), bytesRead);
if (!ec)
StartAsyncRead();
}
void
ClientThread::SelectServer(unsigned serverId)
{
@@ -381,51 +412,67 @@ ClientThread::Main()
m_avatarDownloader.reset(new DownloaderThread);
m_avatarDownloader->Run();
SetState(CLIENT_INITIAL_STATE::Instance());
RegisterTimers();
// Main loop.
boost::asio::io_service::work ioWork(*m_ioService);
try
{
while (!ShouldTerminate())
{
int msg = GetState().Process(*this);
if (msg != MSG_SOCK_INTERNAL_PENDING)
{
if (msg <= MSG_SOCK_LIMIT_CONNECT)
GetCallback().SignalNetClientConnect(msg);
else
GetCallback().SignalNetClientGameInfo(msg);
// Additionally signal the start of the game.
if (msg == MSG_NET_GAME_CLIENT_START)
{
// EngineFactory erstellen
boost::shared_ptr<EngineFactory> factory(new ClientEngineFactory); // LocalEngine erstellen
MapPlayerDataList();
if (GetPlayerDataList().size() != (unsigned)GetStartData().numberOfPlayers)
throw ClientException(__FILE__, __LINE__, ERR_NET_INVALID_PLAYER_COUNT, 0);
m_game.reset(new Game(&m_gui, factory, GetPlayerDataList(), GetGameData(), GetStartData(), m_curGameNum++));
// Initialize GUI speed.
GetGui().initGui(GetGameData().guiSpeed);
// Signal start of game to GUI.
GetCallback().SignalNetClientGameStart(m_game);
}
}
if (IsSessionEstablished())
SendPacketLoop();
m_ioService->poll();
Thread::Msleep(10);
boost::asio::io_service::work ioWork(*m_ioService);
m_ioService->run(); // Will only be aborted asynchronously.
}
} catch (const PokerTHException &e)
{
GetCallback().SignalNetClientError(e.GetErrorId(), e.GetOsErrorCode());
}
// Cancel timers.
GetStateTimer().cancel();
CancelTimers();
// Terminate sub-threads.
m_avatarDownloader->SignalTermination();
m_avatarDownloader->Join(DOWNLOADER_THREAD_TERMINATE_TIMEOUT);
}
void
ClientThread::RegisterTimers()
{
m_avatarTimer.expires_from_now(
boost::posix_time::milliseconds(CLIENT_AVATAR_LOOP_MSEC));
m_avatarTimer.async_wait(
boost::bind(
&ClientThread::TimerCheckAvatarDownloads, shared_from_this(), boost::asio::placeholders::error));
m_sendTimer.expires_from_now(
boost::posix_time::milliseconds(CLIENT_SEND_LOOP_MSEC));
m_sendTimer.async_wait(
boost::bind(
&ClientThread::TimerSendPacketLoop, shared_from_this(), boost::asio::placeholders::error));
}
void
ClientThread::CancelTimers()
{
m_avatarTimer.cancel();
m_sendTimer.cancel();
}
void
ClientThread::InitGame()
{
// EngineFactory erstellen
boost::shared_ptr<EngineFactory> factory(new ClientEngineFactory); // LocalEngine erstellen
MapPlayerDataList();
if (GetPlayerDataList().size() != (unsigned)GetStartData().numberOfPlayers)
throw ClientException(__FILE__, __LINE__, ERR_NET_INVALID_PLAYER_COUNT, 0);
m_game.reset(new Game(&m_gui, factory, GetPlayerDataList(), GetGameData(), GetStartData(), m_curGameNum++));
// Initialize GUI speed.
GetGui().initGui(GetGameData().guiSpeed);
// Signal start of game to GUI.
GetCallback().SignalNetClientGameStart(m_game);
}
void
ClientThread::AddPacket(boost::shared_ptr<NetPacket> packet)
{
@@ -434,21 +481,32 @@ ClientThread::AddPacket(boost::shared_ptr<NetPacket> packet)
}
void
ClientThread::SendPacketLoop()
ClientThread::TimerSendPacketLoop(const boost::system::error_code &ec)
{
boost::mutex::scoped_lock lock(m_outPacketListMutex);
if (!m_outPacketList.empty())
if (!ec)
{
NetPacketList::iterator i = m_outPacketList.begin();
NetPacketList::iterator end = m_outPacketList.end();
while (i != end)
if (IsSessionEstablished())
{
GetSender().Send(GetContext().GetSessionData(), *i);
++i;
boost::mutex::scoped_lock lock(m_outPacketListMutex);
if (!m_outPacketList.empty())
{
NetPacketList::iterator i = m_outPacketList.begin();
NetPacketList::iterator end = m_outPacketList.end();
while (i != end)
{
GetSender().Send(GetContext().GetSessionData(), *i);
++i;
}
m_outPacketList.clear();
}
}
m_outPacketList.clear();
m_sendTimer.expires_from_now(
boost::posix_time::milliseconds(CLIENT_SEND_LOOP_MSEC));
m_sendTimer.async_wait(
boost::bind(
&ClientThread::TimerSendPacketLoop, shared_from_this(), boost::asio::placeholders::error));
}
}
@@ -668,15 +726,23 @@ ClientThread::SetUnknownAvatar(unsigned playerId)
}
void
ClientThread::CheckAvatarDownloads()
ClientThread::TimerCheckAvatarDownloads(const boost::system::error_code& ec)
{
if (m_avatarDownloader && m_avatarDownloader->HasDownloadResult())
if (!ec)
{
unsigned playerId;
boost::shared_ptr<AvatarData> tmpAvatar(new AvatarData);
m_avatarDownloader->GetDownloadResult(playerId, tmpAvatar->fileData);
tmpAvatar->reportedSize = tmpAvatar->fileData.size();
PassAvatarDataToManager(playerId, tmpAvatar);
if (m_avatarDownloader && m_avatarDownloader->HasDownloadResult())
{
unsigned playerId;
boost::shared_ptr<AvatarData> tmpAvatar(new AvatarData);
m_avatarDownloader->GetDownloadResult(playerId, tmpAvatar->fileData);
tmpAvatar->reportedSize = tmpAvatar->fileData.size();
PassAvatarDataToManager(playerId, tmpAvatar);
}
m_avatarTimer.expires_from_now(
boost::posix_time::milliseconds(CLIENT_AVATAR_LOOP_MSEC));
m_avatarTimer.async_wait(
boost::bind(
&ClientThread::TimerCheckAvatarDownloads, shared_from_this(), boost::asio::placeholders::error));
}
}
@@ -724,10 +790,13 @@ void
ClientThread::CreateContextSession()
{
bool validSocket = false;
// TODO ipv6
// TODO sctp
try {
boost::shared_ptr<tcp::socket> newSock(new boost::asio::ip::tcp::socket(*m_ioService, tcp::v4()));
boost::shared_ptr<tcp::socket> newSock;
if (GetContext().GetAddrFamily() == AF_INET6)
newSock.reset(new boost::asio::ip::tcp::socket(*m_ioService, tcp::v6()));
else
newSock.reset(new boost::asio::ip::tcp::socket(*m_ioService, tcp::v4()));
boost::asio::socket_base::non_blocking_io command(true);
newSock->io_control(command);
newSock->set_option(tcp::no_delay(true));
@@ -737,6 +806,8 @@ ClientThread::CreateContextSession()
newSock,
SESSION_ID_GENERIC,
*m_senderCallback)));
GetContext().SetResolver(boost::shared_ptr<boost::asio::ip::tcp::resolver>(
new boost::asio::ip::tcp::resolver(*m_ioService)));
validSocket = true;
} catch (...)
{
@@ -755,7 +826,16 @@ ClientThread::GetState()
void
ClientThread::SetState(ClientState &newState)
{
if (m_curState)
m_curState->Exit(shared_from_this());
m_curState = &newState;
m_curState->Enter(shared_from_this());
}
boost::asio::deadline_timer &
ClientThread::GetStateTimer()
{
return m_stateTimer;
}
SenderHelper &
-42
View File
@@ -1,42 +0,0 @@
/***************************************************************************
* Copyright (C) 2007 by Lothar May *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <net/servercontext.h>
ServerContext::ServerContext()
: m_protocol(0), m_addrFamily(AF_INET), m_serverPort(0)
{
}
ServerContext::~ServerContext()
{
}
SOCKET
ServerContext::GetSocket() const
{
return m_sock;
}
void
ServerContext::SetSocket(SOCKET sock)
{
m_sock = sock;
}
+8 -7
View File
@@ -165,8 +165,8 @@ ServerLobbyThread::AddConnection(boost::shared_ptr<tcp::socket> sock)
boost::bind(
&ServerLobbyThread::HandleRead,
this,
sessionData->GetId(),
boost::asio::placeholders::error,
sessionData->GetId(),
boost::asio::placeholders::bytes_transferred));
}
}
@@ -513,9 +513,10 @@ ServerLobbyThread::Main()
RegisterTimers();
try
{
m_work.reset(new boost::asio::io_service::work(*m_ioService));
m_ioService->run(); // Will only be aborted asynchronously.
m_work.reset();
{
boost::asio::io_service::work ioWork(*m_ioService);
m_ioService->run(); // Will only be aborted asynchronously.
}
// Clear all sessions.
m_sessionManager.Clear();
@@ -585,7 +586,7 @@ ServerLobbyThread::CancelTimers()
}
void
ServerLobbyThread::HandleRead(SessionId sessionId, const boost::system::error_code &error, size_t bytesRead)
ServerLobbyThread::HandleRead(const boost::system::error_code &ec, SessionId sessionId, size_t bytesRead)
{
// Find the session.
SessionWrapper session = m_sessionManager.GetSessionById(sessionId);
@@ -593,7 +594,7 @@ ServerLobbyThread::HandleRead(SessionId sessionId, const boost::system::error_co
session = m_gameSessionManager.GetSessionById(sessionId);
if (session.sessionData)
{
if (!error)
if (!ec)
{
ReceiveBuffer &buf = session.sessionData->GetReceiveBuffer();
buf.recvBufUsed += bytesRead;
@@ -625,8 +626,8 @@ ServerLobbyThread::HandleRead(SessionId sessionId, const boost::system::error_co
boost::bind(
&ServerLobbyThread::HandleRead,
this,
sessionId,
boost::asio::placeholders::error,
sessionId,
boost::asio::placeholders::bytes_transferred));
}
else
+1 -2
View File
@@ -19,7 +19,6 @@
#include <net/socket_helper.h>
#include <net/servermanager.h>
#include <net/servercontext.h>
#include <net/ircthread.h>
#include <net/connectdata.h>
#include <net/serverlobbythread.h>
@@ -39,7 +38,7 @@ using namespace std;
ServerManager::ServerManager(GuiInterface &gui, ConfigFile *config, AvatarManager &avatarManager)
: m_gui(gui), m_playerConfig(config), m_avatarManager(avatarManager)
{
m_ioService.reset(new boost::asio::io_service());
m_ioService.reset(new boost::asio::io_service);
}
ServerManager::~ServerManager()
-57
View File
@@ -1,57 +0,0 @@
/***************************************************************************
* Copyright (C) 2007 by Lothar May *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
/* Context of network server. */
#ifndef _SERVERCONTEXT_H_
#define _SERVERCONTEXT_H_
#include <net/netcontext.h>
class ServerContext : public NetContext
{
public:
ServerContext();
virtual ~ServerContext();
virtual SOCKET GetSocket() const;
void SetSocket(SOCKET sock);
int GetProtocol() const
{return m_protocol;}
void SetProtocol(int protocol)
{m_protocol = protocol;}
int GetAddrFamily() const
{return m_addrFamily;}
void SetAddrFamily(int addrFamily)
{m_addrFamily = addrFamily;}
unsigned GetServerPort() const
{return m_serverPort;}
void SetServerPort(unsigned serverPort)
{m_serverPort = serverPort;}
private:
SOCKET m_sock;
int m_protocol;
int m_addrFamily;
unsigned m_serverPort;
};
#endif
+1 -2
View File
@@ -115,7 +115,7 @@ protected:
void RegisterTimers();
void CancelTimers();
void HandleRead(SessionId sessionId, const boost::system::error_code &error, size_t bytesRead);
void HandleRead(const boost::system::error_code &ec, SessionId sessionId, size_t bytesRead);
void HandlePacket(SessionWrapper session, boost::shared_ptr<NetPacket> packet);
void HandleNetPacketInit(SessionWrapper session, const NetPacketInit &tmpPacket);
void HandleNetPacketAvatarHeader(SessionWrapper session, const NetPacketAvatarHeader &tmpPacket);
@@ -173,7 +173,6 @@ protected:
private:
boost::shared_ptr<boost::asio::io_service> m_ioService;
boost::shared_ptr<boost::asio::io_service::work> m_work;
boost::shared_ptr<ServerSenderCallback> m_senderCallback;
boost::shared_ptr<SenderHelper> m_sender;
+12 -16
View File
@@ -43,8 +43,7 @@
using namespace std;
Session::Session(GuiInterface *g, ConfigFile *c)
: currentGameNum(0), myNetClient(NULL), myNetServer(NULL), myClientIrcThread(NULL),
myGui(g), myConfig(c), myGameType(GAME_TYPE_NONE)
: currentGameNum(0), myGui(g), myConfig(c), myGameType(GAME_TYPE_NONE)
{
myQtToolsInterface = CreateQtToolsWrapper();
}
@@ -165,7 +164,7 @@ void Session::startInternetClient()
if (myConfig->readConfigInt("UseIRCLobbyChat"))
{
myClientIrcThread = new IrcThread(myGui);
myClientIrcThread.reset(new IrcThread(myGui));
myClientIrcThread->Init(
myConfig->readConfigString("IRCServerAddress"),
myConfig->readConfigInt("IRCServerPort"),
@@ -180,7 +179,7 @@ void Session::startInternetClient()
myClientIrcThread->Run();
}
myNetClient = new ClientThread(*myGui, *myAvatarManager);
myNetClient.reset(new ClientThread(*myGui, *myAvatarManager));
bool useAvatarServer = myConfig->readConfigInt("UseAvatarServer") != 0;
myNetClient->Init(
@@ -211,7 +210,7 @@ void Session::startNetworkClient(const string &serverAddress, unsigned serverPor
}
myGameType = GAME_TYPE_NETWORK;
myNetClient = new ClientThread(*myGui, *myAvatarManager);
myNetClient.reset(new ClientThread(*myGui, *myAvatarManager));
myNetClient->Init(
serverAddress,
"",
@@ -237,7 +236,7 @@ void Session::startNetworkClientForLocalServer(const GameData &gameData)
}
myGameType = GAME_TYPE_NETWORK;
myNetClient = new ClientThread(*myGui, *myAvatarManager);
myNetClient.reset(new ClientThread(*myGui, *myAvatarManager));
bool useIpv6 = myConfig->readConfigInt("ServerUseIpv6") == 1;
const char *loopbackAddr = useIpv6 ? "::1" : "127.0.0.1";
myNetClient->Init(
@@ -265,13 +264,11 @@ void Session::terminateNetworkClient()
myClientIrcThread->SignalTermination();
// Give the threads some time to terminate.
if (myNetClient->Join(NET_CLIENT_TERMINATE_TIMEOUT_MSEC))
delete myNetClient;
myNetClient.reset();
if (myClientIrcThread && myClientIrcThread->Join(NET_IRC_TERMINATE_TIMEOUT_MSEC))
delete myClientIrcThread;
myClientIrcThread.reset();
// If termination fails, leave a memory leak to prevent a crash.
myNetClient = 0;
myClientIrcThread = 0;
myGameType = GAME_TYPE_NONE;
}
@@ -297,12 +294,12 @@ void Session::startNetworkServer()
return;
}
myNetServer = new ServerManager(*myGui, myConfig, *myAvatarManager);
myNetServer.reset(new ServerManager(*myGui, myConfig, *myAvatarManager));
boost::shared_ptr<IrcThread> tmpIrcThread;
if (myConfig->readConfigInt("UseAdminIRC"))
{
tmpIrcThread = boost::shared_ptr<IrcThread>(new IrcThread(myNetServer));
tmpIrcThread = boost::shared_ptr<IrcThread>(new IrcThread(myNetServer.get()));
tmpIrcThread->Init(
myConfig->readConfigString("AdminIRCServerAddress"),
@@ -332,9 +329,8 @@ void Session::terminateNetworkServer()
myNetServer->SignalTerminationAll();
// Give the thread some time to terminate.
if (myNetServer->JoinAll(true))
delete myNetServer;
myNetServer.reset();
// If termination fails, leave a memory leak to prevent a crash.
myNetServer = 0;
}
bool Session::pollNetworkServerTerminated()
@@ -433,13 +429,13 @@ void Session::voteKick(bool doKick)
bool Session::isNetworkClientRunning() const
{
// This, and every place which calls this, is a HACK.
return myNetClient != NULL;
return myNetClient.get() != NULL;
}
bool Session::isNetworkServerRunning() const
{
// This, and every place which calls this, is a HACK.
return myNetServer != NULL;
return myNetServer.get() != NULL;
}
ServerInfo Session::getClientServerInfo(unsigned serverId) const
+3 -3
View File
@@ -106,9 +106,9 @@ private:
std::string myIrcNick;
ClientThread *myNetClient;
ServerManager *myNetServer;
IrcThread *myClientIrcThread;
boost::shared_ptr<ClientThread> myNetClient;
boost::shared_ptr<ServerManager> myNetServer;
boost::shared_ptr<IrcThread> myClientIrcThread;
boost::shared_ptr<AvatarManager> myAvatarManager;