我有一个问题,我使用select
函数来等待在服务器端读取到接收的数据,但它的工作方式像是错误的,就好像我什么都没有收到,超时也已经过去了。
服务器端代码:
int fd = accept(sockfd, addr, addrlen);
if(fd > 0)
{
struct timeval tv;
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
tv.tv_sec = 5;
tv.tv_usec = 0;
// wait when i can read data
int ret_select = select(1, &rfds, (fd_set *) 0, (fd_set *) 0, &tv);
if(ret_select > 0)
{
// data ready to be readed. NEVER HERE!
}
else
{
// nothing. ALWAYS HERE
}
}
客户端:
int ret = connect(s, name, namelen);
if(ret == 0)
{
struct timeval tv;
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(s, &rfds);
tv.tv_sec = 5;
tv.tv_usec = 0;
// wait when we can write
int ret_select = select(1, (fd_set *) 0, &rfds, (fd_set *) 0, &tv);
if(ret_select > 0)
{
int sended = send(s, my_data, size_data, 0);
if(sended > 0)
{
// all ok, data sended!
}
}
}
如果我在服务器端删除对
select
的调用,一切都正常,数据可供读取,因此我猜测 select
在我的代码中运行有误!请问我的代码有什么问题?谢谢!