Ejemplo n.º 1
0
static int init_network(lua_State *L, struct event_base *ev_base)
{
    const char *char_name = config_optstring(L, "char_name", NULL);
    if (!char_name)
        ERR_EXIT("config error : not found char name\n");
    if (init_channel(L) == -1)
        ERR_EXIT("init client failed\n");

    const char *srv_addr = config_optstring(L, char_name, NULL);
    if (srv_addr) {
        char ip[MAX_IP_LEN];
        int port;
        if (parse_addr(srv_addr, ip, &port) != 0)
            ERR_EXIT("server addr error\n");
        int fd = start_tcp_listen(ip, port);
        if (fd == -1)
            ERR_EXIT("start server failed : %s\n", strerror(errno));
       struct event *lsn_ev = event_new(ev_base, fd, EV_READ | EV_PERSIST, new_client, ev_base);
        event_add(lsn_ev, NULL);
    }

    const char *remote_svrs = config_optstring(L, "remote_servers", NULL);
    lua_newtable(L);
    lua_pushvalue(L, -1);
    lua_setglobal(L, "remote_servers");
    if (remote_svrs) {
        size_t sz = strlen(remote_svrs);
        char tmp[sz+1];
        strcpy(tmp, remote_svrs);
        char *p = strtok(tmp, ";");
        while (p) {
            const char *rsvr_addr = config_optstring(L, p, NULL);
            if (!rsvr_addr)
                ERR_EXIT("remote server %s addr not found\n", p);
            char ip[MAX_IP_LEN];
            int port;
            if (parse_addr(rsvr_addr, ip, &port) != 0)
                ERR_EXIT("remote server %s addr  error\n", p);
            int fd = connect_tcp_server(ip, port);
            if (fd == -1)
                ERR_EXIT("connect to remote server %s failed : %s\n", p, strerror(errno));
            int id = alloc_server();
            if (id == -1)
                ERR_EXIT("remote server is full\n");
            strcpy(AllChannels[id]._peer_ip, ip);
            lua_pushnumber(L, id);
            lua_setfield(L, -2, p);

            evutil_make_socket_nonblocking(fd);
            AllChannels[id]._bev = bufferevent_socket_new(ev_base, fd, BEV_OPT_CLOSE_ON_FREE);
            bufferevent_setcb(AllChannels[id]._bev, readcb, NULL, errorcb, (void *)(intptr_t)id);
            bufferevent_enable(AllChannels[id]._bev, EV_READ|EV_WRITE);

            p = strtok(NULL, ";");
        }
    }
    lua_pop(L, 1);
    return 0;
}
Ejemplo n.º 2
0
	select_server(SCtx ctx, int p, const std::string& sname = "Network Server") : context(ctx), server(alloc_server(sname, p)), port(p), server_name(sname) { }