DServer Example
#include "Dasyne.hpp"
#include <iostream>
using namespace std;
using namespace libdasyne;
class Client;
const uint16_t PORT_NUMBER = 5127;static bool allOK = true;static DBuffer reply;static vector<Client*> theClients;
class Client : public DClient
{
public: Client(DEngine *newNetEngine,
boost::asio::ip::tcp::socket *newSocket) : DClient(newNetEngine, newSocket)
{
}
private: void receiveHandler(DBuffer &theData)
{
cout << "Received: " << theData.toString() << endl;
send(reply);
} void errorHandler(string message)
{
cout << "Client disconnected: " << message << endl;
}};
class SimpleServer : public DServer
{
public: SimpleServer(DEngine *newNetEngine) : DServer(newNetEngine)
{
}
private: void connectHandler(boost::asio::ip::tcp::socket *newSocket)
{
Client *newClient = new Client(netEngine, newSocket);
cout << "A client connected from " << newClient->getRemoteAddress() << endl;
theClients.push_back(newClient);
} void errorHandler(string errMsg)
{
cout << errMsg << endl;
allOK = false;
}};
int main(int argc,
char *argv[])
{
DEngine netEngine; SimpleServer *myServer = new SimpleServer(&netEngine); string userText; int eventsRun = 0; if (allOK)
{
if (!myServer->bind(libdasyne::DA_IPV4, PORT_NUMBER))
{
allOK = false;
cout << "Couldn't bind: " << myServer->getErrMsg() << endl;
} } if (allOK)
{
cout << "Enter a message to be sent to clients: " << endl;
getline(cin, userText);
reply.appendString(userText);
} if (allOK)
{
if (myServer->startListening())
cout << "Listening for TCP connections, hit Ctrl-C to exit." << endl;
else
{
allOK = false;
cout << "Couldn't listen: " << myServer->getErrMsg() << endl;
} } while (allOK)
{
eventsRun = netEngine.update(-1);
if (eventsRun < 0)
{
cout << netEngine.getErrMsg();
allOK = false;
} else if (eventsRun == 0)
DEngine::sleep(1);
} for (unsigned int i = 0; i < theClients.size(); i++)
delete theClients.at(i);
theClients.clear();
delete myServer;
return 0;
}
Back to Contents