我正在使用 libevent 处理一组端口上的数据接收。我想要完成的行为是这样的:
-假设我有一组端口,1001-1004 -读取端口上的数据,例如 1001。 -一旦回调被击中,禁用此端口 (1001) 上的进一步读取。- 一旦所有端口都接收到数据,将它们全部重新打开以进行读取。
现在我有一个缓冲区事件结构:
static struct bufferevent *bev[4];
我像在文档中显示的那样设置了侦听器:
/* Listener 1 */
sin.sin_port = htons(MIXPORT + 1);
listener1 = evconnlistener_new_bind(base, accept1, NULL,
LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,
(struct sockaddr*)&sin, sizeof(sin));
if (!listener1) { perror("Couldn't create listener1"); return 1; }
evconnlistener_set_error_cb(listener1, accept_error_cb);
static void accept1(struct evconnlistener *listener,
evutil_socket_t fd, struct sockaddr *address, int socklen,
void *ctx) {
/* A new connection was received on this port */
struct event_base *base = evconnlistener_get_base(listener);
bev[0] = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
/* Callback for when (*bufevent, data READ, data WRITTEN, event OCCURRED, *void) */
bufferevent_setcb(bev[0], read1, NULL, echo_event_cb, NULL);
/* Set bufferevent to be able to read */
bufferevent_enable(bev[0], EV_READ);
}
然后我给了它一个 READ 回调:
static void read1(struct bufferevent *bev, void *ctx) {
if(LOG) { logoutput("Data received on port 1"); }
struct evbuffer *input = bufferevent_get_input(bev);
size_t len = evbuffer_get_length(input);
data[0] = malloc(len);
/* Copy evbuffer data into array */
evbuffer_copyout(input, data[0], len);
/* Remove data from evbuffer after copying it out */
evbuffer_drain(input, len);
handle(0);
}
在我的“处理”功能中,我告诉它这样做:
static void handle(int i)
{
/* Disable reading on port until re-enabled later */
bufferevent_disable(bev[i], EV_READ); // I thought this should do it?!
// Do other stuff...
random_function();
}
最后...
static void random_function(); {
/* Re-enable read on port */
bufferevent_enable(bev[src], EV_READ);
}
任何想法我做错了什么?当我将数据发送到随机端口时,我仍然能够发送更多、更多、更多。
蒂亚!