PubSub Websocket实时通信 - GoEasy在小程序中的使用
GoEasy在小程序中的使用
1.初始化GoEasy对象
globalData: {
goEasy: GoEasy.getInstance({
host:"hangzhou.goeasy.io",
appkey:"您的common key",
modules:['pubsub']
})
}
2.建立连接
2.1首先在index.js中引入
let goEasy = getApp().globalData.goEasy;
let pubSub = goEasy.pubsub;
2.2建立连接
goEasy.connect({
id:"001",
data:{"avatar":"/www/xxx.png","nickname":"Neo"},
onSuccess: function () {
console.log("GoEasy connect successfully.")
},
onFailed: function (error) {
console.log("Failed to connect GoEasy, code:"+error.code+ ",error:"+error.content);
},
onProgress:function(attempts) {
console.log("GoEasy is connecting", attempts);
}
});
2.3订阅消息
pubSub.subscribe({
channel: "my_channel",
onMessage: function (message) {
console.log("Channel:" + message.channel + " content:" + message.content);
},
onSuccess: function () {
console.log("Channel订阅成功。");
},
onFailed: function (error) {
console.log("Channel订阅失败, 错误编码:" + error.code + " 错误信息:" + error.content)
}
});
2.4发送消息
pubSub.publish({
channel: "my_channel",
message: "Hello GoEasy!",
onSuccess:function(){
console.log("消息发布成功。");
},
onFailed: function (error) {
console.log("消息发送失败,错误编码:"+error.code+" 错误信息:"+error.content);
}
});
2.5取消订阅
goEasy.pubSub.unsubscribe({
channel: "my_channel",
onSuccess: function () {
alert("订阅取消成功。");
},
onFailed: function (error) {
alert("取消订阅失败,错误编码:" + error.code + " 错误信息:" + error.content)
}
});
2.6断开连接
goEasy.disconnect({
onSuccess: function(){
console.log("GoEasy disconnect successfully.")
},
onFailed: function(error){
console.log("Failed to disconnect GoEasy, code:"+error.code+ ",error:"+error.content);
}
});
有问题欢迎留言哟~看到会即使回复哒
|