Multithreaded TCP server with POCO C ++ libraries

I am trying to develop a TCP server with POCO C ++ libraries. I found some examples here . At first I tried an example from Alex, but the shutdown event did not work. EchoServer has the same problem. So, I tried the Cesar Ortiz example and got an unusual problem. After a while, the server displays an error message:

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

And the connections received a connection timeout error, as well as new connections. The eventhandler semantics example is more correct, but I don’t know how I can fix the shutdown event.

+6
source share
1 answer

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(); 
+12
source

Source: https://habr.com/ru/post/944821/


All Articles