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);