VC++MFC使用域名+端口号连接SOCKET服务器
VC++MFC使用域名+端口号连接SOCKET服务器在VC++MFC中使用域名+端口号连接Socket服务器可通过以下步骤实现:
[*]域名解析
[*]使用gethostbyname或getaddrinfo函数将域名转换为IP地址12
hostent* host = gethostbyname("www.example.com");
if(host) {
CString ip = inet_ntoa(*(in_addr*)host->h_addr_list);
}
[*]Socket初始化
[*]调用AfxSocketInit初始化Winsock库10
if(!AfxSocketInit()) {
AfxMessageBox(_T("Winsock初始化失败"));
return FALSE;
}
[*]创建Socket对象
[*]使用CSocket或CAsyncSocket类建立连接68
CSocket clientSocket;
if(!clientSocket.Create()) {
AfxMessageBox(_T("Socket创建失败"));
return;
}
[*]连接服务器
[*]通过Connect方法连接解析后的IP和端口610
if(!clientSocket.Connect(ip, 8080)) {
AfxMessageBox(_T("连接服务器失败"));
return;
}
[*]完整示例代码
#include <afxsock.h>
void ConnectToServer(CString domain, UINT port) {
// 域名解析
hostent* host = gethostbyname(CT2A(domain));
if(!host) {
AfxMessageBox(_T("域名解析失败"));
return;
}
// 创建Socket
CSocket clientSocket;
if(!clientSocket.Create()) {
AfxMessageBox(_T("Socket创建失败"));
return;
}
// 连接服务器
CString ip = inet_ntoa(*(in_addr*)host->h_addr_list);
if(!clientSocket.Connect(ip, port)) {
AfxMessageBox(_T("连接服务器失败"));
return;
}
AfxMessageBox(_T("连接成功"));
}
注意事项:
[*]需包含头文件<afxsock.h>和链接ws2_32.lib库612
[*]建议在InitInstance中调用AfxSocketInit初始化10
[*]对于异步操作可继承CAsyncSocket并重写OnConnect等回调函数8
[*]错误处理应检查WSAGetLastError返回值
页:
[1]