BaseServer

juhgiyo edited this page Nov 15, 2012 · 12 revisions

BaseServer Usage

Linking

// SomeServer.h
#include "epse.h"
using namespace epl;
using namespace epse;

Server Declaration Example

class SomeServer : public BaseServer
{
public:
   SomeServer(const TCHAR * port=_T("1234"));
   SomeServer(const SomeServer b);
   virtual ~SomeServer();
   SomeServer & operator=(const SomeServer&b)
   {
      if(this!=&b)
      {
         BaseServer::operator =(b);
      }
      return *this;
   }
protected:
   virtual BaseServerWorker* createNewWorker();
};

Server Implementation Example

#include "SomeServer.h"
#include "SomeServerWorker.h"
SomeServer::SomeServer(const TCHAR * port) :BaseServer(port)
{
}

SomeServer::SomeServer(const SomeServer& b):BaseServer(b)
{
}

SomeServer::~SomeServer()
{
}

BaseServerWorker* SomeServer::createNewWorker()
{
   // create new worker that is related to SomeServer and return the pointer
   // this will automatically deleted when Server stops or Client disconnects
   return new SomeServerWorker();
}

Server Start/Stop Example

#include "SomeServer.h"
SomeServer m_server=SomeServer(_T("1020"));
...
if(m_server.StartServer())
{
   // server started
}
else
{
   // server failed starting
}

...
if(m_server.IsServerStarted()) // check if server is started
{
   m_server.StopServer();  // Disconnect all clients connected and stop listening
}
    • Note that a server object creates one "listening thread", and for each client connected, the "listening thread" creates a thread (BaseServerWorker object) to communicate with the client.

Server Broadcast Example

#include "SomeServer.h"
SomeServer m_server=SomeServer(_T("1020"));
...
// Server Starts
// See above example
...
if(m_server.IsServerStarted()) // check if server is started
{
   	PacketContainer<SendPacketType> packetContainer=PacketContainer<SendPacketType>();
    packetContainer.GetPacketPtr()->packetType=SEND_PACKET_TYPE_DIDSOMETHING;
    Packet sendPacket=Packet(reinterpret_cast<const void*>(packetContainer.GetPacketPtr()),packetContainer.GetPacketByteSize(),false);
    m_server.Broadcast(sendPacket);
}
    • For the details of Packet class, see Packet

Server ShutdownAllClient Example

#include "SomeServer.h"
SomeServer m_server=SomeServer(_T("1020"));
...
// Server Starts
// See above example
...
if(m_server.IsServerStarted()) // check if server is started
{
   ShutdownAllClient(); // Disconnects all clients connected.
}
  • This disconnects all clients, connected, from the server.