Leading on from my previous questions I am going to try and clarify one of the problems I am facing.
I am trying to create a multiplayer version of PacMan.
A simple overview of how i’ve made my application is that I have a server which has a ServerSocket which is constantly listening on a specific port. Once a client connects it creates a thread in which all the transferring of data takes place. It first listens for the Direction in which the client wants to move and then sends the updates back to the client. On the client side it’s the reverse of this sending the direction and then waiting for the update to be received. This is done using ObjectOutput/Input Streams. There is also a game class which has all the game logic and this has the game loop which each looping calls each of the connected players serverThread.exchangeDatas() method.
My game works ok with one client connected but as soon as another client joins (locally is all that i’ve tested, but this should work right?) It crashed my game in the Server thread producing the following error java.io.StreamCorruptedException: invalid type code: 00.
Is the code that trips this exception
Object o = in.readObject(); if (o instanceof Direction) { // Get new location player.setDirection((Direction) o); //System.out.println('Got: ' + (Direction)o + ' new location: ' + player.getNextLocation()); } // Send gameState //System.out.println('Sending data'); Data data = new Data(game.getGameState(), game.getScared(), game.getScareLeft(), player.getLives(), player.getScore()); out.flush(); out.writeObject(data); out.flush(); out.reset();
ServerThread code (the one that crashes in the exchangeData method
Game loop code – line 42 is what calls the exchange data method
Any help would be amazing with these.
http://www.mediafire.com/download.php?nwwqmzywfom
here’s a download to both the client and the server (they are netbeans projects)
Sorry for my messy code =[
Multithreading needs synchronisation. Are you using a synced stream (or syncing the access to the stream yourself)?
Update: The code sample given may very well be called from multiple threads. If multiple threads access the same stream, errors like the ones you are experiencing may very well occur.
I suggest having a look at http://java.sun.com/docs/books/tutorial/essential/concurrency/sync.html.
By marking a method/class synchronized, the runtime will make sure that this method/class will be active in no more than 1 thread at the same time. This is actually a vast and difficult topic, so take some time to learn the basics and make sure you understand the basic problem. 🙂