I have a Server-Client program using java, I tried to create a ServerSocket
with a port and Client Socket
with different port and they cannot connect to each other. Client throw ConnectException
. When I change the socket on Client to the same as the one I use for ServerSocket, they worked.
As I understand from the aswer from this thread Java Networking: Explain InputStream and OutputStream in Socket if a machine create a socket with a port then that socket is bind to that machine, so why do client and server need to use same port to connect to each other?
Also, two application can't use same port on a machine so what happen when two difference Server having same port and a machine need to connect to both of them through 2 different application?
You need some basic understanding of TCP communication. Just Google TCP tutorials.
In a nutshell; the server will listen on a specific port. When a server is listening on a port it is bound to it. Only one server (or process) on a machine can be listening on a certain port.
The client will connect to a machine and specify the port to communicate on. If the server is listening on the port the client asked, then comms happens. Otherwise the connection cannot continue.
So the port that the server is bound to (or listening on) must be the same as the port the client specified.
The client and server don't need to use the same port. As you pointed out, a port can only be allocated to a single process at a time on a machine. To be more correct, a port and IP address pair is the allocation unit. So if your machine has two addresses or more one can bind the port to different processes per IP.
The standard setup is for the server process to listen for connections on a port, say 10000 using a server socket. The client process tries to connect to that port using a client socket. It will use a OS allocated port. Once the connection is setup, the server will allocate another client socket, on its side, in order to manage communication with the client process, and this will also have a OS allocated port.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With