我继承自CAsyncSocket
,实现我自己的类。首先,它开始于:
MyClient::MyClient()//this is the constructor, I will create the socket in this constructor
{
if (!Create(0, SOCK_DGRAM, FD_READ | FD_WRITE))
{
UINT errCode = GetLastError();
printf("Create Client socket failed! Errorcode is %d\n", errCode);
}
}
但它显示Create Client socket failed! Errorcode is 10093
.
我在网上搜索,显示 10093 是因为:
尚未执行成功的 WSAStartup。
应用程序没有调用 WSAStartup 或 WSAStartup 失败。应用程序可能正在访问当前活动任务不拥有的套接字(即,尝试在任务之间共享套接字),或者 WSACleanup 已被调用太多次。
然后我修改我的代码
MyClient::MyClient()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
wVersionRequested = MAKEWORD(2, 2);
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0) {
/* Tell the user that we could not find a usable */
/* Winsock DLL. */
printf("WSAStartup failed with error: %d\n", err);
}
/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we */
/* requested. */
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
printf("Could not find a usable version of Winsock.dll\n");
WSACleanup();
}
else
printf("The Winsock 2.2 dll was found okay\n");
/* The Winsock DLL is acceptable. Proceed to use it. */
/* Add network programming using Winsock here */
/* then call WSACleanup when done using the Winsock dll */
if (!Create(0, SOCK_DGRAM, FD_READ | FD_WRITE))
{
UINT errCode = GetLastError();
printf("Create Client socket failed! Errorcode is %d\n", errCode);
}
WSACleanup();
}
然后运行它,它显示:
我也尝试添加
if (!AfxSocketInit())
{
AfxMessageBox(IDP_SOCKETS_INIT_FAILED);
return FALSE;
}
但它仍然有同样的错误。