Вопрос

is it a good or a bad idea to use dynamic buffer sizes in socket communication?

for example: i have a message format [2 bytes: length of the following message][message]

So the buffer size will be message.length+2. On the receiver side I can catch the first two bytes and then I know how many more i will have to to catch.

Is this a good or a bad idea - and WHY?

Это было полезно?

Решение 2

It's just unnecessary. There are read() methods where you define the offset into the buffer and the maximum read length, and there are plenty of other places where you can use a byte[] array, an offset, and a length in the API as well. You don't need to be allocating buffers of exactly the right size.

Другие советы

First, its always better to come up with the data structures, that will be used for communication over sockets. Where u define the place holders for message type, size of the message and the actual message.

Before Writing these kind of structures, please keep following in mind:

  1. Size utilization.

  2. Is cross platform supported, to avoid endianess problems.

  3. Is this extendable.

Its not bad or good but its matter of choice whether to use the way you are using for separating out messages in socket-programming, Or use a delimiter Or use a fixed sized message. At times its use case dependent.

Here you can read more

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top