getInputStream块?

时间:2011-11-11 01:15:02

标签: 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();
            }

        }

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

1 个答案:

答案 0 :(得分:10)

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