我有一个服务器-客户端程序,但我希望能够让客户端请求数据从服务器发回。在注释代码中,如果我启用了该功能,则 Sender.send 只发送一次,之后什么也没有发生。但是,如果我将其禁用,则一切正常。不确定我在注释代码中做错了什么。
private class Client extends Thread {
private Socket socket;
private boolean running;
public Client(Socket socket) {
this.socket = socket;
this.running = true;
if (!(clients.contains(socket))) {
clients.add(socket.getInetAddress().toString());
}
}
private void delete() {
running = false;
try {
log("Client disconnected: (" + socket.getInetAddress().toString().replace("/", "") + ":" + socket.getPort() + ")");
clients.remove(socket.getInetAddress().toString());
socket.close();
} catch (IOException e) {
}
try {
interrupt();
join();
} catch (Exception e) {
}
}
public void run() {
log("Client connected: (" + socket.getInetAddress().toString().replace("/", "") + ":" + socket.getPort() + ")");
try {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
while (running) {
if (!Sender.send(oos)) {
delete();
return;
}
try {
Object object = ois.readObject();
if (object instanceof String[] && ((String[]) object)[0].equals("COMMAND_REQUEST")) {
String command = ((String[]) object)[1].trim();
log("Executed command request: " + command);
Sender.log("Executed command request: " + command);
Bukkit.getServer().dispatchCommand(getServer().getConsoleSender(), command);
}
} catch (Exception e) {
}
Thread.sleep(300);
}
} catch (Exception e) {
delete();
} finally {
try {
socket.close();
} catch (Exception e) {
}
}
}
}
发送方式:
protected static boolean send(ObjectOutputStream oos) {
try {
update();
oos.writeObject(data);
oos.flush();
return true;
} catch (Exception e) {
return false;
}
}