Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does serversocket class serve multiple client connections on same port?

When using a Socket class one is establishing a TCP connection to a server on some port, but on the server the ServerSocket is capable of handling multiple client connections for each accept request and delegate it to a thread to server the request. But how is it possible for a ServerSocket class to accept multiple tcp connections on the same port.

Does it mean that it is upto the OS to decide how many connections it allows or what is the maximum backlog allowed and can this be controlled by applications on top of OS(i mean is java restricted by the maximum backlog supported by OS) and is there any privison for backlog connections in TCP specification?

Best reagards,
Keshav

like image 802
keshav84 Avatar asked Sep 16 '10 18:09

keshav84


2 Answers

A TCP connection is defined by a unique set of (source IP, source port, dest IP, dest port). Since the server binds to a particular port, it defines two of those 4 variables. As long as the clients all come from different IPs and/or different ports, it won't be an issue.

And yes, the OS can control how many total connections are allowed, and your program can restrict that even further.

like image 175
zigdon Avatar answered Oct 14 '22 16:10

zigdon


It serves multiple clients and you can choose how many clients you will handle a the same time.

A connection (aka a Socket between a client and a server isn't only identified by the ServerIP/ServerPort, it's identified with ClientIP/ClientPort/ServerIP/ServerPort.

You only have to accept connections (and usually treat them in different threads).


By default the backlog size is 50, but you can set it when you create your ServerSocket.

new ServerSocket(21, 100); //Create a server socket with a backlog of 100

Resources :

  • javadoc - Socket
  • Sun.com - All about sockets
like image 39
Colin Hebert Avatar answered Oct 14 '22 15:10

Colin Hebert