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