struct sockaddr_in TempSadd; TempSadd.sin_family = AF_INET; TempSadd.sin_port = htons(m_ServerPort); TempSadd.sin_addr.s_addr = inet_addr(m_ServerIp.c_str()); if (-1 == ::connect(m_Socket, (sockaddr*)& TempSadd, sizeof(TempSadd))) { MiniConsole::getInstance().Output("從新鏈接服務器 Failed connect(),Error=<%d>\n", WSAGetLastError()); MiLOG::Instance()->OutputError("從新鏈接服務器Failed connect(),Error=<%d>\n", WSAGetLastError()); MiniConsole::getInstance().Output("ServerIp:%s port:%d \n", m_ServerIp.c_str(), m_ServerPort); closesocket(m_Socket); m_bConnectState = false; } else //*********鏈接成功,能夠開始發送、接收************ { m_bConnectState = true; MiniConsole::getInstance().Output("③鏈接成功服務器IP地址:<%s>,端口號<%d>\n", inet_ntoa(Sadd.sin_addr), ntohs(Sadd.sin_port)); MiLOG::Instance()->OutputSuccess("③鏈接成功服務器IP地址:<%s>,端口號<%d>\n", inet_ntoa(Sadd.sin_addr), ntohs(Sadd.sin_port)); }
這裏有個坑服務器
int connect(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen); ret-成功返回0 失敗返回-1
connect函數是把當前套接字從CLOSED狀態轉移到SYN_SENT狀態,若成功則再轉移到ESTABLISHED狀態。若connect失敗則該套接字再也不可用,必須關閉,咱們不能對這樣的套接字再次調用connect函數。當循環調用connect爲給定主機嘗試各個ip地址直到有一個成功時,在每次connect以後,都必須close當前套接字,並從新調用socket;