Reputation: 39
I have a server-client program, but I want to be able to have client request data from the server to send back. In the commented code, If I have that enabled, the Sender.send only sends once than nothing happens after. But If i have it disabled it works all fine. Not sure what I'm doing wrong in the commented code.
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) {
}
}
}
}
Send method:
protected static boolean send(ObjectOutputStream oos) {
try {
update();
oos.writeObject(data);
oos.flush();
return true;
} catch (Exception e) {
return false;
}
}
Upvotes: 0
Views: 610
Reputation: 310860
It works all fine
No it doesn't. This code as posted will eventually deadlock when both socket and buffers fill up.
The commented out code cannot possibly work unless all of the code is changed to use a single ObjectInputStream and ObjectOutputStream for the life of the socket.
I would add that you asked about the wrong problem here. The question is why didn't the commented-out code work, and the information you failed to supply was the exception that was thrown.
Upvotes: 1