Ducksauce88
Ducksauce88

Reputation: 650

Fixing java.net.BindException: Address already in use: JVM_Bind

I am creating a program that will have 1 server and multiple clients. So what I am trying to do is accept any incoming client connection to the same port, but when I do so I get the exception: java.net.BindException: Address already in use: JVM_Bind.

I am also trying to keep track of each individual client so I can send out messages to a single client, hence me wanting to add the socket to an ArrayList after being connected.

private static ServerSocket socket;
private static ArrayList<Socket> arraySocket = new ArrayList<Socket>();


...


    public static void StartServer() {

                while(true){
                //for (int i = 0; i < Main.nucs.size(); i++) {
                    try {
                        socket = new ServerSocket(Constants.PORT_NUMBER);  
                        socket.setReuseAddress(true);
                        Logger.Log("Waiting for first client");
                        arraySocket.add(socket.accept());
                        Logger.Log("New Client: " + arraySocket.get(count).getInetAddress().toString());
                        (new Thread(new ClientHandler(arraySocket.get(count)))).start();
                        count++;
                    } catch (IOException e) {
                        Logger.Log("Server:IOException:e: " + e);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException ex) {
                            java.util.logging.Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }

    }

Upvotes: 0

Views: 899

Answers (1)

pherris
pherris

Reputation: 17743

Seems like you want to listen once and accept many times -maybe something like this:

public static void StartServer() {

            socket = new ServerSocket(Constants.PORT_NUMBER);  
            socket.setReuseAddress(true);
            Logger.Log("Waiting for first client");

            while(true){
                try {
                    arraySocket.add(socket.accept());
                    Logger.Log("New Client: " + arraySocket.get(count).getInetAddress().toString());
                    (new Thread(new ClientHandler(arraySocket.get(count)))).start();
                    count++;
                } catch (IOException e) {
                    Logger.Log("Server:IOException:e: " + e);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        java.util.logging.Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }

}

Upvotes: 1

Related Questions