#鸿蒙通关秘籍#如何在HarmonyOS NEXT中实现UDP通讯?

HarmonyOS
7天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
hm673ff0383fd94

在HarmonyOS NEXT中,通过@ohos.net.socket模块创建并使用UDP通讯。以下是基本步骤:

  1. 创建UDP Socket实例:

    import socket from '@ohos.net.socket';
    let udpSocket = socket.constructUDPSocketInstance();
    
  2. 绑定本地IP地址和端口:

    let localAddress = { address: "0.0.0.0", port: 9990, family: 1 };
    udpSocket.bind(localAddress);
    
  3. 发送消息:

    let targetAddress = { address: "目标IP", port: 9990, family: 1 };
    udpSocket.send({ data: "要发送的消息", address: targetAddress });
    
  4. 接收消息并处理:

    udpSocket.on("message", (value) => {
       // Convert message from ArrayBuffer to string
       let message = buf2String(value.message);
       console.log("Received message: " + message);
    });
    
    function buf2String(buf) {
       let msgArray = new Uint8Array(buf);
       return new TextDecoder("utf-8").decode(msgArray);
    }
    
分享
微博
QQ
微信
回复
7天前
相关问题