getInputStream块? [英] getInputStream blocks?

查看:92
本文介绍了getInputStream块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用输入/输出流在客户端和服务器之间传递对象.我可以使用我的服务器发送和接收对象,现在我希望客户端现在只能发送该对象.所以我给我的客户一个ObjectInputStream.但是,当我初始化它时,它会阻塞!一直在搜索并找到答案,但没有解决方案.

Using Input/Output stream to pass objects between my client and server. I can both send and receive objects with my server, and and now i want the same for the client which as of now only can send. So i gave my client an ObjectInputStream. However, when i initilazie it, it blocks! Been searching around and found answers but no solution.

请帮助!

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

        }

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

I tried using them in different threads but it had the same problem, at least for me :(

推荐答案

是的,这个问题已经被问过很多次了.对象流格式具有标头,并且ObjectInputStream在构造时读取该标头.因此,它将一直阻塞,直到它通过套接字接收到该标头为止.假设您的客户端/服务器代码看起来相似,则在构造ObjectOutputStream之后,刷新它.这将迫使标头数据通过网络.

yes, this question has been asked many times before. the object stream format has a header, and the ObjectInputStream reads that header on construction. therefore, it is blocking until it receives that header over the socket. assuming your client/server code looks similar, after you construct the ObjectOutputStream, flush it. this will force the header data over the wire.

这篇关于getInputStream块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆