java.net.BindException:已在使用的地址:JVM_Bind Multi Client Server

时间:2016-02-23 20:44:16

标签: java

我有一个Server项目和一个Client项目。当服务器运行时,来自客户端的第一个连接工作正常。在第二次连接时,服务器触发“java.net.BindException:Address in in use:JVM_Bind”错误。有没有办法在同一个端口上添加更多连接?

服务器:

-2000

}

public class Main {

public static void main(String[] args) throws IOException, ClassNotFoundException {

    Socket pipe = null;
    while(true){

    ServerSocket s = new ServerSocket(2345);
    pipe = s.accept();

    Connection c = new Connection(pipe);
    c.start();

    }
}

} }

客户:

public class Connection extends Thread{

private Socket socket = null;

Mensch jim = null;
ObjectInputStream input = null;
ObjectOutputStream output = null;
ServerSocket s = null;

public Connection(Socket s){
    socket = s;
}
   public void run(){
        try {
        input = new ObjectInputStream(socket.getInputStream());
        output = new ObjectOutputStream(socket.getOutputStream());

        jim = (Mensch) input.readObject();
        jim.setAge(33);

        output.writeObject(jim);

        input.close();
        output.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

}

1 个答案:

答案 0 :(得分:4)

这是问题所在:

while(true) {
    ServerSocket s = new ServerSocket(2345);
    pipe = s.accept();
    ...
}

您尝试重复绑定到同一个端口。您需要做的就是创建 ServerSocket并多次调用accept。 (我也在循环中移动pipe变量声明......)

ServerSocket s = new ServerSocket(2345);
while(true) {
    Socket pipe = s.accept();
    ...
}