热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

windows下设置socket的connect超时

变相的实现connect的超时,我要讲的就是这个方法,原理上是这样的:1.建立socket2.将该socket

变相的实现connect的超时,我要讲的就是这个方法,原理上是这样的:
1.建立socket
2.将该socket设置为非阻塞模式
3.调用connect()
4.使用select()检查该socket描述符是否可写(注意,是可写)
5.根据select()返回的结果判断connect()结果
6.将socket设置为阻塞模式(如果你的程序不需要用阻塞模式的,这步就省了,不过一般情况下都是用阻塞模式的,这样也容易管理)

 

// widonws: 默认设置socket TCP client connect为阻塞模式
void TcpConnect(char* strIP, UINT nPort)
{
struct sockaddr_in serverAddress;SOCKET hSocket &#61; NULL;hSocket &#61; socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if( hSocket&#61;&#61;INVALID_SOCKET){return;}memset(&serverAddress, 0, sizeof(serverAddress)); serverAddress.sin_family &#61; AF_INET;serverAddress.sin_addr.s_addr &#61; inet_addr(strIP); serverAddress.sin_port &#61; htons((short)nPort); int iTimeOut &#61; 3000;setsockopt(hSocket,SOL_SOCKET,SO_RCVTIMEO,(char*)&iTimeOut,sizeof(iTimeOut));setsockopt(hSocket,SOL_SOCKET,SO_SNDTIMEO,(char*)&iTimeOut,sizeof(iTimeOut)); if( SOCKET_ERROR&#61;&#61;connect(hSocket, (sockaddr*)&serverAddress, sizeof(serverAddress)) ){ closesocket(hSocket);DWORD gle &#61; WSAGetLastError();return;}char buff[] &#61; "hello";int sl&#61;::send(hSocket,(char*)buff, sizeof(buff), 0);if( sl<0 ){closesocket(hSocket);return ;}closesocket(hSocket);
}
// widonws: 设置socket TCP client connect非阻塞模式
void SockSelect(char* strIP, UINT nPort)
{SOCKET
/*int*/ sockfd &#61; socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if(sockfd <0) {return;}struct sockaddr_in serv_addr;//以服务器地址填充结构serv_addrserv_addr.sin_family &#61; AF_INET;serv_addr.sin_addr.s_addr &#61; inet_addr(strIP);serv_addr.sin_port &#61; htons(nPort);int error &#61; -1;int len &#61; sizeof(int);timeval tm;fd_set set;unsigned long ul &#61; 1;ioctlsocket(sockfd, FIONBIO, &ul); //设置为非阻塞模式bool ret &#61; false;if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) &#61;&#61; -1){tm.tv_sec &#61; 3;tm.tv_usec &#61; 0;FD_ZERO(&set);FD_SET(sockfd, &set);if( select(sockfd&#43;1, NULL, &set, NULL, &tm) > 0){getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (char *)&error, /*(socklen_t *)*/&len);if(error &#61;&#61; 0) ret &#61; true;else ret &#61; false;} else ret &#61; false;}else ret &#61; true;ul &#61; 0;ioctlsocket(sockfd, FIONBIO, &ul); //设置为阻塞模式if(!ret) {closesocket( sockfd );fprintf(stderr , "Cannot Connect the server!/n");return;}fprintf( stderr , "Connected!/n");char buff[] &#61; "hello";int sl&#61;::send(sockfd,(char*)buff, sizeof(buff), 0);closesocket( sockfd );
}



推荐阅读
author-avatar
npa3689305
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有