这是一个简单的TCP服务器.程序终止时如何关闭套接字?
我使用try / finally并尝试关闭套接字.但是当我退出程序时它不会运行finally块.
我使用try / finally并尝试关闭套接字.但是当我退出程序时它不会运行finally块.
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!"); }