我正在使用 Java 进行客户端-服务器模拟,其中客户端(线程)连接到服务器以获取一些数据。几秒钟后,需要杀死随机选择的客户端(线程)之一。我关闭了用于与服务器通信的套接字并让他死了(通过退出 run() 方法)。问题是当新创建的线程试图创建与以前使用的相同的套接字(相同的地址和相同的端口)连接到服务器时,我得到:
java.net.BindException: Address already in use
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:374)
at java.net.Socket.bind(Socket.java:627)
at java.net.Socket.<init>(Socket.java:423)
at java.net.Socket.<init>(Socket.java:319)
创建套接字的代码:
private void createNewSocket(InetAddress sIP, int sPort,
InetAddress cIP, int cPort) {
try {
socket = new Socket(sIP, sPort, cIP, cPort);
} catch (IOException e) {
e.printStackTrace();
System.err.println("Socket unsuccessfully created");
}
try {
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
} catch (IOException e) {
e.printStackTrace();
try {
socket.close();
} catch (IOException e2) {
System.err.println("Socket unsuccessfully closed");
}
}
}
public void run() {
createNewSocket(gprsServerIP, Util.PORT_SERVER_PORT,
clientIP, sendPort);
out.println(REQUEST);
try {
serverPort = Integer.parseInt(in.readLine());
TCPClient.serverPort[clientID] = serverPort;
System.out.println("Server port: " + serverPort + '\n' +
"Send port: " + sendPort + '\n');
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
System.err.println("Socket unsuccessfully closed");
}
}
while (true) {
if (clientID == TCPClient.selectedID) {
TCPClient.selectedID = -1;
createNewSocket(gprsServerIP, Util.PORT_SERVER_PORT,
clientIP, sendPort);
out.println(FREE_PORT + serverPort);
try {
socket.close();
} catch (IOException e2) {
System.err.println("Socket unsuccessfully closed");
}
//System.out.println(socket.isClosed());
System.out.println("Port:" + serverPort + " is free");
TCPClient.id[clientID] = -1;
break;
}
}
clientCount--;
}