【问题标题】:ObjectInputStream fails in Java ThreadJava 线程中的 ObjectInputStream 失败
【发布时间】:2015-10-31 11:07:10
【问题描述】:

我无法从套接字获取输入和输出流,每次到达 getInputStream/getOutputStream 时我的代码都会阻塞。

class Connection implements Runnable {
    private static final Logger logger = Logger.getLogger(Connection.class.getName());
    Socket connection = null;
    Boolean serverIsDown = false;
    Thread thread = null;
    ObjectInputStream ois = null;
    ObjectOutputStream oos = null;
    Context ctx = null;

    public Connection(Socket accept, Boolean serverIsDown) {
        logger.log(Level.INFO, "Connected" + accept.getRemoteSocketAddress());
        this.connection = accept;
        this.serverIsDown = serverIsDown;

        this.thread = new Thread(this, "Client Connection");
        this.thread.start();

    }

    public void init() throws IOException {
        while (true) {
            System.out.println("Hit enter to send object");
            System.in.read();
            Request request = new Request();
            oos.writeObject(request);
        }
    }

    @Override
    public void run() {
        try {
            this.ois = new ObjectInputStream(this.connection.getInputStream()); //Blocks here
            this.oos = new ObjectOutputStream(this.connection.getOutputStream());
            this.init();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

阻塞时没有输出错误。

【问题讨论】:

  • 在创建 ObjectInputStream 之前始终刷新() ObjectOutputStream。这是因为该格式有一个 ObjectInputStream 在构造函数中读取的标头。

标签: java multithreading sockets objectinputstream


【解决方案1】:

如文档所述: http://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html#ObjectInputStream(java.io.InputStream)

创建一个从指定 InputStream 读取的 ObjectInputStream。 从流中读取并验证序列化流标头。此构造函数将阻塞,直到相应的 ObjectOutputStream 写入并刷新标头

我建议你使用两个线程处理来自接受的套接字的输入和输出流,以避免阻塞。另一种更好的方法是使用线程池和一些异步 io (ex;selector),而不是为每个接受的套接字分配一个线程。

另请参阅下面的其他帖子: new ObjectInputStream() blocks

【讨论】:

    【解决方案2】:

    您为每个对象创建一个新流。只创建一个输出和一个输入流。对象流发送的标头数据在您创建新流时可能已损坏。

    【讨论】:

      猜你喜欢
      • 2016-04-05
      • 2021-07-23
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      • 1970-01-01
      • 2020-12-08
      相关资源
      最近更新 更多