Reputation: 139
I am trying to send objects across a socket for a game, but they take a long time to send and can cause the game to hang. I want to use BufferedOutputStreams and BufferedInputStreams to send the data, but my ObjectInputStream won't initialize on the server side when I use the BufferedOutputStream on the client side. The weird thing is that no errors are thrown.
I'm only providing the code involved because it would take a long time to explain what's going on otherwise. Two clients are initialized each game.
/*Server Code*/
ObjectOutputStream toClients;//stream to both players
ObjectInputStream fromClients;//stream from both players
Socket client1;//player one socket
Socket client2;//player two socket
public RunGame(Socket client1, Socket client2)throws IOException//constructor of a new thread
{
this.client1=client1;
this.client2=client2;
}
public void run()//for the thread
{
try{
this.createGame();
/*
rest of code for server when running game
*/
}
catch(IOException e){e.printStackTrace();}
catch(ClassNotFoundException e){e.printStackTrace();}
}
public void createGame()
{
try{
System.out.println("about to create");//this prints out
fromClients=new ObjectInputStream(client1.getInputStream());//first initialization
System.out.println("created");//this doesn't
String s1=(String)fromClients.readObject();
fromClients=new ObjectInputStream(client2.getInputStream());//sets input to player 2
String s2=(String)fromClients.readObject();
}
catch(IOException e){e.printStackTrace();}
catch(ClassNotFoundException e){e.printStackTrace();}
}
/*Client Code*/
Socket sock;//created in the constructor of the thread
ObjectOutputStream toServer;
ObjectInputStream fromServer;
public void run()
{
try{
System.out.println("about to create");//this prints
toServer=new ObjectOutputStream(new BufferedOutputStream(sock.getOutputStream(),8*1024));//bufferedoutputstream is here
toServer.writeObject("String that is to be sent to server");
System.out.println("written");//this also prints
}
catch(IOException e){e.printStackTrace();}
catch(ClassNotFoundException e){e.printStackTrace();}
/*
rest of client code
*/
}
I've been through all of the forums but can't find anything that works, which makes me assume that I'm doing something very novice. Thanks for any help you can give!
Upvotes: 0
Views: 1107