我创建了一个TCP服务器(在PC上运行)和一个客户端(在Android Tablet上运行)。接受连接请求时,服务器一会发生一些奇怪的事情。
我使用了Wireshark,并确认请求已到达我的服务器PC。目的端口为9090。 并还检查了netstat,确认我的应用程序打开了我的端口9090。 我在互联网上搜索了一整天,没有找到任何相关答案。 你有什么建议吗? 预先感谢。
这是我的服务器代码。
int StartServer() {
WSADATA wsaData;
int iResult;
struct addrinfo * result = NULL;
struct addrinfo hints;
int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), & wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory( & hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, & hints, & result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Create a SOCKET for connecting to server
listenSocket = socket(result - > ai_family, result - > ai_socktype, result - > ai_protocol);
if (listenSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
// Setup the TCP listening socket
iResult = bind(listenSocket, result - > ai_addr, (int) result - > ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(listenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
iResult = listen(listenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(listenSocket);
WSACleanup();
return 1;
}
return 0;
}
在主功能中:
//start the server
if ((ret = StartServer()) > 0)
{
cout << "Start server failed!" << endl;
cin >> ret;
return 0;
}
cout << "*************************************" << endl;
cout << "waiting for connection" << endl;
SOCKET clientSocket = INVALID_SOCKET;//create client socket
clientSocket = accept(listenSocket, NULL, NULL);
cout << "connection confirmed!" << endl;
答案 0 :(得分:-1)
我将源代码复制到一个新项目中,并像以前一样进行设置。 当我发布此版本时,它起作用了!
我在几种不同的Wifi上进行了测试,每个都可以正常工作。
但不知道为什么=======