HarmonyNext使用SocketIO实现长链

概要

之前的文章讲解了通过官方TCPSocket来实现socket通信,这篇文章我们来看下如何通过使用SocketIO三方库来实现长链。

技术细节

假如服务地址为:https://host:port/app

我们将服务地址拆解为

请求地址:https://host:port

命名空间:app

1、在项目的oh-package.json文件中添加引用

"dependencies": {
    "@ohos/socketio_2.x": "^1.0.3"
}

2、创建SocketIO实例

this.client = new client_socket();
this.client?.set_open_listener(() => {
  this.connected = true;
  Logger.info(TAG, "连接服务器成功");
  this.callback?.onOpen();
});
this.client?.set_fail_listener(() => {
  Logger.info(TAG, "连接服务器失败");
  this.callback?.onFail();
});
this.client?.set_reconnecting_listener(() => {
  Logger.info(TAG, "正在重新连接服务器中");
  this.callback?.onReconnecting();
});
this.client?.set_reconnect_listener(() => {
  Logger.info(TAG, "重新连接服务器");
  this.callback?.onReconnect();
});
this.client?.set_close_listener((reason: string) => {
  this.connected = false;
  Logger.info(TAG, "连接关闭 " + reason);
  this.callback?.onClose(reason);
});
this.client?.set_socket_open_listener((nsp: string) => {
  Logger.info(TAG, "on_socket_open " + nsp);
  this.callback?.onSocketOpen(nsp);
});
this.client?.set_socket_close_listener((nsp: string) => {
  Logger.info(TAG, "on_socket_close " + nsp);
  this.callback?.onSocketClose(nsp);
});

// 设置命名空间
this.client?.set_nsp("/app");
// 设置header参数
this.client?.set_headers(`{token:${BigInt(tokenId)},name:测试}`);

this.client?.set_reconnect_delay(1000)
this.client?.set_reconnect_delay_max(5000)
this.client?.set_reconnect_attempts(3)

3、连接和断连

// 连接
this.client?.connect('https://host:port')

// 断连
this.client?.socket_close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值