Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UDP network stuck while system waiting/receiving data

Tags:

c++

c

sockets

udp

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:

network 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?

like image 776
Shin Chen Hu Avatar asked Sep 27 '22 11:09

Shin Chen Hu


1 Answers

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.

like image 139
Matthew Avatar answered Sep 30 '22 09:09

Matthew