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

xtr*_*tré 2 java performance networking byte data-stream

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

我的节目是乒乓球比赛.一旦运行,它就会创建一个服务器,客户端现在使用对象流通过Internet连接到该服务器.一切都运作良好,但似乎效率不高.我的意思是球在试图通过更新循环保持同步时来回震动.我可能已经松散地编程了,但这是我能想到的最好的.我希望有更多了解这种事情如何运作的人可以帮助我澄清一些事情.

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

流的构建方式:

    oostream = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
    oostream.flush();
    oistream = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
Run Code Online (Sandbox Code Playgroud)

这是玩家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;

            }
Run Code Online (Sandbox Code Playgroud)

播放器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();

            }
Run Code Online (Sandbox Code Playgroud)

ζ--*_*ζ-- 5

我建议不要使用完全序列化的简单原语.使用DataInputStream之类的:

dostream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
distream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
Run Code Online (Sandbox Code Playgroud)

然后阅读:

 ballx=distream.readInt();
 bally=distream.readInt();
Run Code Online (Sandbox Code Playgroud)

写作:

 dostream.writeInt(ballx);
 dostream.writeInt(bally);
Run Code Online (Sandbox Code Playgroud)

另外我建议你不要等待双方的数据.睡在一个上,让第二个只是等待一整套数据,然后通过切断Thread.sleep()那里传输.