getInputStream块?

Luc*_*elt 2 java multithreading objectinputstream

使用输入/输出流在我的客户端和服务器之间传递对象.我可以用我的服务器发送和接收对象,现在我想要客户端,现在只能发送.所以我给了我的客户一个ObjectInputStream.然而,当我初学它时,它会阻止!一直在寻找答案,但没有解决方案.

请帮忙!

public GameConnection(String strPort, TextArea chat)
    {
        this.port = Integer.parseInt(strPort);
        System.out.println("GameConnection::Constructor(): Connecting on port " + port);
        this.chat = chat;


        connect = new Connection();
        sendObject();
    }
    public void sendObject()
    {
        try
        {  
            obj_stream.writeObject(new String("GameServer received a message!"));  
        }
        catch(Exception e){System.out.println("GameConnection::sendObject(): " + e);}  
    }  

    protected class Connection extends Thread
    {
        private boolean alive = true;

        public Connection()
        {
            try
            {
                socket = new Socket(host, port);
                System.out.println("Connected to GAMESERVER" + host + " on port + " + port);
                obj_stream = new ObjectOutputStream(socket.getOutputStream());
                // Next line BLOCKS!!!
                //ObjectInputStream stream = new ObjectInputStream(socket.getInputStream());
            }
            catch (IOException ioe)
            {
                System.out.println("Connection::constructor() " + ioe);
                Terminate();
            }
            catch (NullPointerException npe)
            {
                System.out.println("Connection::constructor() " + npe);;
                Terminate();
            }

        }
Run Code Online (Sandbox Code Playgroud)

我尝试在不同的线程中使用它们,但它有同样的问题,至少对我来说:(

jta*_*orn 10

是的,之前已经多次询问过这个问题.对象流格式有一个标题,ObjectInputStream在构造时读取该标题.因此,它会阻塞,直到它通过套接字接收到该标头.假设您的客户端/服务器代码看起来相似,在构造ObjectOutputStream之后,将其刷新.这将强制通过电线的标头数据.