开发者

Network Order short (Java)

开发者 https://www.devze.com 2022-12-15 12:15 出处:网络
I need to send a Network Order short for a game server I\'m writing using Java. I read about network order, but I cou开发者_JAVA百科ldn\'t find any details about a short that is sent before the data.

I need to send a Network Order short for a game server I'm writing using Java. I read about network order, but I cou开发者_JAVA百科ldn't find any details about a short that is sent before the data. Could someone explain to me what it is, and how to send one to a client with Java?


Java NIO bytes buffers have support for changing the byte order. Network byte order is Big Endian therefore.

// Allocate a big endian byte buffer
ByteBuffer bb = ByteBuffer.allocate(4096);
bb.order(ByteOrder.BIG_ENDIAN);
bb.putShort(12345);

// Write the buffer to an NIO channel
bb.flip();
channel.write(bb);

Byte Order is the order in which the bytes for numerical values that are larger than a single byte are stored. There are 2 flavours Big Endian (most significant byte first) and Little Endian (least significant byte first).


In java, a short int is a 2 byte quantity. Network byte order send the high-order byte first, followed by the next highest-order byte and so on, with the low order byte sent last. If you have an OutputStream o, and a short i, then

o.write((i >> 8) & 0xff);
o.write(i & 0xff);

send the short in network byte order. I recommend using a DataOutputStream which has a method writeShort() (and writeInt, writeLong, etc.) which automatically write in network byte order.


You can wrap your OutputStream with DataOutputStream.

You can then use DataOutputStream.writeShort. By contract the method writes data in network order.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号