python服务端使用GoEasy实现websocket消息推送

python服务端使用GoEasy实现websocket消息推送

     WebSocket 是 HTML5 提供的一种浏览器与服务器间进行全双工通讯的协议。依靠这种协议可以实现客户端和服务器端 ,一次握手,双向实时通信。

目前GoEasy提供完整的websocket前后端解决方案,简单的几行代码集成,即可快速搭建您的专属websocket服务。

GoEasy提供了灵活多样的服务端语言使用的Restful API接口,我们可以通过GoEasy提供的Rest API灵活、高效的推送消息 。

下面我们来看看如何在python中使用GoEasy来完成websocket服务的搭建:

1、python服务端websocket实现:

以下是GoEasy开发文档中提供的python实现websocket的演示代码。通过简单的调用Rest API接口,我们可以将想要推送的消息推送到任何客户端。

  import requests

  appkey = "BC-xxxxxxxxx"
  channel = "my_channel"
  content = "Hello, GoEasy!"
  data = {"appkey" : appkey, "channel" : channel, "content" : content}
  url = "http(s)://<REST Host>/publish"
  response = requests.post(url, data = data)
  print response.text
                

2、客户端接收消息:

我们假设要接收消息的客户端使用的是html,那么要在html中接收消息,使用以下代码即可:

<!--[if lte IE 8]>//如果需要支持低版本的IE8及以下
<script  type="text/javascript" src="https://cdn.goeasy.io/json2.js"></script>
<![endif]-->

<script type="text/javascript" src="https://cdn.goeasy.io/goeasy-1.0.3.js"></script>
<script>
var goEasy = new GoEasy({
    host:'hangzhou.goeasy.io', //应用所在的区域地址: 【hangzhou.goeasy.io |singapore.goeasy.io】
    appkey: "my_appkey", //替换为您的应用appkey
});
//GoEasy-OTP可以对appkey进行有效保护,详情请参考​ ​ 
//如果需要使用HTTPS/WSS,请在连接初始化GoEasy对象的时候传入参数forceTLS,并设置为true。
</script>
<script>
goEasy.subscribe({
    channel: "my_channel", //替换为您自己的channel
    onMessage: function (message) {
        console.log("Channel:" + message.channel + " content:" + message.content);
    }
});
</script>

另外GoEasy还支持更多的前端技术框架比如小程序、react、vue、uniapp等。同时还是支持php、java、C#等服务端语言。 更多关于Rest API的使用技巧,可以来这里看看:GoEasy服务器发送消息

Comments are closed.