Questions as follows

The client

public class Client { public static void main(String[] args) { try { Socket socket = new Socket("localhost",9999); Send send = new Send(socket); Receive receive = new Receive(socket); send.start(); receive.start(); } catch (Exception e) { e.printStackTrace(); }}}Copy the code

The service side

public class Server { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(9999);  Socket socket = serverSocket.accept(); Send send = new Send(socket); Receive receive = new Receive(socket); send.start(); receive.start(); } catch (Exception e) { e.printStackTrace(); }}}Copy the code

After running, it is true that the client and server can interact, but aren’t the two mian methods finished? Isn’t the server port closed? Then why do you keep writing?

idea

My idea is that the port is not freed, only the memory address of the serverSocket is freed

Before the end of the Server’s main method

After the main method of the Server endsAs you can see, the port is not closed, but there is a danger because there is no reference pointing to the heap and it may later be collected by the GC

If I manually close this port, can I continue communication?

public class Server {
	public static void main(String[] args) {
		try {
			ServerSocket serverSocket = new ServerSocket(9999);
			Socket socket = serverSocket.accept();
			
			Send send = new Send(socket);
			Receive receive = new Receive(socket);
			send.start();
			receive.start();
			
                        serverSocket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
Copy the code

I added serversocket.close (), and it turned out that the port was indeed closed, but could still communicate, which brought me back to my original problem, so I had another idea

The computer only opened port 9999, and our Server process registered this port. Although the port has been closed, the Server process has been identified. When the client sends a message to the Server, it only looks for which process is port 9999, and does not care whether port 9999 is open

The last

I do not know my idea is right, hope big guys can give directions