how to unit test a simple tcp client/server on one local machine/host?

c++, sockets, testing

Solution

Yes, it's possible. There is no such restriction that a server and a client must be different processes. One thread can open/listen a socket and other thread can connect to it.

Problem

I am currently wrapping BSD sockets for the first time and also unit test my results along the way. Anyways I came across a problem while writing a simple test to test my Acceptor and TcpSocket class which is related to reusing the local host address, i.e. Pseudocode: ``` //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"))); ``` Is it even possible to listen and connect on the same host/port? Is there any way to run a simple client/server test on the same machine/host? Thanks! EDIT: Cool, things work now! Just for reference, I also noticed in the process that you don't even need to use a thread, even if you use blocking sockets to perform a simple test, if you decouple listen from accept like this: ``` //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; ``` building the tests like this allows for nice and simple test cases even for the blocking functions.

Original source