跳转至

UDP接收

项目编写

  1. applications/genkipi/app 下新建 udp_recv 文件夹
  2. udp_recv 下新建 main.c 文件
  3. udp_recv 下新建 BUILD.gn文件

代码部分

main.c 文件内容

#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"

#include "genki_wifi_sta.h"

#include "lwip/sockets.h"

#define WIFI_SSID "itheima"
#define WIFI_PASSWORD "12345678"
#define HOSTNAME "itcast"


static void udp_task(void) {
    wifi_sta_connect(WIFI_SSID, WIFI_PASSWORD, HOSTNAME);

    // udp create
    int sock_fd;
    int ret;
    sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock_fd < 0) {
        perror("sock_fd create error\r\n");
        return;
    }

    // config receive addr
    struct sockaddr_in recvfrom_addr;
    socklen_t recvfrom_addr_len = sizeof(recvfrom_addr);

    memset((void *) &recvfrom_addr, 0, recvfrom_addr_len);
    recvfrom_addr.sin_family = AF_INET;
    recvfrom_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    recvfrom_addr.sin_port = htons(8080);

    // bind receive addr
    // bind
    ret = bind(sock_fd, (struct sockaddr *) &recvfrom_addr, recvfrom_addr_len);
    if (ret == -1) {
        perror("bind error\r\n");
        return;
    }

    char recv_buf[1024];
    int recv_len;
    while (1) {
        struct sockaddr_in sender_addr;
        int sender_addr_len;

        recv_len = recvfrom(sock_fd, recv_buf, sizeof(recv_buf), 0, (struct sockaddr *) &sender_addr,
                            sender_addr_len);

        if (recv_len <= 0) {
            continue;
        }

        char recv_data[recv_len];
        memcpy(recv_data, recv_buf, recv_len);
        printf("len: %d data: %s\r\n", recv_len, recv_data);
    }
}

static void start(void) {
    osThreadAttr_t attr;

    attr.name = "udp_recv";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024 * 4;
    attr.priority = 25;

    if (osThreadNew((osThreadFunc_t) udp_task, NULL, &attr) == NULL) {
        printf("Create udp recv task Failed!\r\n");
    }
}

APP_FEATURE_INIT(start);

项目Build.gn

udp_recv 目录下 BUILD.gn 内容为

static_library("udp_recv") {
    sources = [
        "main.c"
    ]

    include_dirs = [
        "//utils/native/lite/include",
        "//base/iot_hardware/peripheral/interfaces/kits",
        "//device/itcast/genkipi/interfaces/kits"
    ]
}

外部Build.gn

udp_recv文件夹上一级目录下BUILD.gn内容为

import("//build/lite/config/component/lite_component.gni")

lite_component("app") {
    features = [
        "udp_recv"
    ]
}