Select 模型

yingpf 2006-07-29 04:48:32
以下是服务端的Select部队,我在客户端发送一个字符串“hellow”,然后客户端退出,为什么在服务器端一直循环显示“hellow”。我不明白为什么执行过一次recv之后,FD_ISSET()还会有效,也就是说为什么hConnected还处于有数据接收的状态(而此时客户端已退出)?
其中,hConnected是一个已连接的SOCKET。

while(1)
{
fd_set fd;
FD_ZERO(&fd);
FD_SET(hConnected, &fd);
nRet = select(0, &fd, NULL, NULL, NULL);
if(FD_ISSET(hConnected, &fd))
{
char buf[30];
int nBytes = recv(hConnected, buf, 30, 0);
buf[nBytes] = '\0';
cout << buf << endl;
}
}
...全文
389 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
yingpf 2006-07-31
  • 打赏
  • 举报
回复
谢谢各位
CW_Wei 2006-07-30
  • 打赏
  • 举报
回复
select() 的返回值:

This function returns the total number of socket handles that are ready and contained in the fd_set structures, zero if the time limit expired, or the SOCKET_ERROR if an error occurred. If the return value is SOCKET_ERROR, WSAGetLastError can be used to retrieve a specific error code.

nuaawenlin 2006-07-29
  • 打赏
  • 举报
回复
nRet = select(0, &fd, NULL, NULL, NULL);
//////////////////////////////////////////////////////


nRet = select(0, &fd, NULL, NULL, NULL);
if(nRet==SOCKET_ERROR)
break;
僵哥 2006-07-29
  • 打赏
  • 举报
回复
当网络异常时recv会返回一个SOCKET_ERROR,但是楼主没有进行错误判断,正确的应当是(当然写法上就自己去设计)
while(1)
{
fd_set fd;
FD_ZERO(&fd);
FD_SET(hConnected, &fd);
nRet = select(0, &fd, NULL, NULL, NULL);
if(FD_ISSET(hConnected, &fd))
{
char buf[30];
int nBytes = recv(hConnected, buf, 30, 0);
if(nBytes==SOCKET_ERROR)
{
if(WSAEWOULDBLOCK==WSAGetLastError())
continue;
/*错误处理*/
closesocket(hConnected);
hConnected=INVALID_SOCKET;
break;
}
buf[nBytes] = '\0';
cout << buf << endl;
}
}

18,356

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 网络编程
c++c语言开发语言 技术论坛(原bbs)
社区管理员
  • 网络编程
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧