AsyncTcpServer_demo.cpp
An example of how to use the
Async::TcpServer class
#include <iostream>
#include <AsyncCppApplication.h>
#include <AsyncTcpServer.h>
using namespace std;
using namespace Async;
class MyClass : public SigC::Object
{
public:
MyClass(void)
{
server = new TcpServer("12345");
server->clientConnected.connect(slot(*this, &MyClass::onClientConnected));
server->clientDisconnected.connect(
slot(*this, &MyClass::onClientDisconnected));
cout << "Connect using: \"telnet localhost 12345\" from "
"another console\n";
}
~MyClass(void)
{
delete server;
}
private:
TcpServer *server;
void onClientConnected(TcpConnection *con)
{
cout << "Client " << con->remoteHost() << ":"
<< con->remotePort() << " connected, "
<< server->numberOfClients() << " clients connected\n";
con->dataReceived.connect(slot(*this, &MyClass::onDataReceived));
con->write("Hello, client!\n", 15);
}
void onClientDisconnected(TcpConnection *con,
TcpConnection::DisconnectReason reason)
{
cout << "Client " << con->remoteHost().toString() << ":"
<< con->remotePort() << " disconnected,"
<< server->numberOfClients() << " clients connected\n";
}
int onDataReceived(TcpConnection *con, void *buf, int count)
{
char *str = static_cast<char *>(buf);
string data(str, str+count);
cout << data;
string dataOut = string("You said: ") + data;
server->writeOnly(con, dataOut.c_str(), dataOut.size());
if (server->numberOfClients() > 1)
{
dataOut = string("He said : ") + data;
server->writeExcept(con, dataOut.c_str(), dataOut.size());
dataOut = string("To all : ") + data;
server->writeAll(dataOut.c_str(), dataOut.size());
}
return count;
}
};
int main(int argc, char **argv)
{
CppApplication app;
MyClass my_class;
app.exec();
}