Is it possible to use libevent for create multiple tcp connections to different servers in one thread? Could you write a sample implementation of such a task?
I have done so, but not sure that it's right:
...
int num_of_connect = 5; /*for example*/
struct event_base *evbase;
struct bufferevent *bev[num_of_connect];
struct sockaddr_in sin[num_of_connect];
evbase = event_base_new();
for(int i=0;i<=(num_of_connect-1);i++){
sin[i].sin_family = AF_INET;
sin[i].sin_addr.s_addr = inet_addr(/*some addr*/);
sin[i].sin_port = htons(/*some port*/);
bev[i] = bufferevent_socket_new(evbase, -1, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev[i], cb_evread, cb_evwrite, cb_event, NULL);
bufferevent_socket_connect(bev[i], (struct sockaddr *)&sin[i], sizeof(struct sockaddr_in开发者_开发知识库));
}
event_base_dispatch(evbase);
...
In addition, similar can be implemented using the boost::asio? Example?)
In addition, similar can be implemented using the boost::asio? Example?)
Yes, it is entirely possible. This is the basis of the proactor design pattern promoted by Boost.Asio. It achieves concurrency without the use of explicit threads by avoiding blocking operations such as connect
, accept
, read
, and write
. You might find some of my previous answers useful here
- Proactor and async_write
- Clarification about asynchronous and synchronous operations
As Tony pointed out in his answer, the Boost.Asio has fantastic examples explaining the asynchronous concepts in detail. The tutorial, specifically the asynchronous daytime server, is also a good place to start.
You could use boost::asio to run in a thread which accepts the connection asynchronously. There is examples on the boost::asio documentation page which will show you how to setup a server which accepts multiple connections on a single thread.
I'm not familiar with libevent to help you there.
Is it possible to use libevent for create multiple tcp connections to different servers in one thread? Could you write a sample implementation of such a task?
Yes, its possible.
You could also create a server that listened on multiple ports with evconnlistener_new_bind
.
And if you wanted to handle one or more signals, then you could use evsignal_new
to add signals to the event base.
In each case (bufferevent_socket_new
, evconnlistener_new_bind
and evsignal_new
, the callbacks for each event would be likely different.
精彩评论