Cleaned up the code. Added client exception for error handling.

This commit is contained in:
lotodore
2007-02-18 11:26:57 +00:00
parent e6c6fa0eee
commit 9ec3e020dd
9 changed files with 173 additions and 71 deletions
+24 -7
View File
@@ -19,6 +19,19 @@
#include "thread.h" #include "thread.h"
// This is ugly, but I can't help it.
#define ADD_MSEC_TO_XTIME(__xt, __msec) \
{ \
__xt.sec += __msec / 1000; \
__xt.nsec += (__msec % 1000) * 1000; \
if (__xt.nsec > NANOSECONDS_PER_SECOND) \
{ \
__xt.sec++; \
__xt.nsec -= NANOSECONDS_PER_SECOND; \
} \
}
// Helper class for thread creation. // Helper class for thread creation.
class ThreadStarter class ThreadStarter
{ {
@@ -68,13 +81,7 @@ Thread::Join(unsigned msecTimeout)
// Calculate time after timeout // Calculate time after timeout
boost::xtime t; boost::xtime t;
boost::xtime_get(&t, boost::TIME_UTC); boost::xtime_get(&t, boost::TIME_UTC);
t.sec += msecTimeout / 1000; ADD_MSEC_TO_XTIME(t, msecTimeout);
t.nsec += (msecTimeout % 1000) * 1000;
if (t.nsec > NANOSECONDS_PER_SECOND)
{
t.sec++;
t.nsec -= NANOSECONDS_PER_SECOND;
}
// Wait for the termination of the application code. // Wait for the termination of the application code.
boost::timed_mutex::scoped_timed_lock lock(m_isTerminatedMutex, t); boost::timed_mutex::scoped_timed_lock lock(m_isTerminatedMutex, t);
@@ -94,6 +101,16 @@ Thread::Join(unsigned msecTimeout)
return tmpIsTerminated; return tmpIsTerminated;
} }
void
Thread::Msleep(unsigned msecs)
{
boost::xtime t;
boost::xtime_get(&t, boost::TIME_UTC);
ADD_MSEC_TO_XTIME(t, msecs);
boost::thread::sleep(t);
}
void void
Thread::MainWrapper() Thread::MainWrapper()
{ {
+3
View File
@@ -46,6 +46,9 @@ public:
// You SHOULD always call join for a thread. // You SHOULD always call join for a thread.
bool Join(unsigned msecTimeout); bool Join(unsigned msecTimeout);
// Sleep the currently active thread.
static void Msleep(unsigned msecs);
protected: protected:
// Startup function. // Startup function.
+2 -2
View File
@@ -28,8 +28,8 @@
class ClientData class ClientData
{ {
public: public:
ClientData() ClientData();
: sockfd(INVALID_SOCKET), addrFamily(AF_INET), serverPort(0) {} ~ClientData();
int GetServerAddrSize() const int GetServerAddrSize() const
{ {
return addrFamily == AF_INET6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in); return addrFamily == AF_INET6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in);
+40
View File
@@ -0,0 +1,40 @@
/***************************************************************************
* 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. *
***************************************************************************/
/* Exception class for client errors. */
#ifndef _CLIENTEXCEPTION_H_
#define _CLIENTEXCEPTION_H_
class ClientException
{
public:
ClientException(int errorId, int osErrorCode)
: m_errorId(errorId), m_osErrorCode(osErrorCode) {}
int GetErrorId() const {return m_errorId;}
int GetOsErrorCode() const {return m_osErrorCode;}
private:
int m_errorId;
int m_osErrorCode;
};
#endif
+5 -5
View File
@@ -35,7 +35,7 @@ public:
virtual ~ClientState(); virtual ~ClientState();
// Main processing function of the current state. // Main processing function of the current state.
virtual void Process(ClientThread &client, ClientCallback &gui) = 0; virtual int Process(ClientThread &client) = 0;
}; };
// State: Initialization. // State: Initialization.
@@ -48,7 +48,7 @@ public:
virtual ~ClientStateInit(); virtual ~ClientStateInit();
// Some basic initialization (socket creation, basic checks). // Some basic initialization (socket creation, basic checks).
virtual void Process(ClientThread &client, ClientCallback &gui); virtual int Process(ClientThread &client);
protected: protected:
@@ -66,7 +66,7 @@ public:
virtual ~ClientStateResolve(); virtual ~ClientStateResolve();
// "Poll" for the completion of the name resolution. // "Poll" for the completion of the name resolution.
virtual void Process(ClientThread &client, ClientCallback &gui); virtual int Process(ClientThread &client);
protected: protected:
@@ -84,7 +84,7 @@ public:
virtual ~ClientStateConnect(); virtual ~ClientStateConnect();
// "Poll" for the completion of the TCP/IP connect call. // "Poll" for the completion of the TCP/IP connect call.
virtual void Process(ClientThread &client, ClientCallback &gui); virtual int Process(ClientThread &client);
protected: protected:
@@ -102,7 +102,7 @@ public:
virtual ~ClientStateFinal(); virtual ~ClientStateFinal();
// sleep. // sleep.
virtual void Process(ClientThread &client, ClientCallback &gui); virtual int Process(ClientThread &client);
protected: protected:
+33
View File
@@ -0,0 +1,33 @@
/***************************************************************************
* 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/clientdata.h>
ClientData::ClientData()
: sockfd(INVALID_SOCKET), addrFamily(AF_INET), serverPort(0)
{
bzero(clientAddr, sizeof(clientAddr));
}
ClientCallback::~ClientCallback()
{
if (sockfd != INVALID_SOCKET)
CLOSESOCKET(sockfd);
}
+41 -50
View File
@@ -20,8 +20,8 @@
#include <net/clientstate.h> #include <net/clientstate.h>
#include <net/clientthread.h> #include <net/clientthread.h>
#include <net/clientdata.h> #include <net/clientdata.h>
#include <net/clientexception.h>
#include <net/socket_msg.h> #include <net/socket_msg.h>
#include <net/clientcallback.h>
#include <stdexcept> #include <stdexcept>
#include <sstream> #include <sstream>
@@ -50,41 +50,30 @@ ClientStateInit::~ClientStateInit()
{ {
} }
void int
ClientStateInit::Process(ClientThread &client, ClientCallback &cb) ClientStateInit::Process(ClientThread &client)
{ {
ClientData &data = client.GetData(); ClientData &data = client.GetData();
if (data.serverAddr.empty()) if (data.serverAddr.empty())
{ throw ClientException(ERR_SOCK_SERVERADDR_NOT_SET, 0);
cb.SignalNetClientError(ERR_SOCK_SERVERADDR_NOT_SET, 0);
throw runtime_error("ClientStateInit"); // TODO: own exception
}
if (data.serverPort < 1024) if (data.serverPort < 1024)
{ throw ClientException(ERR_SOCK_INVALID_PORT, 0);
cb.SignalNetClientError(ERR_SOCK_INVALID_PORT, 0);
throw runtime_error("ClientStateInit");
}
data.sockfd = socket(data.addrFamily, SOCK_STREAM, 0); data.sockfd = socket(data.addrFamily, SOCK_STREAM, 0);
if (!IS_VALID_SOCKET(data.sockfd)) if (!IS_VALID_SOCKET(data.sockfd))
{ throw ClientException(ERR_SOCK_CREATION_FAILED, SOCKET_ERRNO());
cb.SignalNetClientError(ERR_SOCK_CREATION_FAILED, SOCKET_ERRNO());
throw runtime_error("ClientStateInit");
}
#if 0 #if 0
unsigned long mode = 1; unsigned long mode = 1;
if (IOCTLSOCKET(data.sockfd, FIONBIO, &mode) == SOCKET_ERROR) if (IOCTLSOCKET(data.sockfd, FIONBIO, &mode) == SOCKET_ERROR)
{ throw ClientException(ERR_SOCK_CREATION_FAILED, SOCKET_ERRNO());
cb.SignalNetClientError(ERR_SOCK_CREATION_FAILED, SOCKET_ERRNO());
throw runtime_error("ClientStateInit");
}
#endif #endif
cb.SignalNetClientSuccess(MSG_SOCK_INIT_DONE);
client.SetState(ClientStateResolve::Instance()); client.SetState(ClientStateResolve::Instance());
return MSG_SOCK_INIT_DONE;
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@@ -104,36 +93,45 @@ ClientStateResolve::~ClientStateResolve()
{ {
} }
void int
ClientStateResolve::Process(ClientThread &client, ClientCallback &cb) ClientStateResolve::Process(ClientThread &client)
{ {
ClientData &data = client.GetData(); ClientData &data = client.GetData();
data.clientAddr.ss_family = data.addrFamily; data.clientAddr.ss_family = data.addrFamily;
// Treat the server address as numbers first. // Treat the server address as numbers first.
if (socket_string_to_addr(data.serverAddr.c_str(), data.addrFamily, (struct sockaddr *)&data.clientAddr, data.GetServerAddrSize())) if (socket_string_to_addr(
data.serverAddr.c_str(),
data.addrFamily,
(struct sockaddr *)&data.clientAddr,
data.GetServerAddrSize()))
{ {
// Set the port. // Success - but we still need to set the port.
if (!socket_set_port(data.serverPort, data.addrFamily, (struct sockaddr *)&data.clientAddr, data.GetServerAddrSize())) if (!socket_set_port(data.serverPort, data.addrFamily, (struct sockaddr *)&data.clientAddr, data.GetServerAddrSize()))
{ throw ClientException(ERR_SOCK_SET_PORT_FAILED, 0);
cb.SignalNetClientError(ERR_SOCK_SET_PORT_FAILED, 0);
throw runtime_error("ClientStateResolve");
}
} }
else else
{ {
// This did not work out - try name resolution. // This did not work out - try name resolution.
ostringstream tmpStr; ostringstream tmpStr;
tmpStr << data.serverPort; tmpStr << data.serverPort;
if (!socket_resolve(data.serverAddr.c_str(), tmpStr.str().c_str(), data.addrFamily, SOCK_STREAM, 0, (struct sockaddr *)&data.clientAddr, data.GetServerAddrSize())) // TODO: start in a separate thread, since it is blocking.
if (!socket_resolve(
data.serverAddr.c_str(),
tmpStr.str().c_str(),
data.addrFamily,
SOCK_STREAM,
0,
(struct sockaddr *)&data.clientAddr,
data.GetServerAddrSize()))
{ {
cb.SignalNetClientError(ERR_SOCK_RESOLVE_FAILED, 0); // TODO: use errno value throw ClientException(ERR_SOCK_RESOLVE_FAILED, 0);
throw runtime_error("ClientStateResolve");
} }
} }
cb.SignalNetClientSuccess(MSG_SOCK_RESOLVE_DONE);
client.SetState(ClientStateConnect::Instance()); client.SetState(ClientStateConnect::Instance());
return MSG_SOCK_RESOLVE_DONE;
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@@ -153,18 +151,17 @@ ClientStateConnect::~ClientStateConnect()
{ {
} }
void int
ClientStateConnect::Process(ClientThread &client, ClientCallback &cb) ClientStateConnect::Process(ClientThread &client)
{ {
ClientData &data = client.GetData(); ClientData &data = client.GetData();
if (!IS_VALID_CONNECT(connect(data.sockfd, (struct sockaddr *)&data.clientAddr, data.GetServerAddrSize()))) if (!IS_VALID_CONNECT(connect(data.sockfd, (struct sockaddr *)&data.clientAddr, data.GetServerAddrSize())))
{ throw ClientException(ERR_SOCK_CONNECT_FAILED, SOCKET_ERRNO());
cb.SignalNetClientError(ERR_SOCK_CONNECT_FAILED, SOCKET_ERRNO());
throw runtime_error("ClientStateResolve");
}
cb.SignalNetClientSuccess(MSG_SOCK_RESOLVE_DONE);
client.SetState(ClientStateFinal::Instance()); client.SetState(ClientStateFinal::Instance());
return MSG_SOCK_RESOLVE_DONE;
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@@ -184,16 +181,10 @@ ClientStateFinal::~ClientStateFinal()
{ {
} }
void int
ClientStateFinal::Process(ClientThread &client, ClientCallback &cb) ClientStateFinal::Process(ClientThread &client)
{ {
boost::xtime t; Thread::Msleep(10);
boost::xtime_get(&t, boost::TIME_UTC);
t.nsec += 10000; return MSG_SOCK_INTERNAL_PENDING;
if (t.nsec > NANOSECONDS_PER_SECOND)
{
t.sec++;
t.nsec -= NANOSECONDS_PER_SECOND;
}
boost::thread::sleep(t);
} }
+21 -7
View File
@@ -20,6 +20,10 @@
#include <net/clientthread.h> #include <net/clientthread.h>
#include <net/clientstate.h> #include <net/clientstate.h>
#include <net/clientdata.h> #include <net/clientdata.h>
#include <net/clientcallback.h>
#include <net/clientexception.h>
#include <net/socket_msg.h>
#include <cassert> #include <cassert>
@@ -30,7 +34,6 @@ ClientThread::ClientThread(ClientCallback &cb)
: m_curState(NULL), m_callback(cb) : m_curState(NULL), m_callback(cb)
{ {
m_data.reset(new ClientData); m_data.reset(new ClientData);
m_curState = &CLIENT_INITIAL_STATE::Instance();
} }
ClientThread::~ClientThread() ClientThread::~ClientThread()
@@ -42,18 +45,29 @@ ClientThread::Init(const string &serverAddress, unsigned serverPort, bool ipv6,
{ {
if (IsRunning()) if (IsRunning())
return; // TODO: throw exception return; // TODO: throw exception
m_data->addrFamily = ipv6 ? AF_INET6 : AF_INET;
m_data->serverAddr = serverAddress; ClientData &data = GetData();
m_data->serverPort = serverPort;
m_data->password = pwd; data.addrFamily = ipv6 ? AF_INET6 : AF_INET;
data.serverAddr = serverAddress;
data.serverPort = serverPort;
data.password = pwd;
} }
void void
ClientThread::Main() ClientThread::Main()
{ {
while (!ShouldTerminate()) SetState(CLIENT_INITIAL_STATE::Instance());
try {
while (!ShouldTerminate())
{
int msg = GetState().Process(*this);
if (msg != MSG_SOCK_INTERNAL_PENDING)
m_callback.SignalNetClientSuccess(msg);
}
} catch (const ClientException &e)
{ {
GetState().Process(*this, m_callback); m_callback.SignalNetClientError(e.GetErrorId(), e.GetOsErrorCode());
} }
} }
+4
View File
@@ -27,6 +27,10 @@
#define ERR_SOCK_RESOLVE_FAILED 12 #define ERR_SOCK_RESOLVE_FAILED 12
#define ERR_SOCK_CONNECT_FAILED 13 #define ERR_SOCK_CONNECT_FAILED 13
// This is an internal message which is not reported.
#define MSG_SOCK_INTERNAL_PENDING 0
// The following messages are reported.
#define MSG_SOCK_INIT_DONE 1 #define MSG_SOCK_INIT_DONE 1
#define MSG_SOCK_RESOLVE_DONE 2 #define MSG_SOCK_RESOLVE_DONE 2
#define MSG_SOCK_CONNECT_DONE 3 #define MSG_SOCK_CONNECT_DONE 3