询问者
如何设置connect超时?

常规讨论
-
代码如下:
// 装入Winsock然后连接服务器 __declspec (dllexport) int LoadWinsockM(HWND hWnd,char *szIP,HWND m_child_wnd) { WSADATA wsd; DWORD dwLen; int nRet,nZero; LPBYTE pBuf; WSAPROTOCOL_INFO Protocol; char szMessage[81]; if (WSAStartup(0x202,&wsd) != 0) { MessageBox(NULL,"hehe","Client Socket Error",MB_OK); return 0; } dwLen = 0; nRet = WSAEnumProtocols(NULL,NULL,&dwLen); if (nRet == SOCKET_ERROR) { if (WSAGetLastError() != WSAENOBUFS) return 0; } pBuf = malloc(dwLen); nRet = SelectProtocols(SETFLAGS,NOTSETFLAGS,(LPWSAPROTOCOL_INFO)pBuf,&dwLen,&Protocol); free(pBuf); m_data[m_index].sClient = WSASocket(AF_INET,SOCK_STREAM,IPPROTO_IP,NULL,0,SOCK_STREAM); if (m_data[m_index].sClient == INVALID_SOCKET) return 1; nZero = 0; setsockopt(m_data[m_index].sClient,SOL_SOCKET,SO_RCVBUF,(char *)&nZero,sizeof(nZero)); m_data[m_index].server.sin_family = AF_INET; m_data[m_index].server.sin_port = htons(m_data[m_index].port); m_data[m_index].server.sin_addr.s_addr = inet_addr(szIP); if (connect(m_data[m_index].sClient,(struct sockaddr *)&m_data[m_index].server,sizeof(m_data[m_index].server)) == SOCKET_ERROR) { int i=GetLastError(); return 0; } GetResolution(); SetGrids(hWnd); memset(szMessage,'\0',sizeof(szMessage)); sprintf(szMessage,"WM_COMP;%d;0;0;0;\0",10); SendCommandM(hWnd,1,szMessage,NULL); UpdateRegionalScreen(hWnd,m_data[m_index].sClient,TRUE,m_child_wnd); return m_data[m_index].sClient; }
其中
if (connect(m_data[m_index].sClient,(struct sockaddr *)&m_data[m_index].server,sizeof(m_data[m_index].server)) == SOCKET_ERROR)
这一句,如果要链接的机子关机了,也就是说是个无效IP,这个地方会一直等下去,直到windows认为连不上了为止,
我要问的就是,能不能在这之前设置一下超时呢?
我想超过5秒就不让他等了,让它运行下面的代码,怎么设置这个时间呢?用什么API?- 已更改类型 Tim Li 2009年6月30日 8:28 没有回复
全部回复
-
-
设置非阻塞
http://www.cnblogs.com/nemolog/archive/2006/03/12/348431.html
麻烦把正确答案设为解答。 -
设置非阻塞
http://www.cnblogs.com/nemolog/archive/2006/03/12/348431.html
麻烦把正确答案设为解答。
这个例子我看了,亲自做了一下,程序崩溃了!!!
就是在connect的时候崩溃的!!