UDP客户端无法向服务器发送消息,但可以接收

时间:2018-10-16 20:50:15

标签: c++ udp client

我正在尝试创建UDP客户端。当我尝试向服务器发送消息时,收到一条WSAEOPNOTSUPP错误消息。但是随后的recvfrom调用似乎工作正常。我还没有机会在服务器上进行测试,因此我假设数据实际上会按预期返回。根据说明错误的文档

  

已指定MSG_OOB,但是套接字不是流类型的,例如type   SOCK_STREAM,通信域中不支持OOB数据   与此插座相关联,或者插座是单向的   仅支持接收操作。

以下是代码(为保护您而进行了消毒)

WORD version = MAKEWORD(2, 2);
WSADATA data;
int error = 0;

if ((error = WSAStartup(version, &data)) != NO_ERROR)
{
    kzLogError(KZ_LOG_CATEGORY_GENERIC, ("Error: WSAStartup failed with error: {}", error));
    return;
}

if (LOBYTE(data.wVersion) != 2 || HIBYTE(data.wVersion) != 2)
{
    kzLogError(KZ_LOG_CATEGORY_GENERIC, ("Error: System could not support WinSock 2.2."));

    if (WSACleanup() == SOCKET_ERROR)
    {
        kzLogError(KZ_LOG_CATEGORY_GENERIC, ("Error: Winsock cleanup error: {}", WSAGetLastError()));
    }
    return;
}

SOCKET s = INVALID_SOCKET;

if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET)
{
    kzLogError(KZ_LOG_CATEGORY_GENERIC, ("Error: Socket creation failed with error: {}", WSAGetLastError()));

    if (WSACleanup() == SOCKET_ERROR)
    {
        kzLogError(KZ_LOG_CATEGORY_GENERIC, ("Error: Winsock cleanup error: {}", WSAGetLastError()));
    }
    return;
}

int bytesRecv = 0;
ReceiveData receiveData;
struct sockaddr_in server_addr;
int server_addr_len = sizeof(server_addr);

memset((char *)&server_addr, 0, server_addr_len);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(2010);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

memset((char *)&receiveData, 0, sizeof(ReceiveData));

if (sendto(s, “hello”, strlen(“hello”), 0, (struct sockaddr *) &server_addr, server_addr_len) == SOCKET_ERROR)
{
    kzLogError(KZ_LOG_CATEGORY_GENERIC, ("Error: unable to send hello to server: {}", WSAGetLastError()));
}

while (bytesRecv != SOCKET_ERROR)
{
    bytesRecv = recvfrom(s, (char*)&receiveData, sizeof(ReceiveData), 0, (struct sockaddr *) &server_addr, &server_addr_len);
    if (bytesRecv > 0)
    {
        // parse the data
    }
    else
    {
        if (bytesRecv == SOCKET_ERROR)
        {
            kzLogError(KZ_LOG_CATEGORY_GENERIC, ("Error: Reading data: {}", WSAGetLastError()));
        }
    }
}

if (closesocket(s) == SOCKET_ERROR)
{
    kzLogError(KZ_LOG_CATEGORY_GENERIC, ("Error: Unable to close socket: {}", WSAGetLastError()));
}

if (WSACleanup() == SOCKET_ERROR)
{
    kzLogError(KZ_LOG_CATEGORY_GENERIC, ("Error: Winsock cleanup error: {}", WSAGetLastError()));
}

0 个答案:

没有答案