java raknet_RakNet发送与接收数据

http://www.jenkinssoftware.com/raknet/manual/creatingpackets.html

Creating Packets with Bitstreams

Write less data with bitstreams

Lets take our mine example above and use a bitstream to write it out instead. We have all the same data as before.

MessageID useTimeStamp; // Assign this to ID_TIMESTAMP

RakNet::Time timeStamp; // Put the system time in here returned by RakNet::GetTime()

MessageID typeId; // This will be assigned to a type I've added after ID_USER_PACKET_ENUM, lets say ID_SET_TIMED_MINE

useTimeStamp = ID_TIMESTAMP;

timeStamp = RakNet::GetTime();

typeId=ID_SET_TIMED_MINE;

Bitstream myBitStream;

myBitStream.Write(useTimeStamp);

myBitStream.Write(timeStamp);

myBitStream.Write(typeId);

// Assume we have a Mine* mine object

myBitStream.Write(mine->GetPosition().x);

myBitStream.Write(mine->GetPosition().y);

myBitStream.Write(mine->GetPosition().z);

myBitStream.Write(mine->GetNetworkID()); // In the struct this is NetworkID networkId

myBitStream.Write(mine->GetOwner()); // In the struct this is SystemAddress systemAddress

Common mistake!

When writing the first byte to a bitstream, be sure to cast it to (MessageID) or (unsigned char). If you just write the enumeration directly you will be writing a full integer (4 bytes).

Right:

bitStream->Write((MessageID)ID_SET_TIMED_MINE);

Wrong:

bitStream->Write(ID_SET_TIMED_MINE);

In the second case, RakNet will see the first byte is 0, which is reserved internally to ID_INTERNAL_PING, and you will never get it.

http://www.jenkinssoftware.com/raknet/manual/receivingpackets.html

void DoMyPacketHandler(Packet *packet)

{

Bitstream myBitStream(packet->data, packet->length, false); // The false is for efficiency so we don't make a copy of the passed data

myBitStream.Read(useTimeStamp);

myBitStream.Read(timeStamp);

myBitStream.Read(typeId);

myBitStream.Read(x);

myBitStream.Read(y);

myBitStream.Read(z);

myBitStream.Read(networkID); // In the struct this is NetworkID networkId

myBitStream.Read(systemAddress); // In the struct this is SystemAddress systemAddress

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值