简体   繁体   中英

Handling multiple incoming UDP connections with single socket

I'm using C++ and want to know whats the best way to handle multiple incoming UDP connections. When I mean multiple it can be a few hundreds or even thousand. Currently Im using a while loop with recv, the data and the IP address of the connection is stored into an array. So there is a chance a few connections getting lost. So is it possible to do this with a Single socket? If I use multiple threads is there a chance a single connection getting accepted by sockets in multiple threads? Here's what I have so far, Thanks!

    time_t timeout = time(NULL);
    vector<string> ip_list;

    while(time(NULL) <= timeout + 60) {
        if (recv_len = recvfrom(ser_sock, recv_data, recv_size, 0, (struct sockaddr *)&cli_info, &cli_size) == SOCKET_ERROR) {
            printf("[WARNING] recv error occured.\n");
            continue;
        }

        if(strcmp(recv_data, "Save IP") == 0) {
            ip_list.push_back(inet_ntoa(cli_info.sin_addr));
            }
        }
    }

want to know whats the best way to handle multiple incoming UDP connections.

Be careful with your thinking here. There are no connections in UDP. There are simply packets sent by hosts.

Currently Im using a while loop with recv, the data and the IP address of the connection is stored into an array.

Have a look at the select system call. This is designed for waiting on one or more file descriptors (sockets).

http://man7.org/linux/man-pages/man2/select.2.html

So there is a chance a few connections getting lost.

You mean there is a chance of packets being dropped . This is the nature of UDP. Any application you build on UDP must expect that some packets are lost, and that packets will arrive in a different order to which they were sent.

So is it possible to do this with a Single socket?

Yes

If I use multiple threads is there a chance a single connection getting accepted by sockets in multiple threads?

UDP sockets are not "accepted" in the sense that TCP sockets are. I would advise against the use of multiple threads until you understand the domain completely.

You could use select () system call to manage multiple descriptors under some pressure-insensitive circumstance, and epoll () for heavy-load system.

BTW: different from TCP descriptor, there is no acceptance before using it. So you should know exactly the peer or broadcast address.

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