Java – how do I close a socket in the right way?
•
Java
This is a simple TCP server How to close the socket when the program terminates?
Anyone can figure out how to close a socket in the right way?
try { socket = new ServerSocket(port); System.out.println("Server is starting on port " + port + " ..."); }catch (IOException e){ System.out.println("Error on socket creation!"); } Socket connectionSocket = null; try{ while(true){ try{ connectionSocket = socket.accept(); Thread t = new Thread(new ClientConnection(connectionSocket)); t.start(); }catch (IOException e) { System.out.println("Error on accept socket!"); } } }finally{ this.socket.close(); System.out.println("The server is shut down!"); }
Solution
No, when the program exits, the operating system will close all TCP sockets
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码