非阻塞SOCKET套接字connect等待时间的实现
2016-04-07 10:31
387 查看
SOCKET cClient;
cClient=socket(AF_INET,SOCK_STREAM,0);
//设置为非阻塞套接字
int iMode = 1;
ioctlsocket(cClient, FIONBIO, (u_long FAR*)&iMode);
//定义服务端
SOCKADDR_IN saddr;
saddr.sin_addr.S_un.S_addr=inet_addr(CMT->iplist[i]);
saddr.sin_family=AF_INET;
saddr.sin_port=htons(5001);
//超时时间
struct timeval tm;
tm.tv_sec = 3; //3秒
tm.tv_usec = 0;
int ret = -1;
//非阻塞操作
// 尝试去连接服务端
if (!connect(cClient, (SOCKADDR*)&saddr, sizeof(saddr)))
{
ret = 1; // 连接成功
}
else
{
fd_set set;
FD_ZERO(&set);
FD_SET(cClient, &set);
if (select(-1, NULL, &set, NULL, &tm) <= 0)
{
ret = -1; // 有错误(select错误或者超时)
//continue;//循环发送SOCKET时continue
}
else
{
int error = -1;
int optLen = sizeof(int);
getsockopt(cClient, SOL_SOCKET, SO_ERROR, (char*)&error, &optLen);
if (0 != error)
{
ret = -1; // 有错误
//continue;//循环发送SOCKET时continue
}
else
{
ret = 1; // 无错误
}
}
}
// 设回为阻塞socket
//iMode = 0;
//ioctlsocket(cClient, FIONBIO, (u_long FAR*)&iMode); //设置为阻塞模式
if (ret==1)
{
send(cClient,buffer,1024,0);
recv(cClient,buffer,1024,0);
closesocket(cClient);
}
closesocket(cClient);
cClient=socket(AF_INET,SOCK_STREAM,0);
//设置为非阻塞套接字
int iMode = 1;
ioctlsocket(cClient, FIONBIO, (u_long FAR*)&iMode);
//定义服务端
SOCKADDR_IN saddr;
saddr.sin_addr.S_un.S_addr=inet_addr(CMT->iplist[i]);
saddr.sin_family=AF_INET;
saddr.sin_port=htons(5001);
//超时时间
struct timeval tm;
tm.tv_sec = 3; //3秒
tm.tv_usec = 0;
int ret = -1;
//非阻塞操作
// 尝试去连接服务端
if (!connect(cClient, (SOCKADDR*)&saddr, sizeof(saddr)))
{
ret = 1; // 连接成功
}
else
{
fd_set set;
FD_ZERO(&set);
FD_SET(cClient, &set);
if (select(-1, NULL, &set, NULL, &tm) <= 0)
{
ret = -1; // 有错误(select错误或者超时)
//continue;//循环发送SOCKET时continue
}
else
{
int error = -1;
int optLen = sizeof(int);
getsockopt(cClient, SOL_SOCKET, SO_ERROR, (char*)&error, &optLen);
if (0 != error)
{
ret = -1; // 有错误
//continue;//循环发送SOCKET时continue
}
else
{
ret = 1; // 无错误
}
}
}
// 设回为阻塞socket
//iMode = 0;
//ioctlsocket(cClient, FIONBIO, (u_long FAR*)&iMode); //设置为阻塞模式
if (ret==1)
{
send(cClient,buffer,1024,0);
recv(cClient,buffer,1024,0);
closesocket(cClient);
}
closesocket(cClient);
相关文章推荐
- #if defined和#if !defined(c语言的宏定义)
- 2015最流行的Android组件、工具、框架大全
- Android中的Timer和Handler的使用
- 浮点数取模
- C++ 面试问题&资料整理
- minSdkVersion、targetSdkVersion、targetApiLevel的区别
- Office 365 ProPlus 安装及管理
- AutoCAD中ObjectARX C++常用的方法
- 【转】MyEclipse8.5集成Tomcat7时的启动错误:Exception in thread “main” java.lang.NoClassDefFoundError org/apache/commons/logging/LogFactory
- Cts框架解析(12)-ITargetPreparer
- 批量删除以前缀开头的数据表
- MySQL主要的命令(1)
- MSDE 2000
- Zabbix图像集中展示Graphtrees开源
- 建造者模式Builder Pattern
- codeforces_622E. Ants in Leaves(dfs+排序+贪心)
- 内存泄漏与内存溢出
- 分离与继承的思想实现图片上传后的预览功能:ImageUploadView
- 【JQuery UI】什么是JQuery UI
- 01-Memcached介绍