在实际项目开发中,很多时候需要有web推送功能,但是websocket相对复杂,如果业务相对简单,可以考虑第三方推送如http://www.goeasy.io/。
GoEasy免费版支持60个并发,免费12个月,100000条消息,相信可以满足一个小型项目了。注册后申请应用,获得app key等信息。
后端推送消息
后端推送使用RestAPI方式推送
// 组合post数据
$postData = [
'appkey' => $appkey,
'channel' => $channel,
'content' => $content // content如果是数组,可以转换为json字符串
];
HttpService::post(<Rest Host>, $postData);复制代码
前端接收消息
<script type="text/javascript" src="http(s)://<CDN Host>/goeasy.js"></script>
<script type="text/javascript">
var goEasy = new GoEasy({
appkey: '您的app key'
});
goEasy.subscribe({
channel:'demo_channel',
onMessage: function(message){
alert('收到:'+message.content);
}
});
</script>复制代码
前端推送消息
goEasy.publish({
channel:'demo_channel',
message:'Hello world!'
});复制代码