简体   繁体   中英

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?

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.

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.

除了上述答案之外,beej 指南的新链接是: https ://beej.us/guide/bgnet/html/#blocking

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM