Game Development Reference
In-Depth Information
One thing you should know right away
all the code samples in this chapter assume
a single-threaded environment. There are plenty of network programming examples
out there that use one thread per connection and blocking calls to every socket. This
may be an easy way to implement network communications, but it isn
'
t the most
efficient way.
Packet Classes
Data that is sent or received via sockets has a format, just like any file you read from
beginning to end. The format of the data will usually come in chunks, or packets, of
discrete units, each of which is essentially a stand-alone piece of data. The format and
interpretation of these packets is totally up to you. Just as you define the structure of
your data files, you can define the structure of your packet stream. These packets
might carry username and password data, data for events like
Change Game State
or
As your program reads data from a socket, it needs to have some way of determining
what kind of packet is coming in and how many bytes to expect. When the correct
number of bytes is ready, the packet is read from the socket as an atomic unit, encap-
sulated with a C++ packet object, and then handled by your game.
The exact opposite happens when you want to send a packet. The block of bytes that
makes up the packet is assembled, or streamed, into a memory buffer. The size of the
buffer is sent along with the packet as well
Most multiplayer games send binary data over network connections. This is because the
information in the packets contains things like game events, movement deltas, and
game commands that can be encoded very efficiently in a binary format. If this data
were sent in clear text, it would be much larger. Think of it as the same thing as storing
your data in a database or XML. XML might be easier to read, but it takes more space.
This packet class is for binary formatted packets. It allocates its own buffer of bytes
and stores the size of the buffer in the first four bytes, but note that it stores them in
network order. This is generally a good idea, even though I know I might never be
using this system on anything other than my Dell.
Move Actor,
or game commands like
Set Throttle to 100%.
class BinaryPacket
{
protected:
char *m_Data;
public:
inline BinaryPacket(char const * const data, u_long size);
inline BinaryPacket(u_long size);
 
 
Search WWH ::




Custom Search