swoole 服務的建構函式

jackbot發表於2019-09-20

在swoole的建構函式中,主要做的事情就是申請記憶體,然後初始化預設的屬性值,以及設定使用者傳遞的值。

static PHP_METHOD(swoole_server, __construct)
{
    zval *zserv = ZEND_THIS;
    const char *host;
    size_t host_len = 0;
    zend_long sock_type = SW_SOCK_TCP;
    zend_long serv_port = 0;
    zend_long serv_mode = SW_MODE_PROCESS;

    //為server申請空間
    swServer *serv = (swServer *) sw_malloc(sizeof (swServer));
    //server初始化
    swServer_init(serv);
    //獲取引數
   end_parse_parameters(ZEND_NUM_ARGS(), "s|lll", &host, &host_len, &serv_port, &serv_mode, &sock_type)

    //base模式下reacotr和work數量都只有一個。
    if (serv_mode == SW_MODE_BASE)
    {
        serv->reactor_num = 1;
        serv->worker_num = 1;
    }
    serv->factory_mode = serv_mode;
   //增加監聽埠
   swListenPort *port = swServer_add_port(serv, (enum swSocket_type) sock_type, host, serv_port);
    //例項化
    zval connection_iterator_object;
    object_init_ex(&connection_iterator_object, swoole_connection_iterator_ce);
    //修改swServer的connctions屬性為connection_iterator_object
    zend_update_property(swoole_server_ce, zserv, ZEND_STRL("connections"), &connection_iterator_object);
    zval_ptr_dtor(&connection_iterator_object);

    swConnectionIterator *i = (swConnectionIterator *) ecalloc(1, sizeof(swConnectionIterator));
    i->serv = serv;
    //將物件指標儲存在swoole_objects.array裡。
    swoole_set_object(&connection_iterator_object, i);
    //更新物件屬性
    zend_update_property_stringl(swoole_server_ce, zserv, ZEND_STRL("host"), host, host_len);
    zend_update_property_long(swoole_server_ce, zserv, ZEND_STRL("port"), (long) serv->listen_list->port);
    zend_update_property_long(swoole_server_ce, zserv, ZEND_STRL("mode"), serv->factory_mode);
    zend_update_property_long(swoole_server_ce, zserv, ZEND_STRL("type"), sock_type);
    swoole_set_object(zserv, serv);

    zval *ports = sw_malloc_zval();
    array_init(ports);
    server_port_list.zports = ports;

#ifdef HT_ALLOW_COW_VIOLATION    
    HT_ALLOW_COW_VIOLATION(Z_ARRVAL_P(ports));
#endif

    swListenPort *ls;
    LL_FOREACH(serv->listen_list, ls)
    {
        //裡面會例項化swoole_server_port_ce,將埠資訊,swServer賦值給這個物件。
        php_swoole_server_add_port(serv, ls);
    }

    server_port_list.primary_port = (swoole_server_port_property *) serv->listen_list->ptr;

    zend_update_property(swoole_server_ce, zserv, ZEND_STRL("ports"), ports);
}

相關文章