Game Development Reference
In-Depth Information
m_sock = INVALID_SOCKET;
}
}
The two different constructors handle two different cases when creating network
connections. The default constructor handles the case where a client wishes to con-
nect to a server. The second constructor, using an already initialized socket handle,
handles the server side.
The next method is called when you want to connect a new NetSocket to a server
listening for connections.
bool NetSocket::Connect(unsigned int ip, unsigned int port, bool forceCoalesce)
{
struct sockaddr_in sa;
int x = 1;
// create the socket handle
if ((m_sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
return false;
// set socket options - in this case turn off Nagle algorithm if desired
if (!forceCoalesce)
setsockopt(m_sock, IPPROTO_TCP, TCP_NODELAY, (char *)&x, sizeof(x));
// last step - set the IP address and port of the server, and call connect()
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = htonl(ip);
sa.sin_port = htons(port);
if (connect(m_sock, (struct sockaddr *)&sa, sizeof(sa)))
{
closesocket(m_sock);
m_sock = INVALID_SOCKET;
return false;
}
return true;
}
Just as described in the socket primer earlier in this chapter, the process for connect-
ing a socket to a server has three steps. First, you create the socket handle. Second,
you call the socket options. In this case, NetSocket supports disabling the packet-
grouping algorithm by default. This increases network traffic, but it can improve per-
formance if you send/receive tons of tiny packets, like games tend to do. Finally, you
connect the socket to the remote server.
 
Search WWH ::




Custom Search