0

我正在尝试制作一个非常简单的 UDP 服务器,但我似乎无法掌握如何去做。我查看了 Microsoft 文档,但即便如此,我也遇到了这个问题。似乎 recvfrom 函数返回一个错误,调用 WSAGetLastError 告诉我这是一个无效的参数错误,但对我来说,参数似乎是正确的:

int main( int argc, const char* argv[])
{
    char request[MAX_REQUEST_LEN];
    int port;
    SOCKET sock;
    bool quit = false;

    port = 11130;

    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR)
    {
        cout << "WSAstartup failed" << endl;
        return -1;
    }

    // Create a socket.
    sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sock == INVALID_SOCKET) {
        WSACleanup();
        cout << "Error at socket" << endl;
        return -1;
    }

    sockaddr_in server, client;
    int c_len = sizeof(client);

    server.sin_family = AF_INET;
    server.sin_addr.s_addr = htonl(INADDR_ANY);
    server.sin_port = htons(port);

    bind( sock, (sockaddr *)&server, sizeof(server) );

    while(!quit)
    {
        memset(request,'\0', MAX_REQUEST_LEN);
        int result = recvfrom(sock, request, MAX_REQUEST_LEN, 0, (struct sockaddr*) &client, &c_len);
        cout << "Received: " << request << endl << "recvfrom return: " << result << endl;
           //process request

    }

    closesocket(sock);
    WSACleanup();

    return 0;
}

任何帮助,将不胜感激。

4

0 回答 0