How does a Java ServerSocket receive a new socket associated with the same local port after receiving a client?

I am confused about using Socket and ServerSocket ports. The Java java socket tutorial reports the following:

What is a socket?

Typically, the server runs on a specific computer and has a socket associated with a specific port number. The server just waits, listening to the socket for the client to make a connection request. On the client side: the client knows the host name of the machine on which the server is running, and the port number on which the server is listening. To fulfill the connection request, the client tries to bring the server closer to the server and port. The client also needs to identify itself on the server so that it binds to the local port number that it will use during this connection. This is usually assigned by the system.

If all goes well, the server accepts the connection. Upon receipt, the server receives a new socket bound to the same local port and also has a remote endpoint installed on the client address and port. He needs a new socket so that he can continue to listen to the original socket for connection requests while the client is connected.

On the client side, if the connection is accepted, the socket is successfully created, and the client can use the socket to communicate with the server. The client and server can now communicate by writing to or reading their sockets.

I tried the following code for testing. But that excludes.

try {
    ServerSocket serverSocket = new ServerSocket(8080);

    Socket socket = serverSocket.accept();

    // This prints 8080
    System.out.println("Local port of accepted socket : " + socket.getLocalPort());  

    // But this throws java.net.BindException: Address already in use: JVM_Bind 
    Socket myClientSocket = new Socket("www.google.com", 80, null, 8080);

} catch (Exception e) {
    e.printStackTrace();
}

My question is obvious. Although the socket returned from serverSocket.accept()can use the same local port ( 8080), why can't the socket I created use it?

+4
2

, TCP- , TCP ( IP-, INADDR_ANY).

"". IP- , , .

+1

. , "", 8080. . , , .

, google 80 (Google ), , 8080 . , java.net.BindException, , 8080.

... - ( , ):

Socket myClientSocket = new Socket("www.google.com", 80);

Socket myClientSocket = new Socket("www.google.com", 80, null, 58080);
-1

Source: https://habr.com/ru/post/1662122/


All Articles