Creating an efficient way of sending integers over a network. TCP

Deadly 提交于 2019-12-02 00:02:21

I suggest not using full serialization for simply primitives. use DataInputStream and the like instead:

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

Then read with:

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

and write as:

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

Also I suggest you not sleep awaiting data on both sides. Sleep on one and let the second simply await for a full set of data before transmitting by cutting out the Thread.sleep() there.

this is the function im using everytime for it its pretty simple and works perfectly but the function is not rly needed (just very easy to use)

public static final byte[] parseIntToByteArray(int i){
    byte[] b = {(byte)(i >> 24),
                (byte)(i >> 16),
                (byte)(i >> 8),
                (byte)i};
    return b;
}

to get it back:

int xy = (bytearray[0] << 24 | bytearray[1] << 16 | bytearray[2] << 8 | bytearray[3]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!