我正在使用 Winsock 中的 TCP 套接字在 C 中编写一个 Minecraft Classic Server,我正在编写执行“心跳”的函数,只是一个 HTTP 请求,它应该向我返回一个 URL - 根本没有标题或 HTML。
它将数据发送到 Minecraft.net(至少它是这么说的),但在那之后它只是在那里呆了几分钟,最终告诉我它没有从 minecraft.net 获得数据,即它显示“HeartBeat: Recieved no data来自 minecraft.net"
到目前为止,我有以下代码(不包括 WSAStartup 等):
void HeartBeat()
{
unsigned int clSock;
struct hostent *host;
struct sockaddr_in server_addr;
char buffer[128] = "";
char request[256] = "GET /"; //(I will not show the rest of the request...)
if((clSock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("HeartBeat: Error creating socket\n");
return;
} else {
printf("HeartBeat: Success in creating socket\n");
}
printf("HeartBeat: Resolving hostname 'www.minecraft.net'... ");
if((host = gethostbyname("www.minecraft.net")) == NULL)
{
printf("failed\n");
return;
} else {
printf("success!\n");
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(80);
server_addr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
if (connect(clSock, (SOCKADDR*) &server_addr, sizeof(server_addr)) == SOCKET_ERROR)
{
printf("HeartBeat: Error conneting to www.minecraft.net\n");
return;
} else {
printf("HeartBeat: Connected to www.minecraft.net\n");
}
if (send(clSock, request, sizeof(request), 0) < 0)
{
printf("HeartBeat: Sending data failed.\n");
closesocket(clSock);
return;
} else {
printf("HeartBeat: Success in sending data.\n");
}
if ((recv(clSock, buffer, sizeof(buffer), 0)) == 0)
{
printf("HeartBeat: Received no data from www.minecraft.net\n");
closesocket(clSock);
return;
} else {
printf("HeartBeat: Yay, success! Url is '%s'", buffer);
closesocket(clSock);
return;
}
}
有人可以指出我哪里出错了吗?太感谢了。