Using C / C++ socket programming, and the "read(socket, buffer, BUFSIZE)" method. What exactly is the "buffer" I know that char and byte are the same thing, but does it matter how many elements the byte array has in it? Does the buffer need to be able to hold the entire message until the null character?
-
Is this null character sent by the sender of Your mesasage?Maciej Hehl– Maciej Hehl2008-09-27 07:49:41 +00:00Commented Sep 27, 2008 at 7:49
-
No, unfortunately I must append it at the end of the expected payloadHeat Miser– Heat Miser2008-10-21 19:31:24 +00:00Commented Oct 21, 2008 at 19:31
-
Do You know the size of the message, or the end marked somehow?Maciej Hehl– Maciej Hehl2008-10-23 16:16:06 +00:00Commented Oct 23, 2008 at 16:16
-
That is a good point, I should know it because it is sent as part of the HTTP headerHeat Miser– Heat Miser2008-10-25 20:03:22 +00:00Commented Oct 25, 2008 at 20:03
3 Answers
BUFSIZE should be equal to the size of your buffer in bytes. read() will stop reading when the buffer is full. Here is an example:
#define MY_BUFFER_SIZE 1024
char mybuffer[MY_BUFFER_SIZE];
int nBytes = read(sck, mybuffer, MY_BUFFER_SIZE);
3 Comments
As always, use sizeof when you have the chance. Using the built-in operator sizeof, you ask the compiler to compute the size of a variable, rather than specify it yourself. This reduces the risk of introducing bugs when the size of the actual variable is different from what you think.
So, instead of doing
#define BUFSIZE 1500
char buffer[BUFSIZE];
int n = read(sock, buffer, BUFSIZE);
you really should use
char buffer[1500];
int n = read(sock, buffer, sizeof buffer);
Notice how you don't need parenthesis around the argument to sizeof, unless the argument is the name of a type.