dynamic buffer size

D

davis

Hi, I'm writing an app in bluetooth & wi-fi. It is client/server on
both. We have defined our own network protocol that should run over
both mediums. There are packet definitions of variable length.

Inside the packet, one field indicates its length. However, I don't
know ahead of time which packet shall be coming in when I read.

I'm using asynchronous read methods for both. In sockets, I do
Socket.BeginRead( ). This method must be supplied with a byte buffer,
and you must also specify the length to read as one of the parameters.

In the bluetooth, I do the same thing except with serial port profile
using Stream.BeginRead( ).

The problem thus becomes I must specify a byte buffer that is larger
than the packet to ensure I get it all. This causes annoying
post-processing where I must then parse the packet and truncate the
buffer to its real size.

I also don't like this b/c of possible buffer overflow.

My question is simply: is there a better way to do this?
 
S

Samuel R. Neff

call BeginRead with a buffer big enough to hold the header. Then
parse out just the header to get the length. Then call BeginRead
again to read the rest of the packet with an appropriately sized
buffer.

However, it may not save you any time or memory to do that since using
a consistent size would provide for more efficient memory
allocation/deallocation. I'd run a profiler on the code to see how
performance and memory usage are before actually worrying about a
problem.

You could also experiment with keeping the buffers and reusing them,
but that can certainly lead to problems if you're not careful and
again may not be more efficient.

Also, you don't have to worry about memory overruns with BeginRead
calls--.NET will ensure that it only reads up to the length of the
buffer. In fact relying on header information to allocate memory and
then reading that amount of bytes is exactly what can lead to memory
overruns.

HTH,

Sam
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top