我正在使用C++的客戶端/服務器解決方案。通過建立TCP連接只發送一次Recv從客戶端到服務器套接字
從客戶端,我發送數據到我的服務器,並從這臺服務器發送到另一臺服務器。我可以配置端口和IP地址,並且能夠成功發送。
但是,另一臺服務器(不在我的身邊)只需要從我身邊建立一個TCP連接,之後只需要發送和接收數據。
如果我連接了兩次(同時從兩個客戶端說出),則表明連接被拒絕。
部分代碼如下所示:
while ((len = stream->receive(input, sizeof(input)-1)) > 0)
{
input[len] = NULL;
//Code Addition by Srini starts here
//Client declaration
TCPConnector* connector_client = new TCPConnector();
printf("ip_client = %s\tport_client = %s\tport_client_int = %d\n", ip_client.c_str(), port_client.c_str(),atoi(port_client.c_str()));
TCPStream* stream_client = connector_client->connect(ip_client.c_str(), atoi(port_client.c_str()));
//Client declaration ends
if (stream_client)
{
//message = "Is there life on Mars?";
//stream_client->send(message.c_str(), message.size());
//printf("sent - %s\n", message.c_str());
stream_client->send(input, sizeof(input));
printf("sent - %s\n", input);
len = stream_client->receive(line, sizeof(line));
line[len] = NULL;
printf("received - %s\n", line);
delete stream_client;
}
//Code Additon by Srini ends here
stream->send(line, len);
printf("thread %lu, echoed '%s' back to the client\n",
(long unsigned int)self(), line);
}
完整螺紋代碼,其中從客戶端接收,發送到服務器,從服務器接收,並且發送到客戶端在下面的鏈接被示出:
如何更改我的設計流程?即使在客戶端/服務器程序的基本圖中。當客戶端調用connect()
時,服務器每次調用accept()
,然後發送/接收。那麼,可以做些什麼來修改流程,以便客戶端只能連接一次?