仅通过建立一次TCP连接将Recv从客户端发送到服务器套接字

Send Recv from client to server socket by establish TCP Connection only once

本文关键字:客户端 Recv 套接字 服务器 连接 TCP 建立 一次      更新时间:2023-10-16

我正在C++研究客户端/服务器解决方案。

从客户端,我向我的服务器发送数据,从这个服务器发送到另一个服务器。我能够配置端口和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 = %stport_client = %stport_client_int = %dn", 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 - %sn", message.c_str());
stream_client->send(input, sizeof(input));
printf("sent - %sn", input);
len = stream_client->receive(line, sizeof(line));
line[len] = NULL;
printf("received - %sn", line);
delete stream_client;
}
//Code Additon by Srini ends here
stream->send(line, len);
printf("thread %lu, echoed '%s' back to the clientn",
(long unsigned int)self(), line);
}

从客户端接收、发送到服务器、从服务器接收和发送到客户端的完整线程代码显示在以下链接中:

https://pastebin.com/UmPQJ70w

如何更改设计流程? 即使在客户端/服务器程序的基本图中。 当客户端调用connect()时,服务器每次都会调用accept(),然后发生发送/接收。 那么,可以做些什么来修改流,以便客户端只能连接一次?

您的中间服务器(充当代理,所以让我们这样称呼它(需要维护与其他服务器的单个连接,并在代理与其客户端之间完成消息传递并行委派消息传递。

我建议创建一个单独的线程,其唯一任务是维护与其他服务器的连接,并使用它发送/接收消息。

当客户端向代理发送消息时,请将该消息放在线程安全队列中的某个位置。 让线程定期检查队列,并将任何排队的消息发送到其他服务器。

当其他服务器向您的代理发送消息时,线程可以接收该消息并将其转发到相应的客户端。