代码拉取完成,页面将自动刷新
socket.io是一个在客户端和服务器之间实现低延迟、双向和基于事件的通信的库。建立在 WebSocket 协议之上,并提供额外的保证,例如回退到 HTTP 长轮询或自动重新连接。
ohpm install @ohos/socketio
OpenHarmony ohpm 环境配置等更多内容,请参考如何安装 OpenHarmony ohpm 包
import { client_socket } from '@ohos/socketio';
client: client_socket = new client_socket();
this.client.set_open_listener(this.on_open.bind(this));
this.client.set_fail_listener(this.on_fail.bind(this));
this.client.set_reconnecting_listener(this.on_reconnecting.bind(this));
this.client.set_reconnect_listener(this.on_reconnect.bind(this));
this.client.set_close_listener(this.on_close.bind(this));
this.client.set_socket_open_listener(this.on_socket_open.bind(this));
this.client.set_socket_close_listener(this.on_socket_close.bind(this));
this.client.connect(uri) //uri: socket.io服务端地址
on_user_left_listener(event_json: string): void {
//回调数据处理
}
this.client.on("new message", this.on_new_message_listener.bind(this));
this.client.on("user joined", this.on_user_joined_listener.bind(this));
this.client.on("user left", this.on_user_left_listener.bind(this));
this.client.on("login", this.on_login_listener.bind(this));
this.client.emit("add user", username, this.on_emit_callback.bind(this));
this.client.emit("new message", message, this.on_emit_callback);
this.client.close();
client: client_socket = new client_socket();
set_open_listener(on_open: () => void)
set_fail_listener(on_fail: () => void)
set_reconnecting_listener(on_reconnecting: () => void)
set_reconnect_listener(on_reconnect: () => void)
set_close_listener(on_close: (reason: string) => void)
set_socket_open_listener(on_socket_open: (nsp: string) => void)
set_socket_close_listener(on_socket_close: (nsp: string) => void)
set_headers(headers: string)
connect(uri: string)
clear_con_listeners()
clear_socket_listeners()
set_reconnect_attempts(attempts: number)
set_reconnect_delay(millis: number)
set_reconnect_delay_max(millis: number)
close()
sync_close()
opened(): boolean
get_sessionid(): string
on(event_name: string, on_event_listener: (event_json: string) => void)
socket_close()
on_error(on_error_listener: (message: string) => void)
off_error()
emit(name: string, message: string, on_emit_callback?: (emit_callback_json: string) => void)
get_current_state(): number
// demo示例
this.client.on("disconnect", data: string => {
console.log("disconnect", data);
});
// demo示例
this.client.on("ping_pong", data: string => {
console.log("ping_pong", data);
});
git submodule
引入,下载代码时需加上--recursive
参数。git clone --recursive https://gitee.com/openharmony-tpc/openharmony_tpc_samples.git
在下述版本验证通过:
|---- socketio
| |---- entry # 示例代码文件夹
| |---- library # socket.io库
| |---- ets #对外接口目录
|---- client_socket.ets # 对外接口
|---- cpp # 组件代码目录
|---- src # 核心类目录
|---- client_socket.cpp # socket.io客户端NAPI层
| |---- README.md # 安装使用方法
使用过程中发现任何问题都可以提 Issue 给组件,当然也非常欢迎给 发 PR 共建。
本项目基于 MIT LICENSE ,请自由地享受和参与开源。
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。