gpt4 book ai didi

java.net.BindException : Address already in use: JVM_Bind Multi Client Server

转载 作者:行者123 更新时间:2023-12-01 18:07:03 25 4
gpt4 key购买 nike

我有一个服务器项目和一个客户端项目。当服务器运行时,来自客户端的第一个连接工作正常。在第二次连接时,服务器会引发“java.net.BindException:地址已在使用中:JVM_Bind”错误。有没有办法在同一端口上添加更多连接?

服务器:

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

}}

客户:

public class Main {

public static void main(String[] args) {
Mensch jim = new Mensch(19, "Jim");

System.out.println(jim.getAge());
try {
Socket s = new Socket("127.0.0.1", 2345);

ObjectOutputStream clientOutputStream = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream clientInputStream = new ObjectInputStream(s.getInputStream());

clientOutputStream.writeObject(jim);



jim = (Mensch) clientInputStream.readObject();

System.out.println(jim.getAge());

clientOutputStream.close();
clientInputStream.close();


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

}

}

最佳答案

这就是问题:

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

您正在尝试重复绑定(bind)到同一端口。您所需要做的就是创建一个单个 ServerSocket 并对其多次调用accept。 (我还将 pipe 变量声明移到循环内...)

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

关于java.net.BindException : Address already in use: JVM_Bind Multi Client Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35587796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com