修复java.net.BindException:已在使用的地址:JVM_Bind

时间:2015-08-12 17:56:10

标签: java sockets

我正在创建一个包含1个服务器和多个客户端的程序。所以我要做的是接受任何传入的客户端连接到同一个端口,但是当我这样做时,我得到了异常:java.net.BindException: Address already in use: JVM_Bind

我也在尝试跟踪每个客户端,以便将消息发送到单个客户端,因此我希望在连接后将套接字添加到ArrayList。

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);
                        }
                    }
                }

    }

1 个答案:

答案 0 :(得分:1)

好像你想听一次并接受很多次 - 可能是这样的:

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);
                    }
                }
            }

}