简体   繁体   中英

Using select() to receive from multiple peers using UDP sockets while taking user input from STDIN

I am implementing a program that runs in multiple servers, exchanging some information through UDP socket.

It should also take user commands by listening to STDIN and send data to other servers over UDP when requested by the user.

The pseudocode is:

while(1)
    //reset the timeout value

    while(1)
        int sel = select(fdmax+1, &select_fds, NULL, NULL, &timeout);

        if (sel == -1) {exit(1);} //error
        else if (sel == 0) //timeout
            handle timeout event
            break;

        else
            if stdin
                take user command
            if UDP socket
                recvfrom() messages from other servers, check its IP & port
                to see who sent message within time interval

I am having trouble in else part.

I have written a similar program with TCP sockets, and what it did was iterate through the set of file descriptor with select() and if the file descriptor equals STDIN , then serve the user command, and if it equals the listener, handle a new connection, and else, receive TCP messages.

UDP is connectionless, so I guess there is no need to handle a new connection.

It seems like I don't even need to maintain a number of sockets to communicate with multiple sockets. Is it correct?

If so, do I only need to create and bind one socket for communication, and run through STDIN and that socket, and check for user command and message?

Using pseudocode,

FD_SET(STDIN, &master);
FD_SET(socket_fd, &master);


     ...

        else
            for(int i=0; i<socket_fd; ++i)
                if (FD_ISSET(i, &readfds)
                    if (i == STDIN) {handle user commands}
                    else {recvfrom();}

Do this look reasonable?

Also, if UDP is connectionless and if I want to send messages to my direct neighbors (what it would be connected peers if this was TCP ), is storing their IP address and port and sendto() a reasonable way to do it, or is there any better way?

I am not experienced in network programming, and have never used UDP socket before, so please verify my deign and correct me for anything wrong.

Thank you.

Basically, yes. UDP is connectionless, so you can use a single endpoint to communicate with all your clients/peers. You can store their IP address and the source port of their messages (which recvfrom gives you) which you can use as the destination IP address and port in a call to sendto .

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