微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

创建一种通过网络发送整数的有效方法TCP协议

如何解决创建一种通过网络发送整数的有效方法TCP协议

我建议不要对简单的原语使用完全序列化。使用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);

另外,我建议您不要等待双方的数据。睡眠一个,让第二个简单地等待完整的数据集,然后再通过剪切在Thread.sleep()那里等待。

解决方法

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

我的程序是一个乒乓球游戏。一旦运行,它将创建一个服务器,客户端 现在可以
使用对象流通过Internet连接到该服务器。一切运行良好,但效率似乎不高。意思是说,当球试图通过 更新循环
保持同步时,球来回utter停。我可能对其进行了宽松的编程,但这是我能想到的最好的方法。我希望对这种事情如何工作有更多了解的人可以帮助我解决一些问题。

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

流的构造方式:

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

            }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。