2.0.0 • Published 2 years ago
ql-message v2.0.0
ql-message
a websocket client
安装
// with npm
npm install ql-message
// with yarn
yarn add ql-message
使用
引入
import QlMessage from 'ql-message';
初始化
名称 | 说明 | 类型 | 默认值 | 必填 |
---|---|---|---|---|
host | 服务器地址 不需要头部 | string | 是 | |
appId | appId | string | 是 | |
appkey | appkey | string | 是 | |
autoReconnect | 自动重连 | boolean | false | 否 |
maxReconnectCount | 自动重连尝试次数 | number | 10 | 否 |
//建议全局维护一个 `QlMessage`
const qlmessage = QlMessage.getInstance({ appId: 'xxx', appkey: 'xxx', host: 'localhost', autoReconnect: true });
连接
//连接
qlmessage.connect({
onSuccess: function (data) {
//连接成功
},
onFailed: function (data) {
//连接失败
}
});
//断开连接
qlmessage.disconnect();
订阅
//订阅
qlmessage.subscribe({
//替换为您自己的channel
channel: 'my_channel',
//频道消息
onMessage: function (message) {
console.log('Channel:' + message);
},
//订阅频道成功
onSuccess: function () {
console.log('Channel订阅成功。');
},
//订阅频道失败
onFailed: function (error) {
console.log('Channel订阅失败, 错误' + error);
}
});
//取消订阅
qlmessage.unsubscribe({
channel: 'my_channel',
onSuccess: function () {
alert('订阅取消成功。');
},
onFailed: function (error) {
alert('取消订阅失败,错误:' + error);
}
});
//或者
qlmessage.unsubscribe('my_channel');