0
我試圖通過套接字發送遊戲對象,但是它們需要很長時間才能發送,並且可能導致遊戲掛起。我想使用BufferedOutputStreams和BufferedInputStreams來發送數據,但是當我在客戶端使用BufferedOutputStream時,我的ObjectInputStream不會在服務器端初始化。奇怪的是沒有錯誤拋出。當使用BufferedOutputStreams時,ObjectInputStream不會初始化
我只提供涉及的代碼,因爲這需要很長時間才能解釋發生了什麼。每場比賽都有兩名客戶進行初始化。
/*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
*/
}
我已經通過了所有的論壇,但找不到任何有效的工作,這讓我認爲我正在做一些非常新手。謝謝你提供的所有幫助!
就是這樣,謝謝大家糾正我的新手。你真棒 :) – Indeed