1

我正在用 C 实现一个套接字编程项目。我正在使用

选择()

等待来自客户端的数据。我有两个 UDP 套接字,选择调用总是忽略我的一个套接字。谁能简要描述我应该从哪里开始寻找它?这就是我的服务器正在做的事情

waitThreshold.tv_sec = 5000; 
waitThreshold.tv_usec = 50; 
if(sd > sd1)    
    max_sd = (sd + 1);
else if(sd1 > sd)   
    max_sd = (sd1 + 1);
FD_ZERO(&read_sds); 
FD_SET(sd, &read_sds); 
FD_SET(sd1, &read_sds);


ret = select(max_sd, &read_sds, NULL, NULL, &waitThreshold); 
if(ret <0)
{
    printf("\nSelect thrown an exception\n");   
    return 0;
} 
else if(FD_ISSET(sd, &read_sds)) 
{
    // code for socket one
} 
else if(FD_ISSET(sd1, &read_sds)) 
{
    // code for socket two
}
4

2 回答 2

2

你写了else if,所以只有其中一个会运行。

于 2013-03-23T22:09:11.313 回答
0

Generally speaking, when pooling multiple sockets using select() you want to use a for loop instead of branching the code with IFs. Also take note of the fact that select CHANGES the fd_set arguments (the read, write and error file descriptor sets - 2nd, 3rd and 4th arguments) and that you need to re-set them before each select(). A pretty general code layout for selecting sockets that have data to read with multiple concurrent connections would be something like this:

FD_ZERO(&master_sds);
FD_ZERO(&read_sds);

for (i=0; i<number_of_sockets); i++){
    FD_SET(sd[i], &master_sds);
    if sd[i] > max_sd {
        max_sd=sd[i];
    }
}

for(;;){
    read_sds=master_sds;
    ret = select(max_sd, &read_sds, NULL, NULL, &waitThreshold);
    if(ret<0){
        printf("\nSelect thrown an exception\n");
        return 0;
    }
    for(i=0; i<max_sd; i++){
        if FD_ISSET(sd[i], &read_fds){
            // code for socket i
        }
    }   
}

You might not want to have an endless loop to pool the sockets for data, you can insert some condition like receiving specific data on one of the sockets or specific user input as an exit condition. Hope this helps.

于 2013-04-21T14:51:41.367 回答