Harmony UDP

示例代码:

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

import wifi from '@ohos.wifiManager';


import {resolveIP} from '../common/utils/Utils'


let localAddress = resolveIP(wifi.getIpInfo().ipAddress);
let localPort = 8081;

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

  @State address:string = '192.168.100.101'  // 连接的IP地址
  @State port:number = 8083  // 连接的端口号



  @State sendValue:string = ''  // 输入框中要发送的值
  @State saveValue:string = 'Hi'   // 存储UDPServer发送的信息
  private UDPSocket:socket.UDPSocket = null;



  async closeUDP():Promise<void>{
    await this.UDPSocket.close();
    this.UDPSocket.off('message');
    this.UDPSocket = null;
  }

  async createUDP(){

    this.UDPSocket = socket.constructUDPSocketInstance()
    this.UDPSocket.bind({
      address:localAddress,
      port:localPort,
      family:1
    });
  }
  async sendData(data:string,address:string,port:number):Promise<void>
  {
    let option={
      address:{
        address:address,
        port:port,
        family:1
      },
      data:data
    }

    this.UDPSocket.send(option)
  }


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

        Row(){
          Text('发送信息')
          TextInput({placeholder:'想要发送的内容'}).width('80%')
          .onChange((value:string)=>{
            this.sendValue = value;
          })
        }.width('80%')
        Button('发送').width('50%').margin({top:10,bottom:50})
        .onClick((event)=>{
          if(this.sendValue!='')
          {
            this.sendData(this.sendValue,this.address,this.port)
          }
        })

        Row(){
          Text('接收信息')
          Text(){
            Span(this.saveValue).fontColor(Color.Green).fontSize(30)
          }
        }.width('80%')


      }
      .width('100%').height('100%')
    }
    .height('100%')
  }

  aboutToAppear()
  {
    this.createUDP()
    this.UDPSocket.on('message',(data)=>{
      hilog.info(0x0000,'TestTag',JSON.stringify(data))
      let buffer = data.message
      let dataview = new DataView(buffer)
      let str= ""
      for(let i = 0; i<dataview.byteLength; ++i)
      {
        str+= String.fromCharCode(dataview.getUint8(i))
      }
      this.saveValue = str
    })
  }


  aboutToDisappear(){
    this.closeUDP()
  }

}

Utils.ets

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

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值