如何在一台本地机器/主机上对一个简单的tcp客户端/服务器进行单元测试?

时间:2012-05-09 14:10:50

标签: c++ sockets testing

我目前正在首次包装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")));

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

谢谢!

修改

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

//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;

构建这样的测试可以实现简单的测试用例,即使对于阻塞函数也是如此。

1 个答案:

答案 0 :(得分:3)

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