我正在尝试从服务器接收消息,但遇到一些问题。我确信我的服务器代码很好,因为它无需多路复用套接字即可工作,但现在当我尝试使用 select() 时,它没有收到任何内容。
while(1){
tmp_fds = read_fds;
if (select(fdmax + 1, &tmp_fds, NULL, NULL, NULL) == -1)
error((char *)"ERROR in select");
if (FD_ISSET (sockfd, &tmp_fds)){
memset(buffer, 0 , BUFLEN);
n = recv (sockfd,buffer,BUFLEN,0);
}
这是我从服务器接收的代码。我究竟做错了什么 ? 用于与服务器通信的套接字已经在read_fds中。 布弗伦是 256。
最佳答案
试试这个方法
while(1)
{
tmp_fds = read_fds;
int ret=select(fdmax + 1, &tmp_fds, NULL, NULL, NULL);
if (ret > 0)
{
if (FD_ISSET (sockfd, &tmp_fds))
{
// there is no need for the memset
memset(buffer, 0 , BUFLEN);
n = recv (sockfd,buffer,BUFLEN,0);
}
}
else
if (ret < 0)
{
error((char *)"ERROR in select");
// here you must check what kind of error you received
// may be you need to close the socket and start over again
// return;
}
}
关于c - 使用 select() 进行套接字编程。 FD_ISSET 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16506032/