idea to write to socket in seperate thread

Hi everyone!

I made a multiplayer picture puzzle game and I’m trying to improve its responsiveness. As the code is now, when the user clicks to move a tile the program updates the tiles position, redraws the screen, then writes the updated position information to the socket. As a result, if you try to make two moves quickly, the second move doesnt register.

I am thinking about having a seperate thread write the data to the socket? Any comments or suggestions about this?

If you want to try my game it is online in applet form on my website. I’ve been told its quite fun and there are 114 pictures to choose from to play with. Here is the link:

http://www.jeuno.ca/jumble/multiplayerbeta/JeunoJumbleMP.php

Maybe I’ll see ya in there for a game :wink:

What I’ve often done in the past is to create a thread that reads from the socket and a thread that writes to the socket. When you want to write to it from your game thread you would enqueue what you want to send and the sending thread would poll this queue to pick up the next message to send. This will give you the effect of non-blocking IO and keep messages in the correct order.

You could also use NIO which will inherently resolve this, but is a bit more complicated. Also, if you haven’t considered using a game networking API that might also help. Such as http://javagn.org. However, there are many homegrown APIs for networking if you just search this forum.

Ok, I now queue actions in a Vector and have a seperate thread writing from the Vector to the socket to send to the actions to the server. It seems to work ok, however, now when I try to play a sound theres a significant delay that wasnt there before. My setup is like this:

I have an applet which creates a Frame that displays the game. Since the Applet class is the only one that can play a sound file, I pass the applet to the frame in the frames constructor and have a public method in the Applet called makeNoise();

It seems strange to me to have the Frame refrencing its parent applet but I know no other way to play a sound from the Frame. The sounds were working fine with no delay until I introduced this new thread I call a JJClientWriter.

Does anyone have any suggestions on how to better play a sound from a Frame or know why I might be getting the delay after adding a new thread?

???

UPDATE: I think i figured it out. My new thread was looping continously checking the queue and i guess it was hogging the processor. I added a sleep(50) into the loop and everything works fine now. Thanks for your time :slight_smile:

If you’re using JDK 1.5+ then you can use ConcurrentLinkedQueue and simply poll from it. It’s also thread-safe in a non-blocking way.

Wow! Thanks for the tip! The ConcurrentLinkedQueue class works beautifully. Me thinks I spent a little too much time with JDK1.2 back in the day. I’m even just getting into swing components now lol. ;D