我目前首次封裝了BSD套接字,並且還一路單元測試了我的結果。反正我碰到一個問題就來了,而寫一個簡單的測試來測試我的接受器和這與重用本地主機地址的TCPSocket類,即如何在一臺本地機器/主機上測試一個簡單的tcp客戶機/服務器?
僞代碼:
//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;
像這樣構建測試,即使對於阻塞函數也可以提供很好且簡單的測試用例。
我不認爲你正在嘗試是可能的。你應該做的是將行爲從觸發它們的數據包中分離出來,然後編寫測試用例來測試每個行爲,而不管它們是如何被調用的。然後,您可以使用您編寫/借用的工具測試TCP層,如果您的代碼結構正確,應該會更容易。 – blockchaindev