• window的socket编程设置connect连接超时


    timeval tm;
    fd_set set;
    int error = -1;
    int iReceTimeOut = 2000;
    int len = sizeof(int);

    SOCKET hSocket 

    1.生成socket

    hSocket = socket(AF_INET, SOCK_STREAM, 0);

    2.设置套接字为非阻塞模式

    unsigned long ul = 1;

    ioctlsocket(hSocket , FIONBIO, &ul); //设置为非阻塞模式

    3.开始连接目标地

            if (INVALID_SOCKET != hSocket) 
    	{
    		return false;
    	}
    	hSocket = socket(AF_INET, SOCK_STREAM, 0);
    	if (INVALID_SOCKET == hSocket) 
    	{
    		return false;
    	}
    
    	unsigned long ul = 1;
    	timeval tm;
    	fd_set set;
    	int error = -1;
    	int iReceTimeOut = 2000;
    	int len = sizeof(int);
    
    	SOCKADDR_IN SocketAddr;
    	memset(&SocketAddr,0,sizeof(SOCKADDR_IN));
    	SocketAddr.sin_addr.s_addr = inet_addr(pServerIp);
    	SocketAddr.sin_port = htons(iPort);
    	SocketAddr.sin_family = AF_INET;
    
    
    	ioctlsocket(hSocket, FIONBIO, &ul); //设置为非阻塞模式
    	if (SOCKET_ERROR == connect(hSocket, (SOCKADDR *)&SocketAddr, sizeof(SOCKADDR_IN)))
    	{
    		//连接sock5服务器失败
    		tm.tv_sec  = 2;
    		tm.tv_usec = 0;
    		FD_ZERO(&set);
    		FD_SET(hSocket, &set);
    		if( select(hSocket, NULL, &set, NULL, &tm) <= 0)
    		{
    			closesocket(hSocket);
    			hSocket = INVALID_SOCKET;
    			return false;
    		} 
    		getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char *)&error, /*(socklen_t *)*/&len);
    		if (error != 0)
    		{
    			closesocket(hSocket);
    			hSocket = INVALID_SOCKET;
    			return false;
    		}
    	}
    
    	ul = 0;
    	ioctlsocket(hSocket, FIONBIO, &ul); //设置为阻塞模式
    
    	setsockopt( hSocket, SOL_SOCKET, SO_RCVTIMEO, ( char * )&iReceTimeOut, sizeof( int ) );        
    

      

    4.最后结束后将套接字再次设置为阻塞模式

    ul = 0;
    ioctlsocket(hSocket , FIONBIO, &ul); //设置为阻塞模式

    5.如果想设置接受超时

    setsockopt( hSocket , SOL_SOCKET, SO_RCVTIMEO, ( char * )&iReceTimeOut, sizeof( int ) );

  • 相关阅读:
    绑定方式开始服务&调用服务的方法
    采用服务窃听电话示例
    后台服务运行示例
    Android短信监听器——示例
    利用广播实现ip拨号——示例
    Android图片的合成示例
    IIS 7.5 发布Web 网站步骤
    C# 中 多线程同步退出方案 CancellationTokenSource
    UML 类图常用表示方法.
    Socket Receive 避免 Blocking
  • 原文地址:https://www.cnblogs.com/Sniper-quay/p/13955471.html
Copyright © 2020-2023  润新知