码迷,mamicode.com
首页 > Web开发 > 详细

RakNet发送与接收数据

时间:2016-12-23 13:32:59      阅读:286      评论:0      收藏:0      [点我收藏+]

标签:rect   timestamp   jenkins   handler   directly   sys   manual   接收   com   

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 }

RakNet发送与接收数据

标签:rect   timestamp   jenkins   handler   directly   sys   manual   接收   com   

原文地址:http://www.cnblogs.com/coolbear/p/6214294.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!