简体   繁体   中英

Do client and server need to use same port to connect?

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.

答案是否定的,服务器将在特定端口上侦听,但是当客户端开始连接到服务器时例如:服务器在端口80上侦听当客户端连接到服务器时,它将连接到端口80上的serverIP地址。客户端套接字位于另一个端口上端口,由操作系统分配

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM