简体   繁体   English

服务器可以直接连接它所连接的两个套接字吗?

[英]Can a server directly connect two sockets that it is connected to?

Say I have a public server on the Internet, written in C, that is connected to two independent clients. 假设我在Internet上有一个用C编写的公共服务器,该服务器连接到两个独立的客户端。 Both clients initiated the connection. 两个客户端都启动了连接。 One client is (eg) an iOS app, the other is a native Windows app. 一个客户端是(例如)iOS应用程序,另一个是本地Windows应用程序。

The purpose of my server is to allow these clients to send text messages to each other. 我服务器的目的是允许这些客户端相互发送文本消息。 Client 1 sends a message, the server receives it, and then forwards it onto Client 2. The same thing happens in reverse when Client 2 sends a message. 客户端1发送一条消息,服务器接收它,然后将其转发到客户端2。当客户端2发送一条消息时,情况相反。

This feels inefficient. 感觉效率低下。 What I would really like is for both of these connections to contact the server and then for the server to connect these two clients directly to each other - after which my server can forget both clients as they are responsible for communicating with each other. 我真正想要的是让这两个连接都与服务器联系,然后让服务器将这两个客户端直接彼此连接-之后,我的服务器会忘记这两个客户端,因为它们负责彼此通信。 My server is then free to connect up other clients in the same way. 然后,我的服务器可以自由以相同的方式连接其他客户端。

My question is: is this even possible (with TCP and/or UDP)? 我的问题是:(使用TCP和/或UDP)这是否可能? Neither client necessarily has a public IP address, which is why they have to initiate the connection. 两个客户端都不一定具有公共IP地址,这就是为什么他们必须启动连接的原因。 Once the connection is established however, my server knows the connection address of both clients. 但是,一旦建立连接,我的服务器就会知道两个客户端的连接地址。 Is there a way to connect them together? 有没有办法将它们连接在一起? A syscall that can do this sort of thing, perhaps? 可以执行此类操作的系统调用吧?

No, you can not join two existing TCP connections to one. 不,您不能将两个现有的TCP连接加入其中。

There are 2 options: 有2个选项:

1) Keep your server in the middle as it already is. 1)将服务器放置在中间位置。 It should not be problem, if you don't have thousands of clients under one server. 如果您在一台服务器上没有数千个客户端,那应该没问题。

2) Server could send control messages to clients, and order those open new TCP connection between each other. 2)服务器可以向客户端发送控制消息,并命令那些客户端之间打开新的TCP连接。 Server should also make decision which of the two clients must be initiator of the new TCP connection. 服务器还应确定两个客户端中的哪个客户端必须是新TCP连接的发起者。

Option 2 is problematic, because client may have firewall rule that prevents in coming connection to the wanted port. 选项2有问题,因为客户端可能具有阻止进入所需端口的防火墙规则。 Also NAT would cause problems. NAT也会引起问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM