我正在为 TCP/IP 网络客户端通信编写一个类。在类头中,我创建了一个 SOCKET 成员。该类还包含一个调用 WSAStartup 和检查版本的方法。建立连接的方法首先调用 WSAStartup,然后初始化调用 socket() 函数的 SOCKET 成员。请参阅下面的代码。我想知道这是否“正确”,或者是否有更好的方法。
头文件:
/*network.h*/
public class IPnetwork
{
private:
WSADATA wsaData ;
SOCKET hSocket ;
sockaddr_in socketAddress ;
static const int SERVER_PORT = 502 ;
unsigned long int = serverIP ;
public:
IPnetwork(char* serverIPaddress) ;
bool Connect() ;
bool Disconnect() ;
~IPnetwork() ;
private:
bool startWinSock() ;
} ;
源代码:
/*network.cpp*/
IPnetwork::IPnetwork(char* serverIPaddress)
{
serverIP = inet_addr(serverIPaddress) ;
}
bool IPnetwork::Connect()
{
/* start winsock */
if(!startWinSock())
{
return false ; /* winsock problem */
}
/* Create socket */
if ((hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{
return false ; /* could not create socket */
}
/* fill socket address structure */
socketAddress.sin_family = AFINET ;
socketAddress.sin_port = htons(SERVER_PORT) ;
socketAddress.sin_addr.S_un.S_addr = serverIP ;
/* connect */
if(connect(hSocket,reinterpret_cast<sockaddr*>(&socketAddress), sizeof(sockAddr))!=0)
{
return false ; /* could not connect*/
}
return true ;
}
bool IPnetwork::startWinSock()
{
if(WSAStartup(MAKEWORD(REQ_WINSOCK_VER,0),&wsaData)==0)
{
/* Check if major version is at least REQ_WINSOCK_VER */
if (LOBYTE(wsaData.wVersion) < REQ_WINSOCK_VER)
{
return false ; /* winsock started but version is too low */
}
else
{
return true ; /* winsock started with right version*/
}
}
else
{
return false ; /* winsock not started */
}
}