首页 > 学院 > 开发设计 > 正文

C语言socket设置超时/setsockopt函数

2019-11-08 01:28:20
字体:
来源:转载
供稿:网友
//=======================在Windows下似乎操作比较简单,直接调用winsock2.h和ws2_32.lib编程#include"stdafx.h"#include"stdio.h"#include "winsock2.h"#PRagmacomment(lib, "ws2_32.lib")  设置接收超时为 nNetTimeout可采用如下方法:int nNetTimeout= 2000ms;if (SOCKET_ERROR ==  setsockopt(serSocket,SOL_SOCKET, SO_RCVTIMEO, (char *)&nNetTimeout,sizeof(int)))           printf("Set Ser_RecTIMEO error !/r/n");  int ret = recvfrom(serSocket, recvData, 255, 0, (sockaddr*)&remoteAddr, &nAddrLen);       if(ret<0)    {         printf("recv timeout! %d/n",ret);//ret = -1         //continue;     }设置接收超时成功后,若超时,返回值为ret =  -1>>>>>>>>>>>>>>>>>>>>>>>>>>>>>linux<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<而Linux下则不太一样,timeout若仍采用int型将没有效果。linux下应将timeout类型改成struct timeval!注意符号:struct timevaltimeout={4,0};//即timeout={4,0};或者timeout.tv_sec=4; timeout.tv_usec=0;//设置接收超时//setsockopt(sockfd,SOL_SOCKET,SO_RCVTIMEO,(char*)&timeout,sizeof(timeout));setsockopt(sockfd,SOL_SOCKET,SO_RCVTIMEO,(char*)&timeout,sizeof(structtimeval));//同样接收超时后接收返回-1if((rec_length=recvfrom(sockfd,recbuf,MAXDATASIZE,0,(structsockaddr *)&peer,&addrlen))== -1){    printf("recvtimeout!/n");}//======================
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表