HarmonyNext使用SocketIO实现长链 原创

zhouchy
发布于 2025-3-8 22:03
浏览
0收藏


文章目录

概要

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

技术细节

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

我们将服务地址拆解为

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

命名空间:app


1、在项目的oh-package.json文件中添加引用,这里我们使用2.0版本

"dependencies": {
    "@ohos/socketio_2.x": "^1.0.3"
}
  • 1.
  • 2.
  • 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)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.

3、连接和断连

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

// 断连
this.client?.socket_close();
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
收藏
回复
举报
回复
    相关推荐