我有一个服务器 - 客户端程序,但我希望能够从服务器发送回客户端请求数据。在注释代码中,如果我启用了该功能,则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;
}
}
答案 0 :(得分:1)
一切正常
不,不。当socket和缓冲区都填满时,这个发布的代码最终会死锁。
除非所有代码都更改为在套接字的生命周期内使用单个ObjectInputStream和ObjectOutputStream,否则注释掉的代码无法工作。
我想补充一点,你在这里询问了错误的问题。问题是为什么注释掉的代码没有工作,而你提供的信息是抛出的异常。