Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithread TCP Server with POCO C++ libraries

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.

like image 534
Valera A. Avatar asked May 12 '13 17:05

Valera A.


1 Answers

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();
like image 120
Alex Avatar answered Oct 23 '22 19:10

Alex