我正在测试c中的Socket Server应用程序,我在使用代码10038的绑定函数上出错。我查了一下,MSDN说这意味着:
尝试对非套接字的操作进行操作。套接字句柄参数未引用有效套接字,或者对于select,fd_set的成员无效。
以下是代码:
//我有正确的包含文件,例如include,但是当我放#include winsock2.h时,stackoverflow显示它很奇怪
int main()
{
WSADATA wsaData;
SOCKET ListeningSocket;
SOCKET NewConnection;
SOCKADDR_IN ServerAddr;
int Port = 5150;
if(WSAStartup(MAKEWORD(2,2),&wsaData) != 0)
{
printf("Server: WSAStartup failed with error %ld\n",WSAGetLastError());
return -1;
}
else
{
printf("Server: The Winsock dll found!\n");
printf("Server: The current status is: %s.\n",wsaData.szSystemStatus);
}
if(LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
{
printf("Server: The dll do not support Winsock version
%u.%u!\n",LOBYTE(wsaData.wVersion),HIBYTE(wsaData.wVersion));
WSACleanup();
return -1;
}
else
{
printf("Server: The dll supports the Winsock version %u.%u!\n",LOBYTE(wsaData.wVersion),HIBYTE(wsaData.wVersion));
printf("Server: The highest version this dll can support: %u.%u\n",LOBYTE(wsaData.wHighVersion),HIBYTE(wsaData.wHighVersion));
}
ListeningSocket == socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(ListeningSocket == INVALID_SOCKET)
{
printf("Server: Error at socket(), error code: %ld\n",WSAGetLastError());
WSACleanup();
return -1;
}
else
printf("Server: socket() is OK!\n");
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(Port);
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(ListeningSocket, (SOCKADDR *)&ServerAddr,sizeof(ServerAddr)) == SOCKET_ERROR)
{
printf("Server: bind() failed! Error code: %ld.\n",WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
return -1;
}
else
printf("Server: bind() is OK!\n");
if(listen(ListeningSocket,5) == SOCKET_ERROR)
{
printf("Server: listen(): Error listening on socket %ld.\n", WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
return -1;
}
else
printf("Server: listen() is OK, I'm waiting for connections...\n");
printf("Server: accept() is ready...\n");
while(1)
{
NewConnection = SOCKET_ERROR;
while(NewConnection == SOCKET_ERROR)
{
NewConnection = accept(ListeningSocket, NULL, NULL);
}
printf("Server: accept() is OK...\n");
printf("Server: Client connected, ready for receiving and sending data...\n");
ListeningSocket = NewConnection;
break;
}
if(closesocket(NewConnection) != 0)
printf("Server: Cannot close \"NewConnection\" socket. Error code: %ld\n",
WSAGetLastError());
else
printf("Server: Closing \"NewConnection\" socket...\n");
if(WSACleanup() != 0)
printf("Server: WSACleanup() failed! Error code: %ld\n", WSAGetLastError());
else
printf("Server: WSACleanup() is OK...\n");
return 0;
}
答案 0 :(得分:0)
我刚刚得到它,我把==代表
ListeningSocket == socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
而不是=
ListeningSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);