HarmonyOS 心跳场景demo

长链接socket demo,心跳场景demo

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

udp心跳参考示例代码

import connection from '@ohos.net.connection'
import { BusinessError } from '@kit.BasicServicesKit';
import socket from '@ohos.net.socket';

const udp_server_ip = '192.168.52.119';
const udp_server_port = 8081;
const udp_server: socket.NetAddress = {
  address: udp_server_ip,
  port: udp_server_port
}

const TAG = 'xxx'

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  udp: socket.UDPSocket = socket.constructUDPSocketInstance();
  heartBeatIntervalId: number = -1;
  hasBindLocalAddress: boolean = false;

  bindUdpLocalAddress(): Promise<boolean> {
    let hasDefaultNet = connection.hasDefaultNetSync();
    let netHandle = connection.getDefaultNetSync();
    let properties = connection.getConnectionPropertiesSync(netHandle);
    let linkAddress = properties.linkAddresses.pop();
    if (!hasDefaultNet || !netHandle || !properties || !linkAddress) {
      this.hasBindLocalAddress = false;
      return Promise.resolve(false);
    }
    return this.udp.bind({ address: linkAddress.address.address }).then(() => {
      this.hasBindLocalAddress = true;
      return Promise.resolve(true);
    }).catch((error: BusinessError) => {
      console.log(TAG, 'upd socket bind error, ' + JSON.stringify(error));
      return Promise.reject(error);
    })
  }

  sendHeartBeat() {
    let sendOptions: socket.UDPSendOptions = {
      address: udp_server,
      data: 'HeartBeat'
    }
    this.udp.send(sendOptions, (err: BusinessError) => {
      if (err) {
        console.log(TAG, 'send Heartbeat fail' + JSON.stringify(err));
        return;
      }
      console.log(TAG, 'send Heartbeat success');
    })
  }

  aboutToAppear(): void {
    this.udp.on('message', (value: socket.SocketMessageInfo) => {
      console.log(TAG, "on message");
      let buffer: ArrayBuffer = value.message;
      let dataView = new DataView(buffer);
      let str = "";
      for (let i = 0; i < dataView.byteLength; ++i) {
        str += String.fromCharCode(dataView.getUint8(i));
      }
      console.log(TAG, "on connect received:" + str);
    });
    this.udp.on('listening', () => {
      console.log(TAG, "on listening");
    });
    this.udp.on('close', () => {
      console.log(TAG, "on close");
    });
    this.udp.on('error', () => {
      console.log(TAG, "on error");
    });
    this.heartBeatIntervalId = setInterval(() => {
      if (this.hasBindLocalAddress) {
        this.sendHeartBeat();
      } else {
        this.bindUdpLocalAddress().then((hasBindLocalAddress) => {
          if (hasBindLocalAddress) {
            this.sendHeartBeat();
          }
        })
      }
    }, 5000);
  }

  aboutToDisappear(): void {
    setTimeout(() => {
      if (!this.udp) {
        return;
      }
      this.udp.close().then(() => {
        console.log(TAG, 'close success');
      }).catch((err: BusinessError) => {
        console.log(TAG, 'close fail');
      });
      this.udp.off('message');
      this.udp.off('listening');
      this.udp.off('close');
      this.udp.off('error');
      clearInterval(this.heartBeatIntervalId)
    }, 10 * 1000);
  }

  build() {
    RelativeContainer() {
      Text(this.message)
        .id('HelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
    }
    .height('100%')
    .width('100%')
  }
}
分享
微博
QQ
微信
回复
4天前
相关问题
HarmonyOS NFC读、写卡场景demo
281浏览 • 1回复 待解决
HarmonyOS 申请使用webview场景demo
620浏览 • 1回复 待解决
HarmonyOS 商城demo
139浏览 • 1回复 待解决
HarmonyOS 曲线demo
119浏览 • 1回复 待解决
HarmonyOS 视频场景如何实现
177浏览 • 1回复 待解决
HarmonyOS 资讯类demo
339浏览 • 1回复 待解决
HarmonyOS viewModal demo问题
475浏览 • 1回复 待解决
HarmonyOS 滑动缩放demo
144浏览 • 1回复 待解决
HarmonyOS 全局弹窗demo
162浏览 • 1回复 待解决
HarmonyOS Ble蓝牙demo
229浏览 • 1回复 待解决
HarmonyOS应用更新demo
407浏览 • 1回复 待解决
HarmonyOS 帧动画demo
365浏览 • 1回复 待解决
HarmonyOS tab切换demo
120浏览 • 1回复 待解决
HarmonyOS Tab导航demo
173浏览 • 1回复 待解决
HarmonyOS 滤镜实现demo
125浏览 • 1回复 待解决
HarmonyOS 引导页demo
307浏览 • 1回复 待解决
HarmonyOS photopicker的demo
169浏览 • 1回复 待解决
HarmonyOS 加解密 demo
749浏览 • 1回复 待解决
HarmonyOS 网络框架demo
148浏览 • 1回复 待解决
HarmonyOS 混淆相关场景咨询
372浏览 • 1回复 待解决
HarmonyOS BackupExtensionAbility场景区分
72浏览 • 1回复 待解决