Tuesday, 1 October 2013

Android multi-thread socket write implementation

Android multi-thread socket write implementation

I wrote an android client app for a server-based trivia game. My app
creates several threads (the players), and in each thread establishes a
unique socket connection to the server. These connections wait for
messages from the server (e.g., "Correct!"). The app also sends data to
the server on keypresses (e.g., answering choice #1).
At the same time, I need to send stay-alive "pings" to the server based on
the comm protocol of the trivia game. I do this by creating one last
thread, that routinely sends the ping messages over each thread's socket
connection. (I cannot use the original player threads because they are
busy-waiting on server messages). Obviously, there is a synchronization
issue here.
My current code simply has "synchronized(player_socket)" before writing to
the socket through a BufferedWriter. Is this an appropriate implementation
for the situation I described, so that there are no issues if a player has
hit an answer button (which calls a method in the player thread to send an
outgoing message) at the exact instance the "ping manager" thread is
issuing a ping message on the same socket? Or should I have my ping thread
call a method located in the player threads to initiate the ping message?
Thanks for any insight.
Greg

No comments:

Post a Comment