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?
+8
A:
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);
Adam Pierce
2008-09-27 06:33:07
Thanks, but that only partially answers my question. I guess what I am after is what happens if the stream to be read is larger than the buffer?
Heat Miser
2008-09-27 06:36:33
Heat Miser: You keep reading until read() returns 0.
Chris Jester-Young
2008-09-27 06:37:25
Sorry, that wasn't very well phrased. I meant: you have to do your reads in a loop. Each time through the loop, you process what's in the buffer (even if only to append its content to a string). The loop finishes when read() returns 0.
Chris Jester-Young
2008-09-27 06:38:30
@Chris Jester-Young thanks, it makes sense now.
Heat Miser
2008-09-27 06:49:01
CJY is right, and if you're reading from a stream socket you have to do it in a loop even if the buffer is big enough for the message, because you won't necessarily get all the data in one go. Reading a datagram of known size might be an exception, I don't remember.
Steve Jessop
2008-09-27 12:06:49
A:
Your sockets implementation doesn't require the buffer, to be big enough, to hold the entire message for sure, but it might be convenient depending on, what You are doing.
Maciej Hehl
2008-09-27 07:48:57
+1
A:
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.
unwind
2008-10-15 11:00:52