最近使用GoEasy在web端进行实时信息推送,代码极其简单,记录一下,供大家参考:
一提到实时推送,那么大家会想到两点,一是轮询,二是http长连接。GoEasy是基于http长连接封装的免费推送服务,我们不需要考虑后台是如何实现的,而且上手相当快,一个demo几分钟就搞定。GoEasy推送支持Java,JavaScript端的推送,这里我只举个在JavaScript推送和接收的例子,其余的请参考goeasy官网 http://goeasy.io/www/started, 官网上还有详细使用文档 http://goeasy.io/www/documents。
实现步骤相当简单:
1. 在web页面导入goeasy.js
<script src="https://cdn.goeasy.io/goeasy-2.13.2.min.js"></script>
2. 初始化goeasy
let goeasy = goeasy.getInstance({
host:"hangzhou.goeasy.io", //若是新加坡区域:singapore.goeasy.io
appkey:"您的common key",
modules:['pubsub']//根据需要,传入‘pubsub’或'im’,或数组方式同时传入
});
3.在web端建立连接
//建立连接
goeasy.connect({
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);
}
});
4. 在web页面订阅channel
var pubsub = goeasy.pubsub;
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)
}
});
5. 在web页面向已订阅channel的页面推送消息
pubsub.publish({
channel: "my_channel",//替换为您自己的channel
message: "Hello GoEasy!",//替换为您想要发送的消息内容
onSuccess:function(){
console.log("消息发布成功。");
},
onFailed: function (error) {
console.log("消息发送失败,错误编码:"+error.code+" 错误信息:"+error.content);
}
});
所有订阅了channel为“demo_channel“的页面都可以接收消息”Hello world!“
GoEasy官网上的Demo: http://goeasy.io/www/demos
大家可以在多个浏览器里打开这个demo页面,然后在其中一个页面推送给一条信息,可以看到其他浏览器也接收到了该信息。
完毕!