天行健 君子当自强而不息

创建游戏内核(25)【OO改良版】【完】

 

本篇是创建游戏内核(24)【OO改良版】的续篇,关于该内核的细节说明请参阅创建游戏内核(25)


接口:

//====================================================================================
// This class encapsulate client how to communicate with server.
//====================================================================================
typedef class NETWORK_CLIENT
{
public:
    NETWORK_CLIENT();
    
virtual ~NETWORK_CLIENT();

    IDirectPlay8Client* get_client();

    BOOL init();
    BOOL shutdown();

    BOOL connnect(
const GUID* guid_adapter, 
                  
const char* server_ip, long server_port, 
                  
const char* player_name,
                  
const char* session_name, const char* session_pwd);

    BOOL disconnect();
    BOOL is_connected();

    BOOL send_data(
void* data, ulong size, ulong flags);
    BOOL send_text(
char* text, ulong flags);

    BOOL get_local_ip(
char* local_ip);
    
long get_server_port();
    BOOL get_name(
char* name);
    BOOL get_session_name(
char* session_name);
    BOOL get_session_pwd(
char* session_pwd);

    
static HRESULT WINAPI network_msg_handler(PVOID user_context, DWORD msg_id, PVOID msg_buffer);

protected:
    
virtual BOOL _add_player_to_group(DPNMSG_ADD_PLAYER_TO_GROUP* msg) { return TRUE; }
    
virtual BOOL _async_op_complete(DPNMSG_ASYNC_OP_COMPLETE* msg) { return TRUE; }
    
virtual BOOL _client_info(DPNMSG_CLIENT_INFO* msg) { return TRUE; }
    
virtual BOOL _connect_complete(DPNMSG_CONNECT_COMPLETE* msg) { return TRUE; }
    
virtual BOOL _create_group(DPNMSG_CREATE_GROUP* msg) { return TRUE; }
    
virtual BOOL _create_player(DPNMSG_CREATE_PLAYER* msg) { return TRUE; }
    
virtual BOOL _destroy_group(DPNMSG_DESTROY_GROUP* msg) { return TRUE; }
    
virtual BOOL _destroy_player(DPNMSG_DESTROY_PLAYER* msg) { return TRUE; }
    
virtual BOOL _enum_hosts_query(DPNMSG_ENUM_HOSTS_QUERY* msg) { return TRUE; }
    
virtual BOOL _enum_hosts_response(DPNMSG_ENUM_HOSTS_RESPONSE* msg) { return TRUE; }
    
virtual BOOL _group_info(DPNMSG_GROUP_INFO* msg) { return TRUE; }
    
virtual BOOL _host_migrate(DPNMSG_HOST_MIGRATE* msg) { return TRUE; }
    
virtual BOOL _indicate_connect(DPNMSG_INDICATE_CONNECT* msg) { return TRUE; }
    
virtual BOOL _indicated_connect_aborted(DPNMSG_INDICATED_CONNECT_ABORTED* msg) { return TRUE; }
    
virtual BOOL _peer_info(DPNMSG_PEER_INFO* msg) { return TRUE; }
    
virtual BOOL _receive(DPNMSG_RECEIVE* msg) { return TRUE; }
    
virtual BOOL _remove_player_from_group(DPNMSG_REMOVE_PLAYER_FROM_GROUP* msg) { return TRUE; }
    
virtual BOOL _return_buffer(DPNMSG_RETURN_BUFFER* msg) { return TRUE; }
    
virtual BOOL _send_complete(DPNMSG_SEND_COMPLETE* msg) { return TRUE; }
    
virtual BOOL _server_info(DPNMSG_SERVER_INFO* msg) { return TRUE; }
    
virtual BOOL _terminate_session(DPNMSG_TERMINATE_SESSION* msg) { return TRUE; }

protected:
    IDirectPlay8Client* m_client;

    BOOL                m_is_connected;

    
char                m_server_ip[MAX_PATH];
    
long                m_server_port;

    
char                m_name[MAX_PATH];

    
char                m_session_name[MAX_PATH];
    
char                m_session_pwd[MAX_PATH];    
} *NETWORK_CLIENT_PTR;

实现:
//---------------------------------------------------------------------------------
// Constructor, zero member data.
//---------------------------------------------------------------------------------
NETWORK_CLIENT::NETWORK_CLIENT()
{
    memset(
this, 0, sizeof(*this)-4);
}

//---------------------------------------------------------------------------------
// Destructor, shutdown this client connection.
//---------------------------------------------------------------------------------
NETWORK_CLIENT::~NETWORK_CLIENT()
{
    shutdown();
}

//---------------------------------------------------------------------------------
// Shutdown this client connection.
//---------------------------------------------------------------------------------
BOOL NETWORK_CLIENT::shutdown()
{
    
if(! disconnect())
        
return FALSE;

    m_client = NULL;
    
return TRUE;
}

//---------------------------------------------------------------------------------
// Disconnet this client to any clients and servers.
//---------------------------------------------------------------------------------
BOOL NETWORK_CLIENT::disconnect()
{
    
if(m_client)
    {
        
if(FAILED(m_client->Close(0)))
            
return FALSE;
    }
    
    m_is_connected    = FALSE;
    m_server_port     = 0;
    m_server_ip[0]    = 0;
    m_name[0]         = 0;
    m_session_name[0] = 0;
    m_session_pwd[0]  = 0;

    
return TRUE;
}

//---------------------------------------------------------------------------------
// Return pointer to DirectPlay client object.
//---------------------------------------------------------------------------------
IDirectPlay8Client* NETWORK_CLIENT::get_client()
{
    
return m_client;
}

//---------------------------------------------------------------------------------
// Create DirectPlay client object.
//---------------------------------------------------------------------------------
BOOL NETWORK_CLIENT::init()
{
    
// shutdown older connection first
    shutdown();

    
// create the client object
    if(FAILED(CoCreateInstance(CLSID_DirectPlay8Client, NULL, CLSCTX_INPROC, IID_IDirectPlay8Client,
                               (
void**) &m_client)))
        
return FALSE;

    
return TRUE;
}

//---------------------------------------------------------------------------------
// Connect to server.
//---------------------------------------------------------------------------------
BOOL NETWORK_CLIENT::connnect(const GUID* guid_adapter, 
                              
const char* server_ip, long server_port, 
                              
const char* player_name, 
                              
const char* session_name, const char* session_pwd)
{
    
// disconnnect older connection first
    disconnect();

    
// error checking
    if(m_client == NULL || session_name == NULL || player_name == NULL || server_ip == NULL)
        
return FALSE;

    
if((m_server_port = server_port) == 0)
        
return FALSE;

    
// initialize the client object
    if(FAILED(m_client->Initialize((PVOID)this, network_msg_handler, 0)))
        
return FALSE;

    
// assign client information

    DPN_PLAYER_INFO _player_info;
    WCHAR _w_player_name[MAX_PATH];

    ZeroMemory(&_player_info, 
sizeof(DPN_PLAYER_INFO));

    mbstowcs(_w_player_name, player_name, strlen(player_name)+1);

    _player_info.dwSize      = 
sizeof(DPN_PLAYER_INFO);
    _player_info.dwInfoFlags = DPNINFO_NAME | DPNINFO_DATA;
    _player_info.pwszName    = _w_player_name;

    m_client->SetClientInfo(&_player_info, NULL, NULL, DPNSETCLIENTINFO_SYNC);

    
// create address objects

    IDirectPlay8Address* _dp_address = NULL;
    IDirectPlay8Address* _dp_device  = NULL;

    
if(FAILED(CoCreateInstance(CLSID_DirectPlay8Address, NULL, CLSCTX_INPROC, IID_IDirectPlay8Address,
                               (
void**) &_dp_address)))
        
return FALSE;

    
if(FAILED(CoCreateInstance(CLSID_DirectPlay8Address, NULL, CLSCTX_INPROC, IID_IDirectPlay8Address,
                               (
void**) &_dp_device)))
    {
        _dp_address->Release();
        
return FALSE;
    }

    
// set protocols
    _dp_address->SetSP(&CLSID_DP8SP_TCPIP);
    _dp_device->SetSP(&CLSID_DP8SP_TCPIP);

    
// set the port - must not be 0
    _dp_address->AddComponent(DPNA_KEY_PORT, &m_server_port, sizeof(DWORD), DPNA_DATATYPE_DWORD);    

    WCHAR _w_server_ip[MAX_PATH];

    
// set the host ip address
    mbstowcs(_w_server_ip, server_ip, strlen(server_ip)+1);
    _dp_address->AddComponent(DPNA_KEY_HOSTNAME, _w_server_ip, (DWORD) ((wcslen(_w_server_ip) + 1) * 
sizeof(WCHAR)),
                             DPNA_DATATYPE_STRING);

    
// set the adapter
    _dp_address->AddComponent(DPNA_KEY_DEVICE, guid_adapter, sizeof(GUID), DPNA_DATATYPE_GUID);
    _dp_device->AddComponent(DPNA_KEY_DEVICE, guid_adapter, 
sizeof(GUID), DPNA_DATATYPE_GUID);

    WCHAR _w_session_name[MAX_PATH], _w_session_pwd[MAX_PATH];

    
// record the session name and password
    strcpy(m_session_name, session_name);
    mbstowcs(_w_session_name, session_name, MAX_PATH);

    
if(session_pwd)
    {
        strcpy(m_session_pwd, session_pwd);
        mbstowcs(_w_session_pwd, session_pwd, MAX_PATH);
    }

    
// setup the application description structure

    DPN_APPLICATION_DESC _app_desc;

    ZeroMemory(&_app_desc, 
sizeof(DPN_APPLICATION_DESC));

    _app_desc.dwSize          = 
sizeof(DPN_APPLICATION_DESC);
    _app_desc.dwFlags         = DPNSESSION_CLIENT_SERVER;
    _app_desc.guidApplication = g_app_guid;
    _app_desc.pwszSessionName = _w_session_name;

    
if(session_pwd)
    {
        _app_desc.pwszPassword = _w_session_pwd;
        _app_desc.dwFlags |= DPNSESSION_REQUIREPASSWORD;
    }

    DPNHANDLE _async_handle;

    BOOL _ret_value = TRUE;

    
// connect to server    
    HRESULT _rv = m_client->Connect(&_app_desc, _dp_address, _dp_device, NULL, NULL, NULL, 0, NULL, &_async_handle, 0);

    
if(FAILED(_rv))
    {
        _ret_value = FALSE;

        
if(_rv == DPNERR_HOSTREJECTEDCONNECTION)
            err_msg_box("Host reject connection.");
        
else if(_rv == DPNERR_INVALIDAPPLICATION)
            err_msg_box("The GUID supplied for the application is invalid.");
        
else if(_rv == DPNERR_INVALIDDEVICEADDRESS)
            err_msg_box("The address for the local computer or adapter is invalid.");
        
else if(_rv == DPNERR_INVALIDFLAGS)
            err_msg_box("The flags passed to this method are invalid.");
        
else if(_rv == DPNERR_INVALIDHOSTADDRESS)
            err_msg_box("The specified remote address is invalid.");
        
else if(_rv == DPNERR_INVALIDINSTANCE)
            err_msg_box("The GUID for the application instance is invalid.");
        
else if(_rv == DPNERR_INVALIDINTERFACE)
            err_msg_box("The interface parameter is invalid. This value will be returned in a connect request"
            " if the connecting player was not a client in a client/server game or a peer in a peer-to-peer game.");
        
else if(_rv == DPNERR_INVALIDPASSWORD)        
            err_msg_box("An invalid password was supplied when attempting to join a session that requires a password.");
        
else if(_rv == DPNERR_NOCONNECTION)
            err_msg_box("No communication link was established.");
        
else if(_rv == DPNERR_NOTHOST)
            err_msg_box("An attempt by the client to connect to a nonhost computer.");
        
else if(_rv == DPNERR_SESSIONFULL)
            err_msg_box("The maximum number of players allotted for the session has been reached.");
        
else if(_rv == DPNERR_ALREADYCONNECTED)
            err_msg_box("The object is already connected to the session.");
    }   
    
    _dp_address->Release();
    _dp_device->Release();
    
return _ret_value;
}

//---------------------------------------------------------------------------------
// Judge whether client has connected to server.
//---------------------------------------------------------------------------------
BOOL NETWORK_CLIENT::is_connected()
{
    
return m_is_connected;
}

//---------------------------------------------------------------------------------
// Send data to server.
//---------------------------------------------------------------------------------
BOOL NETWORK_CLIENT::send_data(void* data, ulong size, ulong flags)
{
    
// error checking
    if(m_client == NULL)
        
return FALSE;

    
// build a data structure

    DPN_BUFFER_DESC _buffer_desc;

    _buffer_desc.dwBufferSize = size;
    _buffer_desc.pBufferData  = (BYTE*) data;

    DPNHANDLE _async_handle;

    
if(FAILED(m_client->Send(&_buffer_desc, 1, 0, NULL, &_async_handle, flags)))
        
return FALSE;

    
return TRUE;
}

//---------------------------------------------------------------------------------
// Send text to server.
//---------------------------------------------------------------------------------
BOOL NETWORK_CLIENT::send_text(char* text, ulong flags)
{
    
// error checking
    if(m_client == NULL || text == NULL)
        
return FALSE;

    
return send_data(text, (ulong)strlen(text) + 1, flags);
}

//---------------------------------------------------------------------------------
// Get local ip address.
//---------------------------------------------------------------------------------
BOOL NETWORK_CLIENT::get_local_ip(char* local_ip)
{
    WSADATA _wsa_data;

    
if(WSAStartup(MAKEWORD(1, 0), &_wsa_data))
        
return FALSE;

    
char _local_name[MAX_PATH];
    gethostname(_local_name, MAX_PATH);

    HOSTENT* _host_ent;

    
if((_host_ent = gethostbyname(_local_name)) == NULL)
    {
        WSACleanup();
        
return FALSE;
    }

    
char* _ip_addr = inet_ntoa(*((in_addr*) _host_ent->h_addr_list[0]));
    
    WSACleanup();

    
if(_ip_addr == NULL)
        
return FALSE;

    strcpy(local_ip, _ip_addr);

    
return TRUE;
}

//---------------------------------------------------------------------------------
// Return port which used to connect to server.
//---------------------------------------------------------------------------------
long NETWORK_CLIENT::get_server_port()
{
    
return m_server_port;
}


//---------------------------------------------------------------------------------
// Return name.
//---------------------------------------------------------------------------------
BOOL NETWORK_CLIENT::get_name(char* name)
{
    
if(name == NULL)
        
return FALSE;

    strcpy(name, m_name);
    
return TRUE;
}

//---------------------------------------------------------------------------------
// Get session name.
//---------------------------------------------------------------------------------
BOOL NETWORK_CLIENT::get_session_name(char* session_name)
{
    
if(session_name == NULL)
        
return FALSE;

    strcpy(session_name, m_session_name);
    
return TRUE;
}

//---------------------------------------------------------------------------------
// Get session password.
//---------------------------------------------------------------------------------
BOOL NETWORK_CLIENT::get_session_pwd(char* session_pwd)
{
    
if(session_pwd == NULL)
        
return FALSE;

    strcpy(session_pwd, m_session_pwd);
    
return TRUE;
}

//---------------------------------------------------------------------------------
// Message handler.
//---------------------------------------------------------------------------------
HRESULT WINAPI NETWORK_CLIENT::network_msg_handler(PVOID user_context, DWORD msg_id, PVOID msg_buffer)
{
    NETWORK_CLIENT_PTR _client;
    DPNMSG_CONNECT_COMPLETE* _msg_connect_complte;

    
if((_client = (NETWORK_CLIENT_PTR) user_context) == NULL)
        
return E_FAIL;

    
switch(msg_id)
    {
    
case DPN_MSGID_ADD_PLAYER_TO_GROUP:
      
if(_client->_add_player_to_group((DPNMSG_ADD_PLAYER_TO_GROUP*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_ASYNC_OP_COMPLETE:
      
if(_client->_async_op_complete((DPNMSG_ASYNC_OP_COMPLETE*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_CLIENT_INFO:
      
if(_client->_client_info((DPNMSG_CLIENT_INFO*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_CONNECT_COMPLETE:
        
// update connection information

        _msg_connect_complte = (DPNMSG_CONNECT_COMPLETE*) msg_buffer;

        
if(_msg_connect_complte->hResultCode == S_OK)
            _client->m_is_connected = TRUE;

        
if(_client->_connect_complete((DPNMSG_CONNECT_COMPLETE*) msg_buffer))
            
return S_OK;

        
break;

    
case DPN_MSGID_CREATE_GROUP:
      
if(_client->_create_group((DPNMSG_CREATE_GROUP*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_CREATE_PLAYER:
      
if(_client->_create_player((DPNMSG_CREATE_PLAYER*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_DESTROY_GROUP:
      
if(_client->_destroy_group((DPNMSG_DESTROY_GROUP*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_DESTROY_PLAYER:
      
if(_client->_destroy_player((DPNMSG_DESTROY_PLAYER*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_ENUM_HOSTS_QUERY:
      
if(_client->_enum_hosts_query((DPNMSG_ENUM_HOSTS_QUERY*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_ENUM_HOSTS_RESPONSE:
      
if(_client->_enum_hosts_response((DPNMSG_ENUM_HOSTS_RESPONSE*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_GROUP_INFO:
      
if(_client->_group_info((DPNMSG_GROUP_INFO*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_HOST_MIGRATE:
      
if(_client->_host_migrate((DPNMSG_HOST_MIGRATE*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_INDICATE_CONNECT:
      
if(_client->_indicate_connect((DPNMSG_INDICATE_CONNECT*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_INDICATED_CONNECT_ABORTED:
      
if(_client->_indicated_connect_aborted((DPNMSG_INDICATED_CONNECT_ABORTED*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_PEER_INFO:
      
if(_client->_peer_info((DPNMSG_PEER_INFO*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_RECEIVE:
      
if(_client->_receive((DPNMSG_RECEIVE*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_REMOVE_PLAYER_FROM_GROUP:
      
if(_client->_remove_player_from_group((DPNMSG_REMOVE_PLAYER_FROM_GROUP*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_RETURN_BUFFER:
      
if(_client->_return_buffer((DPNMSG_RETURN_BUFFER*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_SEND_COMPLETE:
      
if(_client->_send_complete((DPNMSG_SEND_COMPLETE*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_SERVER_INFO:
      
if(_client->_server_info((DPNMSG_SERVER_INFO*) msg_buffer))
        
return S_OK;
      
break;

    
case DPN_MSGID_TERMINATE_SESSION:
      _client->m_is_connected = FALSE;
      
if(_client->_terminate_session((DPNMSG_TERMINATE_SESSION*) msg_buffer))
        
return S_OK;
      
break;
    }

    
return E_FAIL;
}

posted on 2007-10-14 18:09 lovedday 阅读(342) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


公告

导航

统计

常用链接

随笔分类(178)

3D游戏编程相关链接

搜索

最新评论