If you need a multithreaded TCP server, then out of the box Poco :: Net :: TCPServer will do it - it is multithreaded inside. Start by defining a connection, this one will just send everything you send to it:
class EchoConnection: public TCPServerConnection { public: EchoConnection(const StreamSocket& s): TCPServerConnection(s) { } void run() { StreamSocket& ss = socket(); try { char buffer[256]; int n = ss.receiveBytes(buffer, sizeof(buffer)); while (n > 0) { ss.sendBytes(buffer, n); n = ss.receiveBytes(buffer, sizeof(buffer)); } } catch (Poco::Exception& exc) { std::cerr << "EchoConnection: " << exc.displayText() << std::endl; } } };
Then start the server and send it some data:
TCPServer srv(new TCPServerConnectionFactoryImpl<EchoConnection>()); srv.start(); SocketAddress sa("localhost", srv.socket().address().port()); StreamSocket ss(sa); std::string data("hello, world"); ss.sendBytes(data.data(), (int) data.size()); char buffer[256] = {0}; int n = ss.receiveBytes(buffer, sizeof(buffer)); std::cout << std::string(buffer, n) << std::endl; srv.stop();
source share