【问题标题】:ObjectInputStream won't initialize when using BufferedOutputStreams使用 BufferedOutputStreams 时 ObjectInputStream 不会初始化
【发布时间】:2012-06-21 23:09:57
【问题描述】:

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

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

【问题讨论】:

    标签: java objectoutputstream objectinputstream bufferedoutputstream


    【解决方案1】:

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

    【讨论】:

    • 就是这样,非常感谢您纠正我的新手问题。你太棒了:)
    猜你喜欢
    • 2018-05-03
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    相关资源
    最近更新 更多