⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 network.cpp

📁 网络游戏通用架构, 这是基于boost和libevent写的一个程序
💻 CPP
字号:
#include "network.h"


Network::Network()
{
    Connection::_network= this;
}


Network::~Network()
{
}


int Network::init(void)
{
    socket_init();
    event_init();

    return 0;
}


void Network::breathe(void)
{
    if( _threaded ){
        event_loop( EVLOOP_ONCE );
    }else{
        event_loop( EVLOOP_ONCE | EVLOOP_NONBLOCK );
    }
}


void Network::shutdown(void)
{
    recursive_mutex::scoped_lock lock( _mutex );
    for( list<Connection*>::iterator itor= _connections.begin(); itor!=_connections.end(); ++itor ){
        delete (*itor);
        (*itor)= NULL;
    }
    sockets_shutdown();
}


int Network::listen( int __port, int __backlog )
{
    Connection* conn= NULL;
    try{
        conn= new Connection;
    }catch( exception& e ){
        cerr << "Create listen connection failed: " << __port << "\t(" << e.what() << ")" << endl;
        conn= NULL;
    }catch( ... ){
        cerr << "Create listen connection failed: " << __port << "\t(" << "Unknown exception" << ")" << endl;
        conn= NULL;
    }
    if( conn ){
        int ret= conn->listen( __port, __backlog );
        if( ret ){
            delete conn;
            return ret;
        }else{
            recursive_mutex::scoped_lock lock( _mutex );
            _connections.push_back( conn );
            return 0;
        }
    }else{
        return -1;
    }
}


Connection* Network::connect( const char* __server_ip, int __port )
{
    Connection* conn= NULL;
    try{
        conn= new Connection;
    }catch( exception& e ){
        cerr << "Create listen connection failed: " << __port << "\t(" << e.what() << ")" << endl;
        conn= NULL;
    }catch( ... ){
        cerr << "Create listen connection failed: " << __port << "\t(" << "Unknown exception" << ")" << endl;
        conn= NULL;
    }
    if( conn ){
        int ret= conn->connect( __server_ip, __port );
        if( ret ){
            delete conn;
            return NULL;
        }else{
            recursive_mutex::scoped_lock lock( _mutex );
            _connections.push_back( conn );
            return conn;
        }
    }else{
        return NULL;
    }
}


void Network::disconnect( Connection* __conn )
{
    recursive_mutex::scoped_lock lock( _mutex );
    ConnectionFindOp op( __conn );
    list<Connection*>::iterator itor= find_if( _connections.begin(), _connections.end(), op );    if( itor!=_connections.end() ){//we found it!        assert( *itor );        delete (*itor);        _connections.erase( itor );    }
}


void Network::accepted( Connection* __conn )
{
    recursive_mutex::scoped_lock lock( _mutex );
    _connections.push_back( __conn );
}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -