- 论坛徽章:
- 0
|
在socket编程时使用select模型,如何判断对方主机已经关闭?
- // sockselect.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <windows.h>
- #include <stdio.h>
- #include <tchar.h> //for UNICODE
- #include <io.h>
- #define SERVER_PORT 2020
- void ReadSocket(SOCKET s)
- {
- char recvbuff[1024];
- int ret,
- nLeft,
- idx;
- nLeft = 30;
- idx = 0;
- while(nLeft>0)
- {
- ret = recv(s, &recvbuff[idx], nLeft, 0);
- if(ret==SOCKET_ERROR)
- {
- }
- idx += ret;
- nLeft -= ret;
- }
- }
- int main(int argc, char* argv[])
- {
- SOCKET s = INVALID_SOCKET;
- struct sockaddr_in ClientSAddr;
- WSADATA WSStartData;
- fd_set fdread, fdexcept;
- int ret;
- char DefaultIPAddr[] = "127.0.0.1";
- // time inteval to check sockets
- struct timeval tv;
- // create a socket and connect it to server
- WSAStartup(MAKEWORD(1,1), &WSStartData);
-
- // Init Socket
- s = socket(AF_INET,SOCK_STREAM,0);
-
- // Init Address
- memset (&ClientSAddr, sizeof(ClientSAddr),0);
- ClientSAddr.sin_family = AF_INET;
- ClientSAddr.sin_addr.S_un.S_addr = inet_addr(DefaultIPAddr);
- ClientSAddr.sin_port = htons(SERVER_PORT);
-
- // Connect
- connect(s, (struct sockaddr *)&ClientSAddr, sizeof(ClientSAddr));
- //
- tv.tv_sec = 5;
- tv.tv_usec = 0;
- while(TRUE)
- {
- FD_ZERO(&fdread);
- FD_ZERO(&fdexcept);
- FD_SET(s, &fdread);
- FD_SET(s, &fdexcept);
- ret=select(0, &fdread, NULL, &fdexcept, &tv);
- if(ret==SOCKET_ERROR)
- {
- printf("Error!");
- }
- if(ret > 0)
- {
- if(FD_ISSET(s, &fdexcept))
- {
- printf("s in exception, quit...");
- break;
- }
- if(FD_ISSET(s, &fdread))
- {
- //
- printf("There are %d socket(s) ready, we read it from socket...\n", ret);
- ReadSocket(s);
- //printf("FD_SET");
- }
- }
- }
- return 0;
- }
复制代码
像这样一段代码,如果服务器正常发送数据,那么一切都很正常,一旦服务器socket关闭,客户机就会进入假死状态,CPU占用率达100%,如何判断对方关闭这一事件的发生呢?谢谢! |
|