12
Network
Programming
12.1 Network Overview
“Look, good against remotes is one thing. Good against the living? at’s something else.
—Han Solo
Who are we to argue with Han Solo? Unfortunately, our human opponents are not always
nearby when we want to play against them. If our computer is connected to a network, we
can play against other human opponents who are on the other side of the room or even on
the other side of the world.
In the network world, we hear the terms client and server. With networked games, the
client is the device the player is using, and the server is the device the clients are communi-
cating with. e client accepts input from the player and sends it to the server. e server
typically runs the game, receives input data from the client, applies it to the game, and sends
the state of the game back to the client. e clients use the state information received from
the server to display the game as seen by the player. is is the typical client/server model
used by most games.
e Internet and most local area networks use Internet protocol (IP). e Internet pro-
tocol is a set of rules that dene how information and hardware are to be congured so
that data may be sent from one location to another. However, IP does not dene specic
rules about how large les are to be sent and what should happen if an error occurs during
transmission. For those scenarios, there are higher-level protocols that work in conjunction
with IP.
364 12. Network Programming
TCP. Transmission control protocol (TCP) provides the reliable delivery of data. Large
messages are automatically broken into smaller IP-sized packets, transmitted, received,
and reassembled in order by the receiver. Packets that are lost during transmission are
automatically retransmitted. e reliability of TCP message delivery can result in long delays
(on the order of seconds) if packets are lost and must be retransmitted. For this reason,
TCP is typically not considered suitable for the delivery of real-time data. TCP establishes
a connection between the two devices; this connection is maintained until broken by one
or both devices. In our implementation, only one TCP connection is permitted at a time.
If the other device breaks the connection, an error will result when attempting to send or
receive data.
UDP. User datagram protocol (UDP) is a connectionless protocol. A connectionless protocol
supports communicating with multiple devices from a single interface. UDP provides no
guarantee of data delivery. Data packets may arrive out of order, may be duplicated, or may
not be delivered at all. UDP is typically used for time sensitive applications where the timely
delivery of data is more important than reliability.
12.1.1 Addresses
Each device on the network must have a unique IP address. e original addressing scheme,
known as IPv4, uses a 32-bit number for each address. is allows for 2
32
(4,294,967,296)
addresses. Because of the large number of devices now connected to the Internet and the
way these addresses are allocated, we are quickly running out of unused addresses. A new
addressing scheme, known as IPv6, has been introduced. IPv6 uses a 128-bit number for
each address. is allows for 2
128
(approximately 3.4 × 10
38
) addresses—to put it in perspec-
tive, with IPv6 there are enough addresses to give every grain of sand on the earth its own IP
address and still have a bunch le over. e IPv4 addressing scheme is still the most widely
used, so we will be using it in this book.
12.1.2 Port
Each addressable device also has a range of port numbers that are used. A port number is
a 16-bit number. is yields 2
16
(65,536) port numbers. We might equate the IP address
with the address of a building and the port number with a room in the building. Port
numbers 0–1023 are predened for use in well-known services and should be avoided.
Port numbers 1024–65535 may be freely used.
12.1.3 Socket
In network programming, a socket is an interface to the network. For this reason, network
programming is oen referred to as socket programming. For Windows programming, Win-
sock is the API that supports the creation of sockets that support TCP/IP and UDP/IP.
Sockets may be congured as blocking or nonblocking. A blocking socket does not return
from function calls to send or receive data until the operation is complete. A nonblocking
socket always returns immediately, even if no data was sent or received. Given the real-time
nature of many games, we cannot aord to wait for socket operations to complete. If block-
ing sockets were used, we would need to write a multithreaded application with a separate
36512.3. Initialize the Network
thread to handle communications. Writing multithreaded programs requires additional
complexity, which we would like to avoid, so we will be using nonblocking sockets.
12.2 The Net Class
In order to add network support to our game engine, we will create a new Net class. e
Net class will contain the code to create a nonblocking Winsock socket that we may use
to send and receive data. e socket will be congured to use either TCP/IP or UDP/
IP network communications. e Network class is contained in two les: net.h and
net.cpp. e net.h le includes winsock2.h. ere is also an older winsock.h le.
If these two header les are included in the same project, errors will occur. Unfortunately,
windows.h automatically, and perhaps incorrectly, includes winsock.h. e statement
#define WIN32_LEAN_AND_MEAN prevents windows.h from loading several header
les, including winsock.h. When working with the Net class, make sure all of the project’s
header les dene WIN32_LEAN_AND_MEAN prior to any include statements.
12.3 Initialize the Network
e rst step in using Winsock is to call the WSAStartup function. is function allows
the application to call additional Winsock functions. When nished using Winsock, an
application must call WSACleanup to free the resources allocated by WSAStartup. e
WSACleanup function must be called for every call made to WSAStartup.
int WSAStartup(
WORD wVersionRequested,
LPWSADATA lpWSAData
);
e parameters are:
• wVersionRequested. e highest version of Windows sockets that may be used.
We will be using version 2.2. e Winsock DLL, Ws_32.dll, supports applications
that use Winsock specications from version 1.0 through 2.2.
• lpWSAData. A pointer to a WSAData structure that receives information about the
Windows sockets implementation.
e return value is 0 on success or an error code on failure. We will examine the error
codes in more detail later in this chapter. WSAStartup is called as part of our initialize
function, as seen in Listing 12.1(a).
//========================================================================
// Initialize network
// Protocol = UDP or TCP
// Called by netCreateServer and netCreatClient
// Pre:
// port = Port number
366 12. Network Programming
// protocol = UDP or TCP
// Post:
// Returns two-part int code on error
// The low 16 bits contains Status code as defined in net.h
// The high 16 bits contains "Windows Socket Error Code"
//========================================================================
int Net::initialize(int port, int protocol)
{
unsigned long ul = 1;
int nRet;
int status;
if(netInitialized) // If network currently initialized
closeSockets(); // Close current network and start over
mode = UNINITIALIZED;
status = WSAStartup(0x0202, &wsd); // Initiate the use of winsock 2.2
if (status != 0)
return ( (status << 16) + NET_INIT_FAILED);
Listing 12.1(a). Calling WSAStartup in the Net::initialize function.
12.3.1 Create the Socket
Aer Winsock is initialized, the next step is to create a network socket. e socket func-
tion creates a socket of the specied address family, type, and protocol.
SOCKET WSAAPI socket(
int af,
int type,
int protocol
);
e parameters are:
• af. e address family. e possible values are dened in the Winsock2.h header
le or in the Ws2def.h header le on the Windows SDK released for Windows
Vista and later. We want the Internet address family for IPv4, which is AF_INET.
e supported types are:
AF_UNSPEC. Unspecied.
AF_INET. Internet protocol version 4 (IPv4).
AF_INET6. Internet protocol version 6 (IPv6).
AF_IPX. e IPX/SPX address family; not supported on Windows Vista and later.
AF_APPLETALK. e AppleTalk address famil; not supported on Windows
Vista and later.
AF_NETBIOS. e NetBIOS address family; not supported on 64-bit versions
of windows.
36712.3. Initialize the Network
AF_IRDA. e Infrared Data Association (IrDA) address family.
AF_BTH. e Bluetooth address family.
• type. e type of socket to create. e supported types are:
SOCK_STREAM. Reliable connection-based byte stream. Uses TCP with the In-
ternet address family (AF_INET or AF_INET6).
SOCK_DGRAM. A socket that supports datagrams, which are connection-
less and unreliable. Uses UDP with the Internet address family (AF_INET or
AF_INET6).
SOCK_RAW. A raw socket that allows an application to manipulate the protocol
header.
SOCK_RDM. Reliable datagram message socket.
SOCK_SEQPACKET. A reliable sequence packet.
• protocol. e protocol used. Many types are supported. e only two types we
are interested in are:
IPPROTO_TCP. e af parameter must be either AF_INET or AF_INET6, and
the type parameter must be SOCK_STREAM.
IPPROTO_UDP. e af parameter must be either AF_INET or AF_INET6 and
the type parameter must be SOCK_DGRAM.
e return value is a socket reference unless an error occurred, in which case
INVALID_SOCKET is returned. A detailed error code may be obtained by calling the WSA
GetLastError function.
Our initialize function accepts a protocol parameter that is used to determine
which parameters to use when creating the socket (Listing 12.1(b)).
switch (protocol)
{
case UDP: // UDP
// Create UDP socket and bind it to a local interface and port
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == INVALID_SOCKET)
{
WSACleanup();
status = WSAGetLastError(); // Get detailed error
return ( (status << 16) + NET_INVALID_SOCKET);
}
type = UDP;
break;
case TCP: // TCP
// Create TCP socket and bind it to a local interface and port
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.96.247