我常用的 socket connect 代码,主要是为了记录非阻塞问题

SOCKET connectToS() { int e=0; struct timeval timeout ; fd_set r; SOCKET s=socket(AF_INET,SOCK_STREAM,0); //设置非阻塞方式连接 unsigned long ul1 = 1; e = ioctlsocket(s,FIONBIO,(unsigned long*)&ul1); if(e==SOCKET_ERROR) { fprintf(stderr,"设置[非阻塞]方式错误,请重新启动!/n"); ::closesocket (s); return -1; } struct sockaddr_in addr; memset(&addr,0,sizeof(struct sockaddr_in)); addr.sin_family = AF_INET; addr.sin_port = htons(SERVERPORT); addr.sin_addr.s_addr = inet_addr(SERVERIP); connect(s,(SOCKADDR*)&addr,sizeof(SOCKADDR)); //select 模型,即设置超时 FD_ZERO(&r); FD_SET(s,&r); timeout.tv_sec = 5; //连接超时10秒 timeout.tv_usec =0; e=select(NULL,NULL,&r,NULL,&timeout); if(e<=0) { fprintf(stderr,"连接超时,请检查网络是否可用!/n"); ::closesocket(s); return -1; } unsigned long ul2= 0; e = ioctlsocket(s,FIONBIO,(unsigned long*)&ul2); if(e==SOCKET_ERROR) { fprintf(stderr,"设置[阻塞]方式错误,请重新启动!/n"); ::closesocket (s); return -1; } return s; }

 

 

你可能感兴趣的:(网络技术,C++,socket,struct,null,stream,网络)