I’m in the process of writing a Java client and server, and they’re both talking to each other correctly. At the moment, however, the client must always send a message to the server before it can receive one – but I want the server to be able to send a message without the client asking for it.
In AS3, my primary language, I’d have added an event listener to the socket and handled the data that way – but I can’t seem to find out how I would do that in Java.
Currently my client has this code in it:
public String send(String message) {
out.println(message);
try {
return in.readLine();
} catch (IOException ex) {
return "";
}
}
Basically I call it, passing my message, and it returns giving me the server’s response.
Instead of doing this I want to send a message there, like below, and have the response picked up somewhere different (by an event listener).
public void send(String message) {
out.println(message);
}
As I couldn’t figure out how an event listener would work, I did contemplate using a separate thread to run while(true){in.readLine;} but I want to avoid this if at all possible; I’m not too comfy with threads, and I want to keep it as simple as possible.
The simplest way to do this is to use threads. I would have at least one thread reading the socket which allows the server to send a message to the client any time.
The problem with mixed responses and events is that your first block won’t work because the “response” could be an event.
If you don’t want to use threads, you could have something like
However, it will only read events when a request is sent and if this is not done regularly it can cause the stream to bank up all the way to the server causing it to block as well.