Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ socket 256 byte buffer

I am trying to use some socket network programming in C++. I am trying to send the text "Hello World!" to a server using the C++ send() function. At first, I set the buffer to the size of 13 since "Hello World!" altogether is 12 characters (you have to make it one more than the character count). The send function only sends the characters to the server if I send it about 7 times. And when it does finally come to the server it looks like this:

"Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!"

Now here is the funny part. The "Hello World!" sentence sends immediately if I set the buffer size to 256 (char buffer[256];). When it comes to the server like that though, it shows "Hello World!" with a whole bunch of space after the two words. Why is this happening and if possible, how can I fix it? Please let me know.

Thanks

like image 267
QAH Avatar asked Apr 15 '09 00:04

QAH


1 Answers

When you call read (or receive) with your buffer to read from the socket, an integer value is returned that specifies the number of bytes read. You should only take that much from the buffer. The rest is irrelevant:

int count = read(...);
// buffer[0 .. count - 1] contains the appropriate data.
like image 94
mmx Avatar answered Oct 13 '22 21:10

mmx