No you dont, only the reader needs a thread.
You send messages with methodcall à la
writer = new PrintWriter(socket.getOutputStream());
..
public void sendMsg(String msg){
writer.println(msg);
writer.flush;
}
Yes, he does . If the sending of the message blocks for any reason, your game will also freeze until the message is sent . Though it may be rare to block the sending message, I have learned in the last years that if something has a chance to happen, it WILL happen . Never neglect a rare case .
It is possible to use just one Thread. It is actually the way I'm doing right now .
First I check if there are bytes to be read. If yes, I parse them and send them to a queue for processing by the game later.
Else, I check if there are messages queued to be sent.
Else , I sleep a little and repeat again .
The code : (try catch have been removed for the sake of readability):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| DataInputStream inFromClient; ....
while(active) { if (inFromClient.available()>0) { readDataFromClientAndInsertInParsersQueue(); } else if (!sendMessageQueue.isEmpty()) { sendQueuedMessages(); } else { Thread.sleep(sleepTime); } } |
I can't tell you if this is an excellent approach but it has been working for me .
Any comments from the specialists ?