中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
之前的文章讲解了通过官方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" }
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();
微信扫码分享