PubSub Websocket实时通信 - GoEasy在小程序中的使用
GoEasy在小程序中的使用
1.初始化GoEasy对象
//在app.js的globalData初始化全局GoEasy对象
globalData: {
goEasy: GoEasy.getInstance({
host:"hangzhou.goeasy.io", //若是新加坡区域:singapore.goeasy.io
appkey:"您的common key",
modules:['pubsub']//根据需要,传入‘pubsub’或'im’,或数组方式同时传入
})
}
2.建立连接
2.1首先在index.js中引入
let goEasy = getApp().globalData.goEasy;
let pubSub = goEasy.pubsub;
2.2建立连接
goEasy.connect({
id:"001", //pubsub选填,im必填
data:{"avatar":"/www/xxx.png","nickname":"Neo"}, //必须是一个对象,pubsub选填,im必填,用于上下线提醒和查询在线用户列表时,扩展更多的属性
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",//替换为您自己的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",//替换为您自己的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);
}
});
有问题欢迎留言哟~看到会即使回复哒