网上很多人都有udp开发的疑惑,在这里我就将我实现成功的技巧和经验和大家说说,首先上udpUtil 工具类

// UdpUtils.ets
import socket from '@ohos.net.socket';
import { BusinessError } from '@ohos.base';
import { ToastUtils } from './ToastUtils';

interface GeneratedTypeLiteralInterface_1 {
  message: ArrayBuffer;
  remoteInfo: socket.SocketRemoteInfo;
}

export class UdpUtils {
  private static instance: UdpUtils | null = null;
  private udp: socket.UDPSocket;
  private connectionState: 'disconnected' | 'connecting' | 'connected' = 'disconnected';

  private isConnect:boolean = false

  private port = 18570  //px4无人机端口


  private constructor() {
    this.udp = socket.constructUDPSocketInstance();
  }

  public static getInstance(): UdpUtils {
    if (!UdpUtils.instance) {
      UdpUtils.instance = new UdpUtils();
    }
    return UdpUtils.instance;
  }

  public init(receive: (ip:string,buffer: Uint8Array) => void = () => {
  }): void {
    if (this.connectionState !== 'disconnected') {
      console.warn('UDP already initialized');
      return;
    }
    this.connectionState = 'connecting';

    // 设置消息监听器
    this.udp.on('message', (event: GeneratedTypeLiteralInterface_1) => {
      const len = event.remoteInfo.size
      let message = event.message
      const buffer = new Uint8Array(message);
      receive(event.remoteInfo.address,buffer)
    });

    // 设置错误监听器
    this.udp.on('error', (err: BusinessError) => {
      console.error(`UDP error: ${JSON.stringify(err)}`);
      this.connectionState = 'disconnected';
      if (this.udp) {
        this.udp.close();
      }
    });

    // 绑定UDP端口
    this.udp.bind({ address: '0.0.0.0', port: this.port }, (err: BusinessError) => {
      if (err) {
        console.error(`Bind failed: ${JSON.stringify(err)}`);
        this.connectionState = 'disconnected';
      } else {
        console.info('UDP bind success');
        this.connectionState = 'connected';
      }
    });
  }


  // address 目标ip
  public sendMsg(message: Int8Array, address: string, port: number): void {
    if (this.connectionState !== 'connected') {
      console.error('UDP not connected');
      return;
    }
    let msg = new Uint8Array(message as ArrayBufferLike).buffer

    this.udp.send({
      address: { address: address, port: port },
      data: message.buffer //这里只要buffer或者string的
    }, (err: BusinessError) => {
      if (err) {
        console.error(`yqj-----msg ---->Send failed: ${JSON.stringify(err)}`);
        ToastUtils.show(`yqj-----msg ---->Send failed: ${JSON.stringify(err)}`)
      } else {
        console.log("ip:" + address)
        console.log("port:" + port)
        console.error('yqj---Send successful!');
      }
    });
  }

  public close(): void {
    if (this.udp && this.connectionState === 'connected') {
      this.udp.close();
      this.connectionState = 'disconnected';
      console.info('UDP closed');
    }
  }


}

然后看调用

            let str =
            "-3,32,0,,0,0,29,67,0,0,-128,64,0,0,-64,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-80,0,1,1,-17,3";
            let arr = str.split(',').map(item => parseInt(item));


            let buffer = new ArrayBuffer(arr.length);
            let int8Array = new Int8Array(buffer);
            for (let i = 0; i < arr.length; i++) {
              int8Array[i] = arr[i];
            }
            UdpUtils.getInstance().sendMsg(int8Array,'ip',8080)

好了接下来就是看问题了,
1,网络权限,懂的都懂

            {
              "name": "ohos.permission.INTERNET"
            },

2,同一个局域网,懂得都懂

3,接收的问题, 1,有时候一直接收不到,我做的时候得先重启服务器的 udp,然后给端口发送一下消息,这才能接收到,不然死活接收不到,这有可能是无人机PX4导致的
4,buffer问题,不能直接传array ,要array.buffer,不然都会失败,string没有问题
最重要的就是第3点,很多时候我都是有重启,没有先发送,一直收不到消息,发送也要能发出去,这是最主要的,最好先发个string过去

后面一篇是我的大研究,PX4 mavlink 鸿蒙版的开发,对你没看错,mavlink没有node_mavlink,没有arkts ,我来希望大家多多三连支持我的文章

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐