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?
C uses a buffer to output or input variables. The buffer stores the variable that is supposed to be taken in (input) or sent out (output) of the program. A buffer needs to be cleared before the next input is taken in.
The send() function shall initiate transmission of a message from the specified socket to its peer. The send() function shall send a message only when the socket is connected (including when the peer of a connectionless socket has been set via connect()).
In C, it is most often an array type. By calling it a buffer, there is an implied meaning that the data stored there is temporary in some sense.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With