I am having a slight issue with getting my simple multiplayer game to work, and it has largely to do with clients waiting for a response from the server indefinitely. The game is mostly real-time, which is why this issue has arisen. It's a bit late in the project to change it to a turn-based solution (which is going to be my last resort). I am using a timer to handle the real-time aspects of the game. Everything works perfectly in single-player, so it's quite literally just this one issue holding me up. Basically, the timer checks for any messages from the server before updating all of the usual game logic updates. This is done in the handleServerResponses() function. Here is the code for the timer:
timer.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
if(!gamePanel.getGameOver()){
handleServerResponses();
gamePanel.updateZombieAI();
if(Math.floor(Math.random()*100)<(10+Math.ceil(gamePanel.getPlayer1Score()/10))){
gamePanel.spawnZombie();
}
}
else{
timer.stop();
sendMessage("TERMINATE");
}
}
});
And here is part of the code for the handleServerResponses method:
public void handleServerResponses(){
try {
String message=inStream.readLine();<---Here is where it gets stuck
As you can see, the program gets stuck waiting for the server to send a response, but it will never send a response as neither player can move or send messages. The inStream variable is just a BufferedReader using the server's input stream. I am just passing text between client and server. Is there any way to skip waiting for the response? Meaning, if there isn't anything sent through from the server, can the program just ignore it for that timer tick and update the game logic as normal? I searched for an answer for the past hour, but nothing came up.
Thanks!
Two solutions are available here: the correct one, and the (maybe) easy fix.
The correct solution is to do as Hovercarft Full Of Eels commented and have a separate thread processing your network data. In this model you would have your response handler reading data and adding it to a queue, and your game thread reading data from this queue when / if it is available. In this model your game thread is never waiting for network data as that is the domain of the IO threads.
If for some reason that solution is daunting or impossible for you to implement, then the quick fix may be to simply call inStream.ready() before trying to read from it. This is in no way a guarantee since calling ready() does not ensure that an entire line is available to be read, but if your server only responds with whole lines then it may be just enough to unblock you.
For the record, I would strongly recommend the first solution using a separate IO thread that is uncoupled from your game thread as it will be more robust.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With