Game Development Reference
In-Depth Information
SOCKET NetListenSocket::AcceptConnection(unsigned int *pAddr)
{
SOCKET new_sock;
struct sockaddr_in sock;
int size = sizeof(sock);
if ((new_sock = accept(m_sock, (struct sockaddr *)&sock, &size))==
INVALID_SOCKET)
return INVALID_SOCKET;
if (getpeername(new_sock, (struct sockaddr *)&sock, &size) == SOCKET_ERROR)
{
closesocket(new_sock);
return INVALID_SOCKET;
}
*pAddr = ntohl(sock.sin_addr.s_addr);
return new_sock;
}
This method is a simple wrapper around
accept()
, which does all the heavy lifting.
There
s a utility function,
getpeername()
, which basically grabs the IP address of
the new client and returns it in an output parameter.
You should be asking two questions right now. First, why don
'
t I simply create a
NetSocket()
object right here and return that? Second, who or what actually calls
this
AcceptConnect()
method? The answer to the first question is: I don
'
'
t return a
NetSocket
object because I assume you
ll want to create your own child class that
inherits from
NetSocket
but overloads the
VHandleInput()
and
VHandleOut-
put()
methods. You
'
ll see a class that does exactly that when I show you some more
server-side code. Here
'
'
s the answer to the second question: The server-side code
itself! You
'
ll see that in a few pages.
Sockets need a socket manager, whether they are on a client or on a server. A socket
manager organizes multiple sockets into a manageable group, takes care of handling
the initialization and shutdown of the sockets system, and provides some useful util-
ity functions. It also provides a useful base class for more specialized socket managers
for servers and clients.
class BaseSocketManager
{
public:
BaseSocketManager();
virtual ~BaseSocketManager() { Shutdown(); }