UDP发送
项目编写¶
- 在
applications/genkipi/app
下新建udp_send
文件夹 - 在
udp_send
下新建main.c
文件 - 在
udp_send
下新建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
wifi_sta_connect(WIFI_SSID, WIFI_PASSWORD, HOSTNAME);
// 创建udp
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 broadcast addr
struct sockaddr_in send_addr;
socklen_t send_addr_len = sizeof(send_addr);
//内存初始化
memset((void *) &send_addr, 0, send_addr_len);
send_addr.sin_family = AF_INET;
//这个位置是否是inet_addr_t
send_addr.sin_addr.s_addr = inet_addr("192.168.31.50");
send_addr.sin_port = htons(8080);
char *msg = "hello world";
while (1) {
ret = sendto(sock_fd, msg, strlen(msg), 0, (struct sockaddr *) &send_addr, send_addr_len);
usleep(1 * 1000 * 1000);
}
}
static void start(void) {
osThreadAttr_t attr;
attr.name = "udp_sender";
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 sender task Failed!\r\n");
}
}
APP_FEATURE_INIT(start);
项目Build.gn¶
udp_send
目录下 BUILD.gn
内容为
static_library("udp_send") {
sources = [
"main.c"
]
include_dirs = [
"//utils/native/lite/include",
"//base/iot_hardware/peripheral/interfaces/kits",
"//device/itcast/genkipi/interfaces/kits"
]
}
外部Build.gn¶
upd_send
文件夹上一级目录下BUILD.gn
内容为
import("//build/lite/config/component/lite_component.gni")
lite_component("app") {
features = [
"udp_send"
]
}