char IP[30] = "127.0.0.1";
char PORT[10] = "1000";
void Connection(HWND hwnd)
{
WORD wVersionRequested;
WSADATA wsaData;
char * ip = "";
PHOSTENT hostinfo;
wVersionRequested = MAKEWORD( 2, 0 );
int ConRes, ConRes2;
char Buffer [20] = "";
if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
{
if((hostinfo = gethostbyname(IP)) != NULL)
{
ip = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list);
}
}
InitWSA();
begin:
Sleep(1000);
RemAdr.sin_family = AF_INET;
RemAdr.sin_addr.s_addr=inet_addr(127.0.0.2);
RemAdr.sin_port = htons (atoi(PORT));
client = socket (AF_INET,SOCK_STREAM,0);
switch(connect (client, (struct sockaddr *)&RemAdr,sizeof(RemAdr)))
{
case 0:
WSAAsyncSelect(client,hwnd,RATMSG_SOCKET,FD_READ|FD_CLOSE|FD_CONNECT);
return;
break;
default:
Sleep(1000);
RemAdr.sin_family = AF_INET;
RemAdr.sin_addr.s_addr=inet_addr(ip);
RemAdr.sin_port = htons (atoi(PORT));
client = socket (AF_INET,SOCK_STREAM,0);
ConRes2=connect (client, (struct sockaddr *)&RemAdr,sizeof(RemAdr));
break;
}
switch(ConRes2)
{
case 0:
WSAAsyncSelect(client,hwnd,RATMSG_SOCKET,FD_READ|FD_CLOSE|FD_CONNECT);
return;
break;
default:
goto begin;
break;
}
return;
}
在尝试连接几个小时但连接失败后,用户的互联网最终将断开连接,直到您关闭应用程序。似乎是什么问题?我认为我的代码有点草率,所以任何有用的提示都会很棒,很想学习。
在这个过程中,我实际上是想设法让它有一个“备份”IP 地址来连接,以防第一个失败。因此,如果无法连接到 127.0.0.1,请尝试 127.0.0.2,然后再以 127.0.0.1 为例。我该如何管理?
PS 你在我的代码中看到的任何看起来像是“坏习惯”的东西,请指出,以便我将来学习/修复它。谢谢。