Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

non blocking socket in c++

I am writing client in c++ which client get response on two different ports. I am listening to one port in main thread while I have created other thread (posix based) like this:

void *receiveFunc(void *ptr)
{
    try {
        while ( true ) {
            svr_sock << svr_data;
            cout<<svr_data<<endl;
        }
    } catch ( SocketException& ) {}
}

but when it enters into the this thread it never comes out until I have received something on the socket.

How can I overcome this problem?

like image 516
Aqeel Raza Avatar asked Apr 14 '26 22:04

Aqeel Raza


2 Answers

Your socket is in blocking mode.

It depends on your used OS how to set the socket to non-blocking mode.

Linux: You need to set the socket to nonblocking mode like described in Beej's guide.

Windows: You must use the winsock WinAPI functions.

like image 144
Quonux Avatar answered Apr 17 '26 13:04

Quonux


Why do you need it to 'come out'?

Anyway, the usual way of persuading such a blocked thread to exit is to set some 'terminate' bool for the while loop to check and then close the socket. This causes the socket read to return early with an error.

like image 34
Martin James Avatar answered Apr 17 '26 13:04

Martin James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!