0

我想通过 UDP 从远程设备接收数据,并且我正在使用来自 On-Time RTOS 的 RTIP-32 库

这是我的非阻塞 UDP 套接字的初始化代码

SOCKET UDPCreateSendSocket(DWORD ToIP, WORD Server_port_no)
{
    SOCKET s;
    struct sockaddr_in sin;
    int Result;
    struct timeval select_to;

    // allocate a socket
    s = socket(AF_INET, SOCK_DGRAM, 0);
    if (s == INVALID_SOCKET)
        LogFile.updatelog("failed to allocate socket");

    // connect to the server
    sin.sin_family = AF_INET;
    memcpy(&sin.sin_addr, &ToIP, sizeof(ToIP));
    sin.sin_port = htons(Server_port_no);

    //Enables non-blocking mode
    DWORD iMode = 1;
    Result = ioctlsocket(s, FIONBIO, &iMode);
    if (Result == SOCKET_ERROR)
        LogFile.updatelog("Enable non blocking Failed");

    //Connect
    Result = connect(s, (const struct sockaddr*)&sin, sizeof(sin));
    if (Result == SOCKET_ERROR)
        LogFile.updatelog("connect failed");
  
    fd_set fd_write;
    fd_set fd_read;

    // setup socket list for select()
    FD_ZERO(&fd_write);
    FD_ZERO(&fd_read);

    FD_SET(s, &fd_write);
    FD_SET(s, &fd_read);

    select_to.tv_sec = 1;
    select_to.tv_usec = 0;

    // wait for connect() to complete
    Result = select(1, &fd_read, &fd_write, NULL, &select_to);
    if (Result != 1)
    {
        printf("Timeout waiting for server\n");
        closesocket(s);
        exit(1);
    }

    return s;
}

这是调用recive的函数

int UDPReceive(SOCKET s, void * Data, int MaxLen)
{

    int l = recv(s, (char*)Data, MaxLen, MSG_PEEK);
    if (l == SOCKET_ERROR)
    {
        int error_no = xn_getlasterror();
        xn_geterror_string(error_no);
    }

    if (l == SOCKET_ERROR)
    {
        //Error("recv failed");
        return 0;
    }
    else
        return l;
}

我收到的错误代码112如下所述

进展 (112)

套接字是非阻塞的,但连接会阻塞。在非阻塞套接字上完成了连接操作。这实际上不是一个错误。使用 select 等待连接建立。

我在这里没有做什么

问候希德

4

0 回答 0