Multithread TCP Server with POCO C++ libraries

Valera A. picture Valera A. · May 12, 2013 · Viewed 11.5k times · Source

I'm trying to develop a TCP Server with POCO C++ libraries. I found some examples here. At first I tried example from Alex but shutdown event didn't work. EchoServer have the same problem. So, then I tried Cesar Ortiz example and got a unusual problem. After some time server throws an error:

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
["src/ErrorHandler.cpp", line 60]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

And connections got connection timeout error, new connections as well. Example with eventhandler semeed more correct, but I don't know how can I fix shutdown event.

Answer

Alex picture Alex · May 15, 2013

If all you want is multi-threaded TCP server, then "out of the box" Poco::Net::TCPServer will do - it is multi-threaded internally. Start with defining the connection, this one will just echo back whatever 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, run 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();