ESP8266 SDK 2.0 学习记录4

网络协议栈

ESP8266 SDK 2.0 学习记录4_第1张图片

UDP Client功能分析

PC模拟UDP Server,指定ip和端口号,等待连接

UDP Client向Server发送"I am Client"

Server返回"I am Server"

功能实现

ESP8266 SDK 2.0 学习记录4_第2张图片

#define SERVERADDR "192.168.0.106"
#define SERVERPORT 8000

void ATaskUdpClient(void *pvParameters)
{

    int iVariableExample = 0;
    int fd = -1;
    int NetTimerOut = 5000;
    int ret;
    struct sockaddr_in serverAddr;
    char udpmsg[48];
    STATION_STATUS StaStatus;

    do
    {
        StaStatus = wifi_station_get_connect_status();
        vTaskDelay(100);
    } while (StaStatus != STATION_GOT_IP);

    fd = socket(PF_INET, SOCK_DGRAM, 0);
    if (fd == -1)
    {
        printf("get socket fail!\n");
        vTaskDelete(NULL);
    }

    setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &NetTimerOut, sizeof(int));

    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = inet_addr(SERVERADDR);
    serverAddr.sin_port = htons(SERVERPORT);
    serverAddr.sin_len = sizeof(serverAddr);

    for (;;)
    {
        sendto(fd, "I am udpclient", sizeof("I am udpclient"),
               0, (struct sockaddr *)&serverAddr, (socklen_t)(serverAddr.sin_len));

        do
        {
            ret = recvfrom(fd, udpmsg, 48,
                           0, (struct sockaddr *)&serverAddr, (socklen_t *)(&serverAddr.sin_len));
            if (ret > 0)
            {
                printf("UdpServer:%s\n", udpmsg);
            }
            else
            {
                printf("UdpServer data is no!\n");
                /* code */
            }

        } while (ret == -1);
    }

    vTaskDelete(NULL);
}

void updclient_int(void)
{
    xTaskCreate(ATaskUdpClient, "udpclient", 256, NULL, 4, NULL);
}

 

 

你可能感兴趣的:(ESP8266,SDK,2.0.0)