I have to build up a bilateral UDP network system, that means both server and client send and receive data, as illustrated by the below diagram:
I took a ready to use example from http://www.binarytides.com/udp-socket-programming-in-winsock/
However, on the client, when a data(string) is sent, the client gets stuck waiting for incoming data on this line:
recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)
The client cannot send more data until it receives incoming data.
Is there any method that I can keep sending data to the server, while also waiting for incoming data?
This is because by default sockets are blocking, which means recv
and read
family calls will hang until there is data available. You need to either use nonblocking I/O with multiplexing like select()
or poll()
, or use a separate, dedicated thread for receiving data.
Nonblocking I/O is significantly different in design from blocking I/O code, so there's not a simple change you can make. I recommend you read something like Beej's Guide to Network Programming which covers all of these issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With