如果您想要的只是多线程 TCP 服务器,那么“开箱即用” Poco::Net::TCPServer就可以了——它在内部是多线程的。从定义连接开始,这个连接只会回显您发送给它的任何内容:
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; }
}
};
然后,运行服务器并向其发送一些数据:
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();