Skip to content
Advertisement

Socket data length questions

I have a couple of questions related to the following code:

char buffer[256];
memset(buffer,0,256);

read(socket_fd,buffer,255);

The questions:

  1. Why I read 255 not 256 ?
  2. Let’s say I want to send the word: “Cool” from the client to the server. How many bytes should I write “in client” and how many bytes should i read “in the server”?

I’m really confused.

Advertisement

Answer

You already have good answers here, but I think there’s a concept we should explain.

When you send data through streams (that is, something that writes a number of bytes from one end, and those bytes can be read in the same order in the other end), you almost always want to know when to stop reading. This is mandatory if you’ll send more than one thing: when does the first message stop, and the second begin? In the stream, things get mixed up.

So, how do we delimit messages? There are three simple ways (and many other not so simple ones, of course):

1 Fixed-length messages: If you know beforehand that every message is, say, 10-bytes long, then you don’t have a problem. You just read 10 bytes, and the 11th one will be part of another message. This is very simple, but also very rigid.

2 Delimiting characters, or strings: If you are sending human-readable text, you might delimit your messages the same way you delimit strings in your char*: putting a 0 character at the end. That way, when you read a 0, you know the message ended and any remaining data in the stream belongs to another message.

This is okay for ascii text, but when it comes to arbitrary data it’s also somewhat rigid: there’s a character, or a sequence of characters, that your messages can’t contain (or your program will get confused as to where a message ends).

3 Message headers: This is the best approach for arbitrary length, arbitrary content messages. Before sending any actual message data, send a fixed-length header (or use technique nr 2 to mark the end of the header), specifying metadata about your message. For example, it’s length.

Say you want to send the message ‘Cool’, as you said. Well, first send a byte (or a 2-byte short, or a 4-byte integer) containing ‘4’, the length of the message, and receive it on the other end. You know that before any message arrives, you must read 1 byte, store that somewhere and then read the remaining specified bytes.

A simplified example:

struct mheader {
    int length;
}

// (...)

struct mheader in_h;
read(fd, &in_h, sizeof(struct mheader);

if (in_h.length > 0) {
    read(fd, buffer, in_h.length)
}

In actual use, remember that read doesn’t always read the exact amount of bytes you request. Check the return value to find out (which could be negative to indicate errors), and read again if necessary.

Hope this helps. Good luck!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement