试图用winsock打开一个套接字。我从visual studio得到一个错误,指出我在ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
我的整个代码就在那里:
ListenSocket = INVALID_SOCKET;
ClientSocket = INVALID_SOCKET;
WORD wVersionRequested;
WSADATA wsaData;
int wsaerr;
wVersionRequested = MAKEWORD(2, 2);
wsaerr = WSAStartup(wVersionRequested, &wsaData);
if (wsaerr != 0)
{
printf("Server: The Winsock dll not found!\n");
WSACleanup();
return 0;
}
else
{
printf("Server: The Winsock2 dll found \n");
}
/* SOCKET is simply a UINT, created because
on Unix sockets are file descriptors(UINT) but not in windows
so new type SOCKET was created */
cout << AF_INET << endl ;
cout << SOCK_STREAM << endl ;
cout << IPPROTO_TCP << endl ;
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(ListenSocket == INVALID_SOCKET)
{
cerr << "Server: Error initializing socket!n" << endl;
WSACleanup();
return 0;
}
/* The SOCKADDR_IN structure is used by
Win Sockets to specify an endpoint address
to which the socket connects */
sockaddr_in service,client ;
service.sin_family = AF_INET;
service.sin_port = htons(port);
service.sin_addr.s_addr = INADDR_ANY;
/* bind just links the socket
with the sockaddr_in struct we initialized */
if(bind(ListenSocket,(SOCKADDR*)&service,sizeof(service))==SOCKET_ERROR)
{
printf("Server: Error binding socket to port \n");
WSACleanup();
return 0;
}
/* wait for incoming connections */
if(listen(ListenSocket,10)==SOCKET_ERROR)
printf("listen(): Error listening on socket %d\n", WSAGetLastError());
else
{
printf("Server: Waiting for connections...\n");
}
/* accept connections */
printf("Server: Waiting for a client to connect...\n");
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
wprintf(L"accept failed with error: %ld\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
} else {
wprintf(L"Client connected.\n");
acceptConns();
}
很想得到一些帮助,因为我无法弄清楚它为什么不起作用。
提前致谢
编辑:我使用以下代码在一个线程中创建该服务器。这似乎是我首先得到错误
的原因DWORD WINAPI myThread(LPVOID lpParameter)
{
tcp_server* server = (tcp_server*)lpParameter ;
server->start_listening(); // The above function
return 0 ;
}
.....
HANDLE myHandle = CreateThread(0, 0, myThread, server, 0,NULL);
答案 0 :(得分:1)
我在
上有读访问权限违规ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
该行没有明显的读访问权。
但是,由于您显示的代码(出于诊断目的而不完整)位于类方法tcp_server::start_listening()
中,并且ListenSocket
可能是该类的成员,并且您正在调用{{ 1}}通过传递给线程的start_listening()
对象指针,可以理解
唯一可能发生的读取是在分配给tcp_server
成员时访问隐式this
指针。
在线程调用ListenSocket
时(或者至少在调用tcp_server
时,被指向的start_listening()
对象最有可能在内存中无效,因为你事先初步确定socket()
。如果确实如此,则分配给ListenSocket
将是未定义的行为, CAN 会导致访问冲突错误(如果有的话,会导致其他类型的错误)。
但是,在调用ListenSocket
之前,您没有显示如何创建server
对象,或者在CreateThread()
退出后您对该对象执行了操作,因此这个推理只是一个(除非你展示一个更完整的代码示例,否则我会猜测。