[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
RE: [Libevent-users] Read callback problem
Hi,
> I have a simple network application with simple protocol over
> TCP\IP. The main idea of protocol is size+message model. So at first i'm
> sending size of message (coded in big-endian, first 4 bytes) than the
> whole message.
> I'm using event2 and read data from OnRead callback which i set and
> enabled to bufferevent with next code:
>
> static void OnRead(struct bufferevent *bev, void *user_data)
> {
> int buf_len = evbuffer_get_length(bufferevent_get_input(bev));
> ConnectionContext *ctx = user_data;
> uint8_t size_data[4],*data;
>
> printf("bytes avaliable this call: %d\n",buf_len); // always 18
> bytes
>
> switch (ctx->state)
> {
> case ReadSize:
> if (buf_len < 4)
> break;
> bufferevent_read(bev,size_data,4);
> ctx->size = get_be32(size_data);
> ctx->state = ReadCommand;
> break;
> case ReadCommand:
> if (buf_len<ctx->size)
> break;
> data = new uint8_t[ctx->size];
> bufferevent_read(bev,data,ctx->size);
> /// work with data
> delete[] data;
> break;
> default:
> //error handler
> }
> }
>
> Each time OnRead is called i don't know exactly how much bytes i
> will need to read. So if understand the mechanism of libevent right OnRead
> should be called each time there is at least one byte avaliable to read.
> When i try to send 18 bytes OnRead callback successfully called first time
> and ctx->state is set to ReadCommand, but callback is not calling second
> time, when there is 14 bytes avaliable! What am i doing wrong?
Depending on the setup and such, I've done this and it works quite
well. I would wonder what setup you are doing before I would consider
libevent at fault here. My initial thought is that you have not called
enable on the read callback. I *believe* that libevent will always call the
read callback the first time data is received after connection, but unless
you enable read it won't call the callback again.
The code you posted looks like it should function though, so look
into the setup code and of course the other side which is sending.
KB
***********************************************************************
To unsubscribe, send an e-mail to majordomo@xxxxxxxxxxxxx with
unsubscribe libevent-users in the body.