java - 创建一种通过网络发送整数的有效方法。传输控制协议(protocol)

标签 java performance networking byte data-stream

如何将整数值转换为字节数组,然后通过字节流将它们发送到客户端程序,客户端程序将字节数组转换回整数?

我的程序是一个乒乓球游戏。一旦运行,它就会创建一个服务器,客户端立即使用对象流通过互联网连接到该服务器。一切都运转良好,但似乎效率不高。我的意思是,当球试图通过更新循环保持同步时,球会来回 Swing 。我可能已经对它进行了松散的编程,但这是我能想到的最好的。我希望对这种事情如何运作有更多了解的人可以帮助我澄清一些事情。

我的问题直截了当。我需要知道一种更好的方法来更有效地通过互联网发送球位置和球员位置。目前所需时间太长。不过,我可能会以错误的方式更新它。

流的构造方式:

    oostream = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
    oostream.flush();
    oistream = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));

这是玩家 2 的更新循环:

            IntData id = new IntData();

            while (running) {

                id.ballx = ballx;
                id.bally = bally;
                id.player2Y = player2Y;
                oostream.writeObject(id);
                oostream.flush();

                Thread.sleep(updaterate);

                id = (IntData) oistream.readObject();
                player1Y = id.player1Y;
                    ballx = id.ballx;
                bally = id.bally;

            }

玩家 1 是服务器主机。 这是玩家 1 的更新循环:

            IntData id = new IntData();

            while (running) {

                id = (IntData) oistream.readObject();
                player2Y = id.player2Y;
                ballx = id.ballx;
                bally = id.bally;

                Thread.sleep(updaterate);

                id.ballx = ballx;
                id.bally = bally;
                id.player1Y = player1Y;
                oostream.writeObject(id);
                oostream.flush();

            }

最佳答案

我建议不要对简单的原语使用完整序列化。使用 DataInputStream 等代替:

dostream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
distream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

然后阅读:

 ballx=distream.readInt();
 bally=distream.readInt();

并写为:

 dostream.writeInt(ballx);
 dostream.writeInt(bally);

另外我建议你不要 sleep 等待双方的数据。在其中一个上 hibernate ,让第二个在传输之前通过删除 Thread.sleep() 来等待完整的数据。

关于java - 创建一种通过网络发送整数的有效方法。传输控制协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19351159/

相关文章:

java - 在 Spring 3 中为组件扫描组织类的聪明方法是什么?

java - 为什么 KeyValue 采用公钥?

performance - Page Speed - 消除渲染阻塞

networking - 如何在 Fedora 19 中设置静态 IP

linux - 如何从 docker 容器管理主机网络命名空间

java - 在 Java 中更快地将 txt 文件读取到 mySQL 数据库

Java 游程长度解码(扩展压缩字符串)

使用 Big O(n log n) 或 Big O(log n) 复杂度的 Java 程序

c# - 编写文件 C# (.NET) 或 PERL 哪个更快?

Java - 端口监听程序的漏洞是什么?