问题描述
我想做的是监听5000的套接字,该套接字与代码完美结合
What i am trying to do is listen to a socket of 5000, which works perfectly with the code
TcpListener listener = new TcpListener(IPAddress.Any, 5000);
NetworkStream Network;
TcpClient client;
client = listener.AcceptTcpClient();
但是当服务器有两个连接到服务器的客户端时,它们都监听多线程传输的同一条消息,我不希望发生这种情况,因为与它们彼此读取它们正在从网络流中删除字节
but when the server has two clients that connect to the server they both listen to the same message coming through as they are multi threaded, i dont want this to happen because with them reading each other they are removing bytes from the network stream.
所以我的问题是,在最终建立连接之前,侦听器是否有办法监听任何IP,那么一旦建立连接,线程将仅侦听该IP地址?
so my question is, is there a way for the listener to listen to any ip until it finally receives a connection, then once the connection has been made the thread only listens to that ip address??
谢谢
推荐答案
TCP不能那样工作.创建TCP套接字时,请绑定到端口A,然后监听:
TCP does not work that way.When you create a TCP socket, bind to port A, and listen what you have is :
- 端口A上的监听套接字
一个客户端连接到服务器,结果是克隆了侦听套接字,克隆是套接字对的一部分,另一个套接字是连接套接字. 克隆"插座称为维修插座.最终结果:
A client connects to the server, what happens is that the listening socket is cloned, the clone is part of a socket pair, the other socket is the connecting socket. The 'cloned' socket is called the servicing socket. End result :
- 端口A上的监听套接字(仍然存在,您没有将其关闭)
- 端口A上的服务插座,但是是一对插座的一部分. (IPA(A),IPB(B))
套接字对可识别连接!当在TCP级别接收到某些内容时,还将检查源ip地址和端口,因此,将标识正确的服务套接字,该套接字将在接收发生的位置进行.您永远不会在监听套接字上接收数据.
The socket pair identifies the connection! When something is received at TCP level, the source ip address and port are also checked and as such the right servicing socket is identified where upon the reception will take place.You never ever receive data on a listening socket.
如果另一个客户端连接,您将获得一个不同的IP地址和端口:
If another client connects you get this, assuming a different ip address and port:
- 端口A上的监听套接字(仍然存在,您没有关闭它)
- 端口A上的服务插座,但是是一对插座的一部分. (IPA(A),IPB(B))
- 端口A上的服务插座,但是是一对插座的一部分. (IPA(A),IPC(C))
,并且这假设没有连接被关闭.您现在可以看到服务器系统上有3个插槽,所有插槽都使用相同的端口.每个已建立的连接1个侦听插槽和一个维修插槽.即每个客户.每个连接都是不同的,正确的套接字将接收属于该连接的数据.连接中只有2个端点,并且连接是双向的.
and this is assuming that no connections are closed. You see now you have 3 sockets on your server system, all using the same port. 1 listening socket, and a servicing socket per connection that is being establised. ie per client. Each connection is distinct, the right socket will receive data that belongs to the connection. There are only 2 ends in a connection, and connections are bidirectional.
TCP有点复杂,您可能会发现我的解释令人生畏,在这种情况下,您应该尝试在书籍或互联网上阅读有关TCP的更多信息.套接字编程也是一本有趣的文章,因为仅对TCP的说明不能解释套接字级别的情况.
TCP is a bit complex, you may find my explanation daunting in which case you should try to read more about TCP in books, or on the internet. Also socket programming is an interesting read because a mere explanation of TCP does not explain what happens at socket level.
这篇关于Tcp侦听器和客户端侦听特定IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!