问题
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.
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??
Thank you
回答1:
TCP does not work that way. When you create a TCP socket, bind to port A, and listen what you have is :
- A listening socket on port 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 listening socket on port A (still lives, you did not close it)
- A servicing socket on port A, but part of a socket pair. (IPA(A), IPB(B))
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.
If another client connects you get this, assuming a different ip address and port:
- A listening socket on port A (still lives, you did not close it)
- A servicing socket on port A, but part of a socket pair. (IPA(A), IPB(B))
- A servicing socket on port A, but part of a socket pair. (IPA(A), IPC(C))
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 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.
来源:https://stackoverflow.com/questions/30054673/tcp-listener-and-client-listening-to-specfic-ip