Java Socket 卡在 new ObjectInputStream() [英] Java Socket stuck at new ObjectInputStream()

查看:84
本文介绍了Java Socket 卡在 new ObjectInputStream()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个游戏的服务器/客户端模型,但它一直卡在 ObjectInputStream 初始化中.

I have this server/client model for a game but it keeps getting stuck at the ObjectInputStream initialization.

这是客户端启动方法的代码:

Here is the code for the client's start method:

public void start(){
try {
        Socket s = new Socket("127.0.0.1", 24680);
        Thread.sleep(1000);
        ois = new ObjectInputStream(s.getInputStream()); // stuck here
        oos = new ObjectOutputStream(s.getOutputStream());
        startGame();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

这里是服务器代码:

try {
    InputStream fis = socket.getInputStream();
    ObjectInputStream ois = new ObjectInputStream(fis);
    while (true) {
        ArrayList < Dot > lists = (ArrayList < Dot > ) ois.readObject();
        for (Socket s: sockets) {
            ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
            oos.writeObject(lists);
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

提前致谢!

推荐答案

你至少需要在 ObjectInputStream 之前构建ObjectOutputStream 一方面,最好两者兼而有之,以免发生意外.否则 new ObjectInputStream() 会阻止尝试读取尚未被对等方的 new ObjectOutputStream() 写入的流标头,因为他也在 中被阻止new ObjectInputStream().

You need to construct the ObjectOutputStream before the ObjectInputStream at at least one end, preferably both to avoid accidents. Otherwise new ObjectInputStream() blocks trying to read the stream header which hasn't been written yet by the peer's new ObjectOutputStream(), because he also is blocked in new ObjectInputStream().

其他注意事项:

  • 与您当前的代码不同,您必须在套接字的整个生命周期内在两端使用相同的对象流.原因是一样的:流头.如果您继续创建新的 ObjectOutputStreams,您将继续编写新的流标头,这是对等方不会期望或理解的.
  • 删除sleep().网络代码中不需要睡眠.他们只是在浪费时间.Cargo-cult 编程.
  • You must use the same object streams for the life of the socket, at both ends, unlike your current code. The reason is the same: the stream header. If you keep creating new ObjectOutputStreams you will keep writing new stream headers, which the peer won't expect or understand.
  • Remove the sleep(). There is no need for sleeps in networking code. They are just literally a waste of time. Cargo-cult programming.

这篇关于Java Socket 卡在 new ObjectInputStream()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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