1

If a machine is running a server application that listens on some port (say 9999) and on the same machine several client applications opens a TcpClient(localhost,9999) connection to the same server application, what will happen? Will this cause some sort of collision?

LimS
  • 85
  • 1
  • 10
  • Possible duplicate of [Can two applications listen to the same port?](http://stackoverflow.com/questions/1694144/can-two-applications-listen-to-the-same-port) – Cjen1 Nov 01 '15 at 11:02
  • @Micky, I simply don't understand how that works, how does the packets don't get mixed? – LimS Nov 01 '15 at 11:40

1 Answers1

1

In C# a TcpListener is waiting for incoming connections from a client with AcceptSocket or AcceptTcpClient. On a successful connection you get back a Socket object that can be used to talk to that specific client identified by client IP. If the connection to the client is handled in another thread than AcceptSocket your sever application can talk to multiple clients at once. e.g. server loop just calls Accept and is directly handing over the Socket to some handler Thread/Task. And in general for incoming connections you know the client IP-Address (and port) and based on this one can multiplex the connection/data to the corresponding socket. A good and complete answer but non C# specific is here TCP : two different sockets sharing a port?

On the client side a random port is choosen for the outgoing connection. This is done by the socket/network system

In the internet paradigm, the port numbers are between 0 and 65535 and are chosen randomly by the transport layer software running on the client host. These are called ephemeral ports (range from 1024 to 49151).

Applied C#.NET Socket Programming

Community
  • 1
  • 1
Muraad Nofal
  • 794
  • 3
  • 6
  • My question is, what happens when everything runs on the same machine. – LimS Nov 02 '15 at 06:49
  • My question is, what happens when everything is on the same machine, the server and the clients. All of the have the same IP. The server listens on the specified port, and as for the clients ports, I am not sure if pick random output port implicitly or not. If not then I don't understand how could they have different socket. – LimS Nov 02 '15 at 06:51
  • Yes you are right I think the underlying OS socket system is choosing random outports for a client – Muraad Nofal Nov 02 '15 at 19:05