コード例 #1
0
ファイル: TcpClient.cpp プロジェクト: jjfsq1985/StudyLab
void* TcpClient::ConnectThread(void *pParam)
{
    TcpClient *pClient = (TcpClient *)pParam;

    struct sockaddr_in sin;
    sin.sin_family = AF_INET;
    inet_pton(AF_INET, pClient->m_cIPAddr, (void*)&sin.sin_addr);
    sin.sin_port = htons(pClient->m_nPort);

    int nCycle = 15;
    while (pClient->m_bConnecting)
    {
        if (nCycle < 15)
        {
            nCycle++;
            Sleep(1000);
            continue;
        }
        Tprintf(L"Connecting\n");
        nCycle = 0;
        struct event_base *base = event_base_new();
        assert(base != NULL);
#if defined (WIN32)
        evthread_use_windows_threads();
#else
        evthread_use_pthreads();
#endif
        evthread_make_base_notifiable(base);
        struct bufferevent *bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
        bufferevent_setcb(bev, read_cb, NULL, event_cb, pClient);
        bufferevent_enable(bev, EV_READ | EV_WRITE | EV_PERSIST);
        //连接
        if (bufferevent_socket_connect(bev, (SOCKADDR*)&sin, sizeof(SOCKADDR)) < 0)
        {
            bufferevent_free(bev);
            return NULL;
        }
        event_base_dispatch(base);

        event_base_free(base);
    }
    return NULL;
}
コード例 #2
0
ファイル: libevent_ssl_test.c プロジェクト: atassumer/SwiftFS
int main ()
{

	SSL_library_init ();
	ERR_load_crypto_strings ();
	SSL_load_error_strings ();
	OpenSSL_add_all_algorithms();

    event_enable_debug_mode ();
    evbase = event_base_new ();
    dnsbase = evdns_base_new (evbase, 1);

    perform_ssl_connection ();

    event_base_dispatch (evbase);
    event_base_free (evbase);

    return 0;
}
コード例 #3
0
ファイル: client.c プロジェクト: heyuanlong/stage
int main(int argc, char** argv)
{
    if( argc < 3 )
    {
        printf("please input 2 parameter\n");
        return -1;
    }


    //两个参数依次是服务器端的IP地址、端口号
    int sockfd = tcp_connect_server(argv[1], atoi(argv[2]));
    if( sockfd == -1)
    {
        perror("tcp_connect error ");
        return -1;
    }

    printf("connect to server successful\n");

    struct event_base* base = event_base_new();


    struct event *ev_sockfd = event_new(base, sockfd,
                                        EV_READ | EV_PERSIST,
                                        socket_read_cb, NULL);
    event_add(ev_sockfd, NULL);



    //监听终端输入事件
    struct event* ev_cmd = event_new(base, STDIN_FILENO,
                                      EV_READ | EV_PERSIST, cmd_msg_cb,
                                      (void*)&sockfd);

    event_add(ev_cmd, NULL);



    event_base_dispatch(base);

    printf("finished \n");
    return 0;
}
コード例 #4
0
int main(int argc, char* argv[]) {
    if (argc != 3) {
        printf("%s config-file node_id\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    Config *conf = parse_conf(argv[1]);
    struct application *app = malloc(sizeof(struct application));
    app->server_id = atoi(argv[2]);
    app->sock = create_socket();
    app->conf = conf;
    LearnerCtx *learner_ctx = make_learner(conf);
    set_app_ctx(learner_ctx, app);
    register_deliver_cb(learner_ctx, deliver);
    event_base_dispatch(learner_ctx->base);
    free_learner(learner_ctx);
    free(conf);
    free(app);
    return (EXIT_SUCCESS);
}
コード例 #5
0
ファイル: clientRedis.c プロジェクト: jaderfabiano/chat
/*Inicia conexao com o Redis e configura as funcoes de callback no libEvent*/
void initRedis( const char * channel, char * id) {
    signal(SIGPIPE, SIG_IGN);
    struct event_base *base = event_base_new();
    strcpy(globalChannel, channel);    
    setMyID(id); 
    redisAsyncContext * redis = redisAsyncConnect("127.0.0.1", 6379);
    if ( redis->err ) {
	   printf("Erro conectando no redis %s\n", redis->errstr);
	   exit(EXIT_FAILURE);
    }
   
    initStdin( channel);

    redisLibeventAttach( redis,base);
    redisAsyncSetConnectCallback(redis, connectCallback);
    redisAsyncSetDisconnectCallback( redis,disconnectCallback);
    event_base_dispatch(base);

}
コード例 #6
0
int JtEventServer::EventLoop()
{
	//默认存在一个定时器
	//////JtEventTimer *Timer = new JtEventTimer();
	//////Timer->OnAddToServer(this);

	pEventPairPipe = new JtEventPairPipe();
	pEventPairPipe->AddToServer(this);
	
	//jtprintf("[%s]event_base_dispatch before\n", __FUNCTION__);

	Started();

	//int res = event_base_loop(base,EVLOOP_NO_EXIT_ON_EMPTY);
	int res = event_base_dispatch(base);
	if(res==0)
	{
		jtprintf("[%s]event_base_dispatch out res %d\n", __FUNCTION__, res);
	}
	else if(res==-1)
	{
		jtprintf("[%s]event_base_dispatch error res %d\n", __FUNCTION__, res);
	}
	else if(res==1)
	{
		jtprintf("[%s]event_base_dispatch no event res %d\n", __FUNCTION__, res);
	}
	else
	{
		jtprintf("[%s]event_base_dispatch res %d\n", __FUNCTION__, res);
	}
	
	/////delete Timer;
	delete pEventPairPipe;
	pEventPairPipe = NULL;
	//必须先移除所有的事件,然后再调用event_base_free
	event_base_free(base);

	base = NULL;
	//

	return 0;
}
コード例 #7
0
static char *getUserInput(KonohaContext *kctx, char *buff, const char *cid, const char *host, int port)
{
	struct event_base *base = event_base_new();
	struct evhttp *httpd = evhttp_new(base);
	if(evhttp_bind_socket(httpd, host, port) < 0) {
		PLATAPI LoggerModule.syslog_i(5/*LOG_NOTICE*/, "{\"Method\": \"DScriptError\", \"CId\": \"%s\", \"Body\": \"couldn't bind socket\"}", cid);
		exit(1);
	}

	UserInput ui = {};
	ui.base = base;
	ui.buff = buff;
	evhttp_set_gencb(httpd, userInput2Buff, (void *)&ui);
	event_base_dispatch(base);
	evhttp_free(httpd);
	event_base_free(base);

	return buff;
}
コード例 #8
0
ファイル: remote_mock.c プロジェクト: atomic77/mosql-storage
val* mock_recover_key(struct remote_mock* rm, key* k) {
	int port = 12345;
	unsigned int h = joat_hash(k->data, k->size);
		
	rec_key_msg_for_key(k, rm->buffer, &rm->buffer_size);
	rm->recv_sock = udp_bind_fd(my_port);
	socket_make_reusable(rm->recv_sock);
	socket_make_non_block(rm->recv_sock);
	if (h % 2 != 0)
		port = 12346;
	rm->send_sock = udp_socket_connect("127.0.0.1", port);
	send(rm->send_sock, rm->buffer, rm->buffer_size, 0);	
	rm->ev_read = event_new(rm->base, rm->recv_sock, EV_READ, handle_rec_key, rm);
	event_add(rm->ev_read, NULL);
	event_base_dispatch(rm->base);
	close(rm->recv_sock);
	close(rm->send_sock);
	return rm->v;
}
コード例 #9
0
ファイル: example-libevent.c プロジェクト: Rudeman/achat
int main (int argc, char **argv) {
    signal(SIGPIPE, SIG_IGN);
    struct event_base *base = event_base_new();

    redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
    if (c->err) {
        /* Let *c leak for now... */
        printf("Error: %s\n", c->errstr);
        return 1;
    }

    redisLibeventAttach(c,base);
    redisAsyncSetConnectCallback(c,connectCallback);
    redisAsyncSetDisconnectCallback(c,disconnectCallback);
    redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1]));
    redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key");
    event_base_dispatch(base);
    return 0;
}
コード例 #10
0
ファイル: tcpserver.cpp プロジェクト: JayfonLin/chessserver
int TCPServerInit(){
	evutil_socket_t listener;
    listener = socket(AF_INET, SOCK_STREAM, 0);
    assert(listener > 0);
    evutil_make_listen_socket_reuseable(listener);

    struct sockaddr_in sin;
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = 0;
    sin.sin_port = htons(LISTEN_PORT);

    if (bind(listener, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
        perror("bind");
        return 1;
    }

    if (listen(listener, LISTEN_BACKLOG) < 0) {
        perror("listen");
        return 1;
    }

    printf("Listening...");

    evutil_make_socket_nonblocking(listener);

    struct event_base *base = event_base_new();
    assert(base != NULL);
    struct event *listen_event;
    listen_event = event_new(base, listener, EV_READ|EV_PERSIST, do_accept, (void*)base);
    event_add(listen_event, NULL);

    pid_t pid;
    pid = fork();
    if (pid == 0){
        CLog::GetInstance()->start();
    	event_base_dispatch(base);
    	Log("The End.");
    	return 0;
	}else{
    	return 0;
	}
}
コード例 #11
0
static void run_responce_test (struct event_base *evbase, struct evdns_base *dns_base, TestID test_id)
{
    OutData *out;
    struct evbuffer *in_buf;
    HttpClient *http;

    LOG_debug (HTTP_TEST, "===================== TEST ID : %d  =======================", test_id);
    out = g_new0 (OutData, 1);
    out->evbase = evbase;
    out->test_id = test_id;
    out->header_sent = FALSE;

    start_srv (out);
    
    //http = http_client_create (app);
    in_buf = evbuffer_new ();

    http = http_client_create (app);
    http_client_set_cb_ctx (http, in_buf);
    http_client_set_on_chunk_cb (http, on_input_data_cb);
    http_client_set_output_length (http, 1);

    http_client_start_request_to_storage_url (http, Method_get, "/index.html", NULL, NULL);
    
    event_base_dispatch (evbase);
    
    http_client_destroy (http);

    LOG_debug (HTTP_TEST, "Resulting buff: %zd", evbuffer_get_length (in_buf));
    evbuffer_free (in_buf);

    g_free (out->first_line);
    g_free (out->header_line);
    evconnlistener_free (out->listener);
    evtimer_del (out->timeout);
    event_free (out->timeout);
    evbuffer_free (out->out_buf);
    evbuffer_free (out->in_file);

    g_free (out);
    LOG_debug (HTTP_TEST, "===================== END TEST ID : %d  =======================", test_id);
}
コード例 #12
0
		void HttpServer::startServer(int port, int nCPU, char *rootDir) {
			struct sockaddr_in listenAddr;
			struct event_base *base;
			struct evconnlistener *listener;

			if (rootDir == nullptr) {
				rootDir_ = Configuration::ROOT_DIR;
			} else {
				rootDir_ = rootDir;
			}
			base = event_base_new();
			if (!base) {
				throw std::runtime_error("Can't create base");
			}
			if (evthread_make_base_notifiable(base) < 0) {
				event_base_free(base);
				throw std::runtime_error("Couldn't make base notifiable!");
			}
			memset(&listenAddr, 0, sizeof(listenAddr));
			listenAddr.sin_family = AF_INET;
			listenAddr.sin_addr.s_addr = htonl(0);
			if (port == 0) {
				port = Configuration::PORT;
			}
			listenAddr.sin_port = htons(port);
			if (nCPU == 0) {
				nCPU = Configuration::nCPU;
			}
			WorkQueue::workqueue_init((workqueue_t *) &workqueue, nCPU);
			listener = evconnlistener_new_bind(base, acceptConnCb, (void *) &workqueue,
											   LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE | LEV_OPT_THREADSAFE, SOMAXCONN,
											   (struct sockaddr *) &listenAddr, sizeof(listenAddr));
			if (listener == NULL) {
				event_base_free(base);
				WorkQueue::workqueue_shutdown(&workqueue);
				throw std::runtime_error("Port is busy");
			}
			evconnlistener_set_error_cb(listener, acceptErrorCb);
			event_base_dispatch(base);
			event_base_free(base);
			WorkQueue::workqueue_shutdown(&workqueue);
		}
コード例 #13
0
ファイル: event_test.c プロジェクト: dong777/libevent_sample
int
main ()
{
    int sockfd;
    struct bufferevent *p_event;
    struct sockaddr_in addr;

    ff = fopen("/tmp/log", "w");
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);

    if (inet_pton(AF_INET, SVRADDR, &addr.sin_addr) <= 0) {
        printf("inet_pton");
        exit(1);
    }

    if ((p_base = event_base_new()) == NULL) {
        printf("event_base_new ");
        return 1;
    }

    /* we do not need invoke socket function to create socket */
    if ((p_event = bufferevent_socket_new(p_base, -1, BEV_OPT_CLOSE_ON_FREE)) == NULL) {
        printf("bufferevent_socket_new ");
        return 1;
    }

    /* client actually connecte to server at this time. */
    if ((sockfd = bufferevent_socket_connect(p_event, (struct sockaddr *) &addr,
                                             sizeof(addr))) < 0) {
        printf("bufferevent_socket_connect ");
        return 1;
    }

    /* */
    bufferevent_setcb(p_event, buff_input_cb, NULL, buff_ev_cb, p_base);
    bufferevent_enable (p_event, EV_READ);
    event_base_dispatch(p_base);

    return 0;
}
コード例 #14
0
ファイル: ev1.c プロジェクト: ChampionL/socket
int main(){
	int fd1 = tcp_listen(1314);
	int fd2 = tcp_listen(1315);
	int len1,len2;
	int fd11 = accept(fd1,NULL,&len1);
	int fd21 = accept(fd2,NULL,&len2);
	int flag = fcntl(fd11,F_GETFL,0);
	fcntl(fd11,F_SETFL,flag|O_NONBLOCK);//需要将其设置为非阻塞形式
	flag = fcntl(fd21,F_GETFL,0);
	fcntl(fd21,F_SETFL,flag|O_NONBLOCK);
	struct event_base * base = event_base_new();//创建event_base,在创建event时候需要使用。
	struct event * ev1,*ev2;
	struct timeval tv={5,0};
	ev1 = event_new(base,fd11,EV_READ|EV_PERSIST,cb_func_read,NULL);//使用event_new创建事件
	ev2 = event_new(base,fd21,EV_READ|EV_PERSIST,cb_func_read,NULL);//都是对读感兴趣,一次active之后,事件将不处于pending状态,需要重新使其处于pending状态,使用能够EV_PERSIST
	
	event_add(ev1,NULL);//添加event
	event_add(ev2,NULL);

	event_base_dispatch(base);//开启事件循环
	/*event_base_loop,event_base_loop开始监听事件循环伪代码如下所示,按照事件的优先级来处理,每个事件都拥有一个优先级,优先级数目可以在开始时候设置。
    while (any events are registered with the loop,
        or EVLOOP_NO_EXIT_ON_EMPTY was set) {

    if (EVLOOP_NONBLOCK was set, or any events are already active)
        If any registered events have triggered, mark them active.
    else
        Wait until at least one event has triggered, and mark it active.

    for (p = 0; p < n_priorities; ++p) {
       if (any event with priority of p is active) {
          Run all active events with priority of p.
          break; //Do not run any events of a less important priority 
       }
    }

    if (EVLOOP_ONCE was set or EVLOOP_NONBLOCK was set)
       break;
    }
    */
	return 0;
}
コード例 #15
0
ファイル: janssonrpc_io.c プロジェクト: AndreiPlesa/kamailio
int jsonrpc_io_child_process(int cmd_pipe)
{
	global_ev_base = event_base_new();
	global_evdns_base = evdns_base_new(global_ev_base, 1);

	set_non_blocking(cmd_pipe);
	struct event* pipe_ev = event_new(global_ev_base, cmd_pipe, EV_READ | EV_PERSIST, cmd_pipe_cb, NULL);
	if(!pipe_ev) {
		ERR("Failed to create pipe event\n");
		return -1;
	}

	if(event_add(pipe_ev, NULL)<0) {
		ERR("Failed to start pipe event\n");
		return -1;
	}

	connect_servers(global_server_group);

#if 0
	/* attach shutdown signal handler */
	/* The shutdown handler are intended to clean up the remaining memory
	 * in the IO process. However, catching the signals causes unpreditable
	 * behavior in the Kamailio shutdown process, so this should be disabled
	 * except when doing memory debugging. */
	struct sigaction sa;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	sa.sa_handler = io_shutdown;
	if(sigaction(SIGTERM, &sa, NULL) == -1) {
		ERR("Failed to attach IO shutdown handler to SIGTERM\n");
	} else if(sigaction(SIGINT, NULL, &sa) == -1) {
		ERR("Failed to attach IO shutdown handler to SIGINT\n");
	}
#endif

	if(event_base_dispatch(global_ev_base)<0) {
		ERR("IO couldn't start event loop\n");
		return -1;
	}
	return 0;
}
コード例 #16
0
ファイル: server2.cpp プロジェクト: wenwenyyw/learn-cpp
void
run(void)
{
    evutil_socket_t listener;
    struct sockaddr_in sin;
    struct event_base *base;
    struct event *listener_event;

    base = event_base_new();
    if (!base)
        return; /*XXXerr*/

    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = 0;
    sin.sin_port = htons(40713);

    listener = socket(AF_INET, SOCK_STREAM, 0);
    evutil_make_socket_nonblocking(listener);

#ifndef WIN32
    {
        int one = 1;
        setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
    }
#endif

    if (bind(listener, (struct sockaddr*)&sin, sizeof(sin)) < 0) {
        perror("bind");
        return;
    }

    if (listen(listener, 16)<0) {
        perror("listen");
        return;
    }

    listener_event = event_new(base, listener, EV_READ|EV_PERSIST, do_accept, (void*)base);
    /*XXX check it */
    event_add(listener_event, NULL);

    event_base_dispatch(base);
}
コード例 #17
0
int
main(int argc, char **argv)
{
        struct event_base *base;
        struct evconnlistener *listener;
        struct sockaddr_in sin;

        int port = 8787;

        if (argc > 1) {
                port = atoi(argv[1]);
        }
        if (port<=0 || port>65535) {
                puts("Invalid port");
                return 1;
        }

        base = event_base_new();
        if (!base) {
                puts("Couldn't open event base");
                return 1;
        }

        /* Clear the sockaddr before using it, in case there are extra
         * platform-specific fields that can mess us up. */
        memset(&sin, 0, sizeof(sin));
        sin.sin_family = AF_INET;
        sin.sin_addr.s_addr = htonl(0);
        sin.sin_port = htons(port);

        listener = evconnlistener_new_bind(base, accept_conn_cb, NULL,
            LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,
            (struct sockaddr*)&sin, sizeof(sin));
        if (!listener) {
                perror("Couldn't create listener");
                return 1;
        }
        evconnlistener_set_error_cb(listener, accept_error_cb);

        event_base_dispatch(base);
        return 0;
}
コード例 #18
0
ファイル: conn.c プロジェクト: 0xffea/shim
int
main(int argc, char **argv)
{
	struct evdns_base *dns;
	struct event_base *base;
	struct bufferevent *bev;
	struct url *socks, *host;
	int s4;

	base = event_base_new();
	if (base == NULL) {
		log_fatal("event_base_new failed.");
		exit(1);
	}

	dns = evdns_base_new(base, 1);
	if (dns == NULL) {
		log_fatal("evdns_base_new failed.");
		exit(1);
	}
	
	log_set_file(NULL);
	log_set_min_level(LOG_DEBUG);
	if (argc >= 3) {
		socks = url_tokenize(argv[2]);
		s4 = !evutil_ascii_strcasecmp("socks4", socks->scheme);
		if (conn_set_socks_server(socks->host, socks->port, s4?
				SOCKS_4 : SOCKS_4a) < 0)
			return 0;
	}
	
	host = url_connect_tokenize(argv[1]);

	bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);

	conn_connect_bufferevent(bev, dns, AF_INET, host->host, host->port,
				 do_connect, NULL);

	event_base_dispatch(base);

	return 0;
}
コード例 #19
0
ファイル: baseserver.cpp プロジェクト: yzqcode/WebServer
void BaseServer::run(const char *address, unsigned short port)
{
    assert(address!=NULL);
    event_base* base = event_base_new();
    memset(&m_sin,0,sizeof(m_sin));
    m_sin.sin_family = AF_INET;
    m_sin.sin_port   = htons(port);
    inet_aton(address,&m_sin.sin_addr);

    m_listener = evconnlistener_new_bind(base,listener_callback,(void*)base,LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,10,(sockaddr*)&m_sin,sizeof(m_sin));

    assert(m_listener!=NULL);

    event_base_dispatch(base);

    evconnlistener_free(m_listener);
    event_base_free(base);


}
コード例 #20
0
static ZEND_RESULT_CODE php_http_client_curl_event_exec(void *context)
{
	php_http_client_curl_event_context_t *ctx = context;
	php_http_client_curl_t *curl = ctx->client->ctx;

#if DBG_EVENTS
	fprintf(stderr, "E");
#endif

	/* kickstart */
	php_http_client_curl_event_handler(ctx, CURL_SOCKET_TIMEOUT, 0);

	do {
		if (0 > event_base_dispatch(ctx->evbase)) {
			return FAILURE;
		}
	} while (curl->unfinished && !EG(exception));

	return SUCCESS;
}
コード例 #21
0
ファイル: test_redis.cpp プロジェクト: vbillys/test_redis
int main (int argc, char **argv) {
  if (argc < 2) {
    printf("error need channel to be specified\n");
    return 1;
  }
  signal(SIGPIPE, SIG_IGN);
  struct event_base *base = event_base_new();

  redisAsyncContext *c = redisAsyncConnect("pub-redis-13387.us-east-1-4.6.ec2.redislabs.com", 13387);
  redisContext *cs = redisConnect("pub-redis-13387.us-east-1-4.6.ec2.redislabs.com", 13387);
  if (c->err) {
    printf("error: %s\n", c->errstr);
    return 1;
  }

  redisLibeventAttach(c, base);
  redisAsyncCommand(c, onMessage, cs, "SUBSCRIBE %s",argv[1]);
  event_base_dispatch(base);
  return 0;
}
コード例 #22
0
ファイル: attach.c プロジェクト: kghost/sandbox
void attach_namespace (int client, struct arguments arguments) {
	w(evutil_make_socket_closeonexec(client));
	w(evutil_make_socket_nonblocking(client));

	struct event_config *ev_config = p(event_config_new());
	w(event_config_require_features(ev_config, EV_FEATURE_FDS));
	struct event_base *ev_base = p(event_base_new_with_config(ev_config));
	event_config_free(ev_config);

	struct event *ev_client = p(event_new(ev_base, client, EV_READ|EV_PERSIST, client_func, NULL));

	struct arg arg = { .event = ev_client, .command = arguments.command };

	w(event_assign(ev_client, ev_base, client, EV_READ|EV_PERSIST, client_func, &arg));
	event_add(ev_client, NULL);

	w(event_base_dispatch(ev_base));

	event_base_free(ev_base);
}
コード例 #23
0
ファイル: AsyncRedis.hpp プロジェクト: hua345/MutexIM
void func(const std::string& commandStr)
{
	g_SubscribeMutex.lock();
	struct event_base *m_base = event_base_new();

	redisAsyncContext *m_redis = redisAsyncConnect("127.0.0.1", 6379);
	if (m_redis->err) {
		/* Let *c leak for now... */
		printf("Error: %s\n", m_redis->errstr);
	}
	redisAsyncCommand(m_redis,authCallback, (char*) "auth", "auth %s", "014006");

	redisLibeventAttach(m_redis, m_base);
	redisAsyncSetConnectCallback(m_redis, connectCallback);
	redisAsyncSetDisconnectCallback(m_redis, disconnectCallback);

	redisAsyncCommand(m_redis, subscribeCallback, (char*) "sub", commandStr.c_str());
	g_SubscribeMutex.unlock();
	event_base_dispatch(m_base);
}
コード例 #24
0
ファイル: server.cpp プロジェクト: yuanlinhu/net_test
int main(int argc, char** argv)
{
	int listener = tcp_server_init(12345, 5);
	if(listener == -1)
	{
		printf("tcp_server_init error");
		return -1;
	}
	
	event_base* base = event_base_new();
	
	event* ev_listen = event_new(base, listener, EV_READ | EV_PERSIST,
								accept_cb, base);
								
	event_add(ev_listen, NULL);
	
	event_base_dispatch(base);
	
	return 0;
}
コード例 #25
0
void *httpserver_dispatch(void *arg) {
#ifndef MULTI_THREAD_SUPPORT
	struct event_base *base = (struct event_base *)arg;
	struct event *signal_event;
	signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)base);

	if (!signal_event || event_add(signal_event, NULL)<0) {
		fprintf(stderr, "Could not create/add a signal event!\n");
		return NULL;
	}
#endif
	event_base_dispatch((struct event_base *) arg);

#ifndef MULTI_THREAD_SUPPORT
	//evconnlistener_free(lmg_listener);
	event_free(signal_event);
#endif
	event_base_free((struct event_base *) arg);
	return NULL;
}
コード例 #26
0
ファイル: tcp_server.c プロジェクト: iamwljiang/libevent_test
int main(int argc,char **argv)
{
	struct event_base * base = event_base_new();
	struct sockaddr_in addr ;
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = htonl(0);
	addr.sin_port = htons(3333);
	set_timer(base);
	struct evconnlistener * lev ;
	lev = evconnlistener_new_bind(base,accept_conn_cb,NULL,
		LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,
		-1,(struct sockaddr*)&addr,sizeof(addr));

	evconnlistener_set_error_cb(lev,listener_error_cb);

	event_base_dispatch(base);
	evconnlistener_free(lev);
	event_base_free(base);
	return 0;
}
コード例 #27
0
int tcp_start_up(){

	WSADATA WSAData;

	struct event_base *base;
    struct evconnlistener *listener;
    struct sockaddr_in sin;

    int port = 22222;
	WSAStartup(0x101, &WSAData);
      
    base = event_base_new();
    if (!base) {
            puts("Couldn't open event base");
            return 1;
    }

    /* Clear the sockaddr before using it, in case there are extra
        * platform-specific fields that can mess us up. */
    memset(&sin, 0, sizeof(sin));
    /* This is an INET address */
    sin.sin_family = AF_INET;
    /* Listen on 0.0.0.0 */
    sin.sin_addr.s_addr = htonl(0);
    /* Listen on the given port. */
    sin.sin_port = htons(port);

    listener = evconnlistener_new_bind(base, accept_conn_cb, NULL,
        LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,
        (struct sockaddr*)&sin, sizeof(sin));
    if (!listener) {
            perror("Couldn't create listener");
            return 1;
    }

    evconnlistener_set_error_cb(listener, accept_error_cb);
	printf("ready to dispatch...\n");
    event_base_dispatch(base);
	
    return 0;
}
コード例 #28
0
ファイル: regress_dns.c プロジェクト: chris-davis/libevent
static void
dns_inflight_test(void *arg)
{
	struct basic_test_data *data = arg;
	struct event_base *base = data->base;
	struct evdns_base *dns = NULL;
	ev_uint16_t portnum = 53900;/*XXXX let the code pick a port*/

	struct generic_dns_callback_result r[20];
	int i;

	tt_assert(regress_dnsserver(base, &portnum, reissue_table));

	/* Make sure that having another (very bad!) RNG doesn't mess us
	 * up. */
	evdns_set_random_bytes_fn(dumb_bytes_fn);

	dns = evdns_base_new(base, 0);
	tt_assert(!evdns_base_nameserver_ip_add(dns, "127.0.0.1:53900"));
	tt_assert(! evdns_base_set_option(dns, "max-inflight:", "3", DNS_OPTIONS_ALL));
	tt_assert(! evdns_base_set_option(dns, "randomize-case:", "0", DNS_OPTIONS_ALL));

	for(i=0;i<20;++i)
		evdns_base_resolve_ipv4(dns, "foof.example.com", 0, generic_dns_callback, &r[i]);

	n_replies_left = 20;
	exit_base = base;

	event_base_dispatch(base);

	for (i=0;i<20;++i) {
		tt_int_op(r[i].type, ==, DNS_IPv4_A);
		tt_int_op(r[i].count, ==, 1);
		tt_int_op(((ev_uint32_t*)r[i].addrs)[0], ==, htonl(0xf00ff00f));
	}

end:
	if (dns)
		evdns_base_free(dns, 0);
	regress_clean_dnsserver();
}
コード例 #29
0
ファイル: master.cpp プロジェクト: jiangeZh/slighttpd
bool Master::StartMaster(int argc, char *argv[])
{
	if (0 != conf_para.InitPara(argc, argv))
		return false;

	std::cout << "Start Master" << std::endl;

	if (!m_worker.Init(this))
	{
		std::cerr<< "Master: Worker::Init()" << std::endl;
		return false;
	}

	nums_of_child = conf_para.MaxWorker;

	//创建一定数量的worker
	while (nums_of_child > 0)
	{
		switch (fork())
		{
			case -1:
				std::cerr<< "Master: StartMaster(): fork()" << std::endl;
				return false;
			case 0:
				m_worker.Run();
				return true;
			default:
				--nums_of_child;
				break;
		}
	}

	m_base = event_base_new();
	m_exit_event = evsignal_new(m_base, SIGINT, Master::MasterExitSignal, m_base);
	m_chld_event = evsignal_new(m_base, SIGCHLD, Master::MasterChldSignal, this);
	evsignal_add(m_exit_event, NULL);
	evsignal_add(m_chld_event, NULL);
	event_base_dispatch(m_base);

	return true;
}
コード例 #30
0
ファイル: time-test.c プロジェクト: 00datman/ompi
int
main(int argc, char **argv)
{
	struct event timeout;
	struct timeval tv;
	struct event_base *base;
	int flags;

#ifdef WIN32
	WORD wVersionRequested;
	WSADATA wsaData;

	wVersionRequested = MAKEWORD(2, 2);

	(void)WSAStartup(wVersionRequested, &wsaData);
#endif

	if (argc == 2 && !strcmp(argv[1], "-p")) {
		event_is_persistent = 1;
		flags = EV_PERSIST;
	} else {
		event_is_persistent = 0;
		flags = 0;
	}

	/* Initalize the event library */
	base = event_base_new();

	/* Initalize one event */
	event_assign(&timeout, base, -1, flags, timeout_cb, (void*) &timeout);

	evutil_timerclear(&tv);
	tv.tv_sec = 2;
	event_add(&timeout, &tv);

	evutil_gettimeofday(&lasttime, NULL);

	event_base_dispatch(base);

	return (0);
}