Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7194092
  • 博文数量: 510
  • 博客积分: 12019
  • 博客等级: 上将
  • 技术积分: 6836
  • 用 户 组: 普通用户
  • 注册时间: 2005-08-01 16:46
文章分类

全部博文(510)

文章存档

2022年(2)

2021年(6)

2020年(59)

2019年(4)

2018年(10)

2017年(5)

2016年(2)

2015年(4)

2014年(4)

2013年(16)

2012年(47)

2011年(65)

2010年(46)

2009年(34)

2008年(52)

2007年(52)

2006年(80)

2005年(22)

分类: WINDOWS

2009-08-19 13:05:16

WSADATA wsd;

SOCKET cClient;

int ret;

struct sockaddr_in server;

hostent *host=NULL;



if(WSAStartup(MAKEWORD(2,0),&wsd)){return 0;}

cClient=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

if(cClient==INVALID_SOCKET){return 0;}

//set Recv and Send time out

int TimeOut=6000; //设置发送超时6秒

if(::setsockopt(cClient,SOL_SOCKET,SO_SNDTIMEO,(char *)&TimeOut,sizeof(TimeOut))==SOCKET_ERROR){

return 0;

}

TimeOut=6000;//设置接收超时6秒

if(::setsockopt(cClient,SOL_SOCKET,SO_RCVTIMEO,(char *)&TimeOut,sizeof(TimeOut))==SOCKET_ERROR){

return 0;

}

//设置非阻塞方式连接

unsigned long ul = 1;

ret = ioctlsocket(cClient, FIONBIO, (unsigned long*)&ul);

if(ret==SOCKET_ERROR)return 0;



//连接

server.sin_family = AF_INET;

server.sin_port = htons(25);

server.sin_addr .s_addr = inet_addr((LPCSTR)pSmtp);

if(server.sin_addr.s_addr == INADDR_NONE){return 0;}



connect(cClient,(const struct sockaddr *)&server,sizeof(server));



//select 模型,即设置超时

struct timeval timeout ;

fd_set r;



FD_ZERO(&r);

FD_SET(cClient, &r);

timeout.tv_sec = 15; //连接超时15秒

timeout.tv_usec =0;

ret = select(0, 0, &r, 0, &timeout);

if ( ret <= 0 )

{

::closesocket(cClient);

return 0;

}

//一般非锁定模式套接比较难控制,可以根据实际情况考虑 再设回阻塞模式

unsigned long ul1= 0 ;

ret = ioctlsocket(cClient, FIONBIO, (unsigned long*)&ul1);

if(ret==SOCKET_ERROR){

::closesocket (cClient);

return 0;

}
阅读(4122) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2009-08-19 13:06:43

/ 等待连接,nListenSock是非阻塞的,返回的也为非阻塞的 static int waitConnect( int nListenSock, int nTimeout ) { struct timeval time0, time1; fd_set rdfds; int nSel; FD_ZERO(&rdfds); FD_SET(nListenSock, &rdfds); if( nTimeout > 0 ) { struct timeval tv; tv.tv_sec = 0; tv.tv_usec = nTimeout*1000; gettime(&time0); while( (nSel = select(nListenSock+1,0, &rdfds, 0, &tv)) == -1 && errno == EINTR ) { gettime(&time1); nTimeout -= TIMEDELTA_MS(time1,time0);