LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Receiving all data from socket (https://www.linuxquestions.org/questions/programming-9/receiving-all-data-from-socket-154947/)

Ohmu 03-08-2004 08:07 AM

Receiving all data from socket
 
Hi!

I tried to receive all data from socket like:
1) Receive the first portion of data
2) Set socket non-blocking
3) Receive data until it gives error 11 (no more data)

But that gives strange characters in the result...
Is there some better(100% working) way to receive all data?

Thank's,
Ohmu

jtshaw 03-08-2004 08:27 AM

are you sure those strange characters aren't actually being recieved?

Ohmu 03-08-2004 08:37 AM

nope... I am 100% sure of that...

deiussum 03-08-2004 10:41 AM

What language are you using?

And are you checking how many bytes you receive with each block of data you receive, and making sure to use ONLY that number of bytes? For instance in c, you could end up doing something like this:

Code:

char buffer[256];

recv(sock, buffer, 256, 0);

printf("%s\n", buffer);



And if you actually only recv 5 bytes the first 5 bytes will be what you received and the last of them would be garbage and probably displayed if the data wasn't sent as a null-terminated string. (e.g. if the sending app sent "hello" instead of "hello\0" your buffer would end up having so mething like "hellowhatevergarbagewasherebeforethereceiveetc...").

Instead, you would do something like so:

Code:

char buffer[256];
int n;

n = recv(sock, buffer, 256, 0);

// NULL terminate the string
buffer[n] = '\0';

printf("%s\n", buffer);

Obviously, if you are receiving binary data, you probably wouldn't be null terminating it like that, but you should still be checking how many bytes are received and only operating on that number of bytes.

Ohmu 03-08-2004 10:49 AM

well.. I fill the array of chars with \0 and then recv data.. but the strange characters aren't at the end only.. they are in the middle too

deiussum 03-08-2004 01:45 PM

Hmmm... showing us a little bit of your code might be useful.

Ohmu 03-08-2004 01:58 PM

OK.. got it working.. ty all for help


All times are GMT -5. The time now is 12:05 PM.