Hi3861 OpenHarmony嵌入式应用入门--UDP Client

本篇使用的是lwip编写udp客户端。需要提前准备好一个PARAM_HOTSPOT_SSID宏定义的热点,并且密码为PARAM_HOTSPOT_PSK。还需要准备一个udp服务,服务ip为PARAM_SERVER_ADDR宏定义,端口为PARAM_SERVER_PORT宏定义。

修改网络参数

在Hi3861开发板上运行上述四个测试程序之前,需要根据你的无线路由、Linux系统IP修改 net_params.h文件的相关代码:

  • PARAM_HOTSPOT_SSID 修改为你的热点名称
  • PARAM_HOTSPOT_PSK 修改为你的热点密码;
  • PARAM_SERVER_ADDR 修改为你的服务器IP地址;
  • PARAM_SERVER_PORT 修改为你的服务器端口号;

LwIP Socket API编程udp客户端主要步骤

创建Socket socket()

设置目标服务器地址和端口 sockaddr_in

发送和接收数据 sendto() recvfrom()

关闭Socket close()

代码编写

修改D:\DevEcoProjects\test\src\vendor\rtplay\rt_hi3861\demo\BUILD.gn文件

# Copyright (c) 2023 Beijing HuaQing YuanJian Education Technology Co., Ltd
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#    http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License. 

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

lite_component("demo") {
  features = [
    #"base_00_helloworld:base_helloworld_example",
    #"base_01_led:base_led_example",
    #"base_02_loopkey:base_loopkey_example",
    #"base_03_irqkey:base_irqkey_example",
    #"base_04_adc:base_adc_example",
    #"base_05_pwm:base_pwm_example",
    #"base_06_ssd1306:base_ssd1306_example",
    #"kernel_01_task:kernel_task_example",
    #"kernel_02_timer:kernel_timer_example",
    #"kernel_03_event:kernel_event_example",
    #"kernel_04_mutex:kernel_mutex_example",
    #"kernel_05_semaphore_as_mutex:kernel_semaphore_as_mutex_example",
    #"kernel_06_semaphore_for_sync:kernel_semaphore_for_sync_example",
    #"kernel_07_semaphore_for_count:kernel_semaphore_for_count_example",
    #"kernel_08_message_queue:kernel_message_queue_example",
    #"wifi_09_hotspot:wifi_hotspot_example",
    #"wifi_10_sta:wifi_sta_example",
    #"tcp_11_server:tcp_server_example",
    #"tcp_12_client:tcp_client_example",
    #"udp_13_server:udp_server_example",
    "udp_14_client:udp_client_example",
  ]
}

创建D:\DevEcoProjects\test\src\vendor\rtplay\rt_hi3861\demo\udp_14_client文件夹

文件夹中创建D:\DevEcoProjects\test\src\vendor\rtplay\rt_hi3861\demo\udp_14_client\BUILD.gn文件

#Copyright (C) 2021 HiHope Open Source Organization .
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#
#limitations under the License.

static_library("udp_client_example") {
    # uncomment one of following line, to enable one test:
    sources = ["udp_client_example.c"]

    sources += ["wifi_connecter.c"]
    include_dirs = [
        "//utils/native/lite/include",
        "//kernel/liteos_m/kal",
        "//foundation/communication/wifi_lite/interfaces/wifiservice",
    ]
}

文件夹中创建D:\DevEcoProjects\test\src\vendor\rtplay\rt_hi3861\demo\udp_14_client\net_common.h文件,文件主要引入一些头文件。文件同tcp_12_client\net_common.h

文件夹中创建D:\DevEcoProjects\test\src\vendor\rtplay\rt_hi3861\demo\udp_14_client\wifi_connecter.h文件,该头文件包含wifi连接的宏。文件同tcp_12_client\wifi_connecter.h

文件夹中创建D:\DevEcoProjects\test\src\vendor\rtplay\rt_hi3861\demo\udp_14_client\wifi_connecter.c文件,文件同tcp_12_client\wifi_connecter.c

文件夹中创建D:\DevEcoProjects\test\src\vendor\rtplay\rt_hi3861\demo\udp_14_client\udp_client_example.c文件

/*
 * Copyright (C) 2021 HiHope Open Source Organization .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 *
 * limitations under the License.
 */

#include <stdio.h>
// #include <string.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"

#include "net_common.h"
#include "wifi_connecter.h"

static char request[] = "Hello.";
static char response[128] = "";

#define DELAY_TICKS_10     (10)

void UdpClientTest(void)
{
    WifiDeviceConfig config = {0};

    // 准备AP的配置参数
    // strcpy(config.ssid, PARAM_HOTSPOT_SSID);
    // strcpy(config.preSharedKey, PARAM_HOTSPOT_PSK);
    strcpy_s(config.ssid, WIFI_MAX_SSID_LEN, PARAM_HOTSPOT_SSID);
    strcpy_s(config.preSharedKey, WIFI_MAX_KEY_LEN, PARAM_HOTSPOT_PSK);
    config.securityType = PARAM_HOTSPOT_TYPE;

    osDelay(DELAY_TICKS_10);

    int netId = ConnectToHotspot(&config);

    ssize_t retval = 0;
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0); // UDP socket

    struct sockaddr_in toAddr = {0};
    toAddr.sin_family = AF_INET;
    toAddr.sin_port = htons(PARAM_SERVER_PORT); // 端口号,从主机字节序转为网络字节序
    if (inet_pton(AF_INET, PARAM_SERVER_ADDR, &toAddr.sin_addr) <= 0) { // 将主机IP地址从"点分十进制"字符串 转化为 标准格式(32位整数)
        printf("inet_pton failed!\r\n");
        goto do_cleanup;
    }

    // UDP socket 是 "无连接的" ,因此每次发送都必须先指定目标主机和端口,主机可以是多播地址
    retval = sendto(sockfd, request, sizeof(request), 0, (struct sockaddr *)&toAddr, sizeof(toAddr));
    if (retval < 0) {
        printf("sendto failed!\r\n");
        goto do_cleanup;
    }
    printf("send UDP message {%s} %ld done!\r\n", request, retval);

    struct sockaddr_in fromAddr = {0};
    socklen_t fromLen = sizeof(fromAddr);

    // UDP socket 是 "无连接的" ,因此每次接收时前并不知道消息来自何处,通过 fromAddr 参数可以得到发送方的信息(主机、端口号)
    retval = recvfrom(sockfd, &response, sizeof(response), 0, (struct sockaddr *)&fromAddr, &fromLen);
    if (retval <= 0) {
        printf("recvfrom failed or abort, %ld, %d!\r\n", retval, errno);
        goto do_cleanup;
    }
    response[retval] = '\0';
    printf("recv UDP message {%s} %ld done!\r\n", response, retval);
    printf("peer info: ipaddr = %s, port = %hu\r\n", inet_ntoa(fromAddr.sin_addr), ntohs(fromAddr.sin_port));

do_cleanup:
    printf("do_cleanup...\r\n");
    close(sockfd);
    DisconnectWithHotspot(netId);
}

SYS_RUN(UdpClientTest);

使用build,编译成功后,使用upload进行烧录。

相关推荐
Industio_触觉智能9 小时前
如何在开源鸿蒙OpenHarmony开启SELinux模式?RK3566鸿蒙开发板演示
openharmony·selinux·开源鸿蒙·鸿蒙开发板·rk3566开发板
C++忠实粉丝11 小时前
计算机网络socket编程(2)_UDP网络编程实现网络字典
linux·网络·c++·网络协议·计算机网络·udp
添砖java_85711 小时前
UDP数据报套接字编程
网络·网络协议·udp
9527华安11 小时前
FPGA实现PCIE3.0视频采集转10G万兆UDP网络输出,基于XDMA+GTH架构,提供工程源码和技术支持
网络·fpga开发·udp·音视频·xdma·pcie3.0·万兆网
很楠不爱14 小时前
Linux网络——传输层协议
linux·网络·udp
程序猿小D14 小时前
第三百三十一节 Java网络教程 - Java网络UDP多播
java·网络·udp
程序猿小D17 小时前
第三百三十节 Java网络教程 - Java网络UDP服务器
java·开发语言·网络·网络协议·udp·多线程
helloWorldZMY1 天前
传输控制协议(TCP)和用户数据报协议(UDP)
网络协议·tcp/ip·计算机网络·udp
9527华安1 天前
FPGA实现PCIE3.0视频采集转SFP光口千兆UDP网络输出,基于XDMA+GTH架构,提供2套工程源码和技术支持
网络·fpga开发·udp·音视频·xdma·pcie3.0
Ljw...2 天前
(udp)网络编程套接字Linux(整理)
linux·网络·udp·bind·本地环回