0

我正在尝试通过套接字发送对象以进行游戏,但它们需要很长时间才能发送并且可能导致游戏挂起。我想使用 BufferedOutputStreams 和 BufferedInputStreams 来发送数据,但是当我在客户端使用 BufferedOutputStream 时,我的 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
     */
}

我已经浏览了所有论坛,但找不到任何有用的东西,这让我认为我正在做一些非常新手的事情。谢谢你提供的所有帮助!

4

1 回答 1

1

您需要否则不会将其输出发送到套接字.flush()ObjectOutputStreamBufferedOutputStream

于 2012-06-21T23:19:46.730 回答