OpenHarmony开源社区
直播中

连志安

4年用户 493经验值
擅长:嵌入式技术 控制/MCU
私信 关注
[经验]

DAYU200 网络编程,UDP通信

socket API可以参考这个:https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-socket.md

推荐大家试用 3.2beta版本来做socket通信,版本下载:
http://ci.openharmony.cn/dailys/dailybuilds

image.png

这里提供一个简单的socket通信代码:

import socket from '@ohos.net.socket'
import wifi from '@ohos.wifi';

function resolveIP(ip) {
  if (ip < 0 || ip > 0xFFFFFFFF) {
    throw ("The number is not normal!");
  }
  return (ip >>> 24) + "." + (ip >> 16 & 0xFF) + "." + (ip >> 8 & 0xFF) + "." + (ip & 0xFF);
}

let udp = socket.constructUDPSocketInstance()
let port = 3861

let localAddr = {
  address: resolveIP(wifi.getIpInfo().ipAddress),
  port: port
}

let mixerAddr = {
  //  address: '255.255.255.255', //局域网关播地址
  address: '192.168.255.78', //打蒜器地址
  port: port
}

udp.bind(localAddr, e => {
  if (e) {
    console.log('==bind error')
    return
  }
  console.log('==bind ok')
})

udp.on('listening', () => {
  console.log("==on listening success");
})

udp.on('message', data => { //收到指定端口来的消息
  console.log("==on message!")

  let dataView = new DataView(data.message)

  let str = ""
  for (let i = 0;i < dataView.byteLength; ++i) {
    let c = String.fromCharCode(dataView.getUint8(i))
    if (c !== "n") {
      str += c
    }
  }
  console.log("==message:" + str + "From:" + data.remoteInfo.address)
  mixerAddr.address = data.remoteInfo.address //更新打蒜器的地址

  // 发送数据
  udp.send({ data: 'recv ok!rn',address: mixerAddr});
})


// 连接使用完毕后,主动关闭。取消相关事件的订阅。
setTimeout(() => {
  // 发送数据
  udp.send({ data: 'hello!rn',address: mixerAddr});
}, 5 * 1000);



@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)

        Button('send', { type: ButtonType.Normal, stateEffect: true })
          .onClick(() => {
            this.sendData()
          })
      }
      .width('100%')
    }
    .height('100%')
  }

  async sendData() {
    let order = 'hellorn' //开关指令

    try {

      await udp.send({ data: order,address: mixerAddr})

      console.log(`==Send ${order} >:  + ${mixerAddr.address}`)

    } catch (e){
      console.log('==Error send: ' + e)
    }

  }
}

更多回帖

发帖
×
20
完善资料,
赚取积分