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();
}
Share:
10,067
John
Author by

John

Updated on June 05, 2022

Comments

  • John
    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
    John about 13 years
    thanks for figuring out my mistake. But what if I don't know NUM_CONN_TO_WAIT_FOR. Anyway, thanks!
  • Anubis
    Anubis over 9 years
    Now 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..)