3

我目前是第一次包装 BSD 套接字,并在此过程中对我的结果进行单元测试。无论如何,我在编写一个简单的测试来测试与重用本地主机地址相关的 Acceptor 和 TcpSocket 类时遇到了一个问题,即

伪代码:

//server thread
{
    //binds, listens and accepts on port 50716 on localhost
    TcpAcceptor acceptor(Resolver::fromService("50716"));
    //i get a ECONNREFUSED error inside the accept function when trying to create newSock
    TcpSocket newSock = acceptor.accept();
}

//connect in the main thread
TcpSocket connectionSocket(Resolver::resolve(Resolver::Query("localhost", "50716")));

甚至可以在同一个主机/端口上监听和连接吗?有没有办法在同一台机器/主机上运行简单的客户端/服务器测试?

谢谢!

编辑:

酷,现在一切正常!仅供参考,我还注意到在这个过程中你甚至不需要使用线程,即使你使用阻塞套接字来执行一个简单的测试,如果你像这样将监听与接受解耦:

//server socket
TcpAcceptor acceptor;
acceptor.bind(Resolver::fromService("0"));
acceptor.listen();

//client socket, blocks until connection is established
TcpSocket clientSock(SocketAddress("127.0.0.1", acceptor.address().port()));

//accept the connection, blocks until one accept is done
TcpSocket connectionSock = acceptor.accept();

//send a test message to the client
size_t numBytesSent = connectionSock.send(ByteArray("Hello World!"));

//read the message on the client socket
ByteArray msg(12);
size_t bytesReceived = clientSock.receive(msg);
std::cout<<"Num Bytes received: "<<bytesReceived<<std::endl;
std::cout<<"Message: "<<msg<<std::endl;

像这样构建测试允许很好和简单的测试用例,即使是阻塞功能。

4

1 回答 1

4

是的,这是可能的。没有服务器和客户端必须是不同进程的限制。一个线程可以打开/侦听套接字,而其他线程可以连接到它。

于 2012-05-09T14:38:28.037 回答