使用BufferedOutputStream

使用BufferedOutputStream

我正在尝试通过套接字向游戏发送对象,但是这些对象要花很长时间发送,并且可能导致游戏挂起。我想使用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
     */
}


我参加过所有论坛,但找不到任何有效的方法,这使我认为我正在做一些非常新手的事情。谢谢你提供的所有帮助!

最佳答案

您需要.flush()您的ObjectOutputStream,否则BufferedOutputStream不会将其输出发送到套接字。

09-27 06:13