Search code examples
javasocketsserversocket

ServerSocket port number can be any 5009, 12221,6 785, etc. But why?


I am confused and searched a lot, but couldnt find answer to my question, help me out....

ServerSocket s= new ServerSocket(port);

from where does this port number comes from? even if I take any number either of 4 or 5 digits, it works perfectly but why and how? e.g. port number can be any 5009, 12221, 6785, etc. but why? and who decides what number it should be?


Solution

  • It is up to you to specify the listening port for your server side application because the client side has to know to which port it should try connecting to.

    As ports range 1-1024 is reserved for system services (this is just by convention, not a rule) you can pick any port from (1024, 65535]. If the port you have selected is occupied by another application, it will just throw an exception. If you do not specify the port number, it will be randomly generated.