c++ - UDP server consumes all processor time in multithreaded program -
i'm developing client/server application. client , server run on 2 different machines running ubuntu 16.04. client sends 2 variables influence flow of server part, therefore, want decrease packet loss rate as possible. application thread-based.
in 1 thread udp server running. project has gui implemented using qt. when tried implement udp server blocking, whole program , gui froze until packet received. , when packet received program didn't response.
therefore, thought non-blocking udp best way it. managed make udp non-blocking using select(). comes problem. if set timeout of recvfrom
10ms , thread allowed run every 10ms, no packet lost but, apparently, udp thread consumes processor time program freezes. if increased interval of calling thread or reduced timeout interval, around 80% of packets lost. know udp connectionless protocol , tcp may better option, have use udp
client side sends packets on udp.
the question is: how can reduce packet loss rate without blocking other threads executing efficiently?
following code (the based on stackoverflow answer which, @ moment, can't find refer here).
void receiveudp(void) { fd_set readfds; static int fd; static struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 10000; static char buffer[10]; static int length; if ( (fd = socket(af_inet, sock_dgram, 0)) < 0 ) { perror("socket failed"); return; } struct sockaddr_in serveraddr; memset( &serveraddr, 0, sizeof(serveraddr) ); serveraddr.sin_family = af_inet; serveraddr.sin_port = htons( 50037 ); serveraddr.sin_addr.s_addr = htonl( inaddr_any ); if( bind(fd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) { perror("bind failed"); return; } fcntl(fd, f_setfl, o_nonblock); fd_zero(&readfds); fd_set(fd, &readfds); int rv = select(fd+1, &readfds, null, null, &tv); if(rv == -1) { printf("error in select\n"); _exit(0); } else if(rv == 0) { printf("timeout\n"); } else { if(fd_isset(fd, &readfds)) { length = recvfrom(fd, buffer, sizeof(buffer) - 1, 0, null, 0); if(length < 0) { perror("recvfrom failed"); } else { printf("%d bytes received: \n", length); } } } close(fd); }
Comments
Post a Comment