18,356
社区成员
发帖
与我相关
我的任务
分享
WSADATA wsaData;
SOCKADDR_IN server_addr;
WORD wVersion;
wVersion = MAKEWORD(2,2);
/*初始化socket资源*/
WSAStartup(wVersion, &wsaData);
//获取长度
int len = WideCharToMultiByte(CP_ACP, 0, ip_p, ip_p.GetLength(), NULL, 0, NULL, NULL);
char * cip = new char[len + 1];
memset(cip, 0x00, len + 1);
//宽字节转多字节
WideCharToMultiByte(CP_ACP, 0, ip_p, ip_p.GetLength(), cip, len, NULL, NULL);
//cip[len+1] = '\0';
//server_addr.sin_addr.s_addr = inet_addr(tmpData);
server_addr.sin_addr.s_addr = inet_addr(cip);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(_ttoi(port_p));
if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{
//create socket error
check = false;
}
unsigned long ul = 1;
int ret;
ret = ioctlsocket(sock, FIONBIO,(unsigned long *)&ul);//设置成非阻塞模式。
if (connect(sock, (struct sockaddr *) &server_addr, sizeof(SOCKADDR_IN)) == SOCKET_ERROR)
{
//connect error
check = false;
}
else
{
//连接成功
check = true;
m_bActive = true;
m_connectype = TCPIP;
}
delete []cip;
//连接超时设置
struct timeval tmout ;
fd_set r;
FD_ZERO(&r);
FD_SET(m_Socket, &r);
tmout.tv_sec = 15; //连接超时时间
tmout.tv_usec =0;
ret = select(sock, 0, &r, 0, &tmout);
if ( ret <= 0 )
{
return FALSE;
}