![]() |
Receiving a packet
When a packet comes in on the network, i.e. Receive returns non-zero, there are three steps involved in handling it. The Multiplayer class handles step one and three for you, so if you derive from it you can just override ProcessUnhandledPacket and the public functions you can skip straight to step two. 1. Determine the packet type. This is returned by the following code: unsigned char GetPacketIdentifier(Packet *p) { if ((unsigned char)p->data[0] == ID_TIMESTAMP) return (unsigned char) p->data[sizeof(unsigned char) + sizeof(unsigned long)]; else return (unsigned char) p->data[0]; } Receiving a structure If you originally sent a structure, you can cast it back as follows: // If you override the Multiplayer class this line would be in ProcessUnhandledPacket if (packetIdentifier==/* User assigned packet identifier here */) DoMyPacketHandler(packet); // Put this anywhere you want. Inside the state class that handles the game is a good place void DoMyPacketHandler(Packet *packet) { // Cast the data to the appropriate type of struct MyStruct *s = (MyStruct *) packet->data; assert(p->length == sizeof(MyStruct)); if (p->length != sizeof(MyStruct)) return; // Using NetworkIDGenerator and the macro defined therein, get a pointer to the object specified in the struct MyObject *object = (MyObject *) GET_OBJECT_FROM_ID(s.objectId); // Perform the functionality for this type of packet object->DoFunction(); } Usability Comments
3. Deallocate the packet by passing it to the method virtual void DeallocatePacket(Packet *packet)=0; of the network interface that you got it from. Receiving a bitstream If you originally sent a bitstream, we create a bitstream to unparse the data in the same order we wrote it. We create a bitstream, using the data and the length of the packet. We then use the Read functions where we formerly used the Write functions, the ReadCompressed functions where we formerly used WriteCompressed, and follow the same logical branching if we wrote any data conditionally. This is all shown in the following example which would read in the data for the mine we created in creating packets. 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); bool isAtZero; myBitStream.Read(isAtZero); if (isAtZero==false) { x=0.0f; y=0.0f; z=0.0f; } else { myBitStream.Read(x); myBitStream.Read(y); myBitStream.Read(z); } myBitStream.Read(objectID); // In the struct this is ObjectID objectId myBitStream.Read(playerId); // In the struct this is PlayerID playerId } |
![]() |
Index Creating Packets Sending Packets |