close all the sockets after using it? on server side
10,067
Call server.close()
in a finally
block.
ServerSocket server = new ServerSocket(PORT);
try {
while (true) {
System.out.println("Waiting for client...");
// open client socket to accept connection
Socket client = server.accept();
System.out.println(client.getInetAddress()+" contacted ");
System.out.println("Creating thread to serve request");
ServerStudentThread student = new ServerStudentThread(client);
student.start();
}
} finally {
server.close();
}
Author by
John
Updated on June 05, 2022Comments
-
John almost 2 years
Do I have to close all the sockets after using it? Where should I put them in this code? My program just works normally when I run it. However, when I re-run it, it said "Exception in thread "main" java.net.BindException: Address already in use: JVM_Bind". Therefore, I think I did not close all the socket after using it.
import java.io.*; import java.net.*; import java.util.*; public class Server2 { public static void main(String args[]) throws Exception { int PORT = 5555; // Open port 5555 //open socket to listen ServerSocket server = new ServerSocket(PORT); Socket client = null; while (true) { System.out.println("Waiting for client..."); // open client socket to accept connection client = server.accept(); System.out.println(client.getInetAddress()+" contacted "); System.out.println("Creating thread to serve request"); ServerStudentThread student = new ServerStudentThread(client); student.start(); } }
}
-
John about 13 yearsthanks for figuring out my mistake. But what if I don't know NUM_CONN_TO_WAIT_FOR. Anyway, thanks!
-
Anubis over 9 yearsNow in Java 7 you can try with resources;
try(ServerSocket server = new ServerSocket(PORT)) {...}
. It will release the resources properly at the end (will do null check etc..)