This statement is not always true: "As everyone knows the read of a socket is blocking, IE, always waiting for information in the socket."
A socket may or may not be "blocking", it merely depends on setting this property in the stream.
What may be happening, in your case, is the read is blocking, but when receiving new data, it usually returns the value and exits the lock state (this is expected).
Try using something like the following code to evaluate what’s going through your stream, to see if the correct data is coming in, and if what you’re receiving is control data and/or special characters (remember to put some criteria in the code to exit the infinite loop, if there is no way to break the code ;) ).
while ((numread = read(sock_fd, &buff, 1)) > 0) {
write(out_fd, &buff, 1);
}
Here is a function that serves to configure the blocking behavior in both linux and windows:
#import <fcntl.h>
/** Retorna true se funcionou, ou false se houve algum erro
* fd é o file descriptor em que for aplicar o parâmetro
* blocking é true ou false, definindo se o socket vai ser "bloqueante" ou não
*/
bool SetSocketBlockingEnabled(int fd, bool blocking)
{
if (fd < 0) return false;
#ifdef WIN32
unsigned long mode = blocking ? 0 : 1;
return (ioctlsocket(fd, FIONBIO, &mode) == 0) ? true : false;
#else
int flags = fcntl(fd, F_GETFL, 0);
if (flags < 0) return false;
flags = blocking ? (flags&~O_NONBLOCK) : (flags|O_NONBLOCK);
return (fcntl(fd, F_SETFL, flags) == 0) ? true : false;
#endif
}
Original code in this reply by Soen
Well, this close-up shouldn’t even be there either. It would be good for you to start from a code that already works, and adapt to its use gradually. In any case, I edited my reply to try to be more comprehensive.
– Bacco