0

我想使用频道 api 推送更新以打开页面,到目前为止我所做的是将页面客户端 id 存储在 ndb 中 - 我已经包含了代码摘要

我的问题是:如何管理已关闭的页面和过期的令牌?

这是将更新推送到许多打开页面的最佳方式吗?

打开页面代码:

import webapp2
import uuid
from google.appengine.api import channel
from google.appengine.ext import ndb

class Frame(ndb.Model):
  clientID = ndb.StringProperty()
  date = ndb.DateTimeProperty(auto_now_add=True)

class MainHandler(BaseHandler):
    def get(self):
        client_id = str(uuid.uuid4())
        channel_token = channel.create_channel(client_id)
        frame = Frame(clientID = client_id)
        frame.put()

        self.render_response('home.html',** "token":channel_token,"client_id":client_id)

发送消息代码:

from google.appengine.api import channel
from google.appengine.ext import ndb

class Frame(ndb.Model):
  clientID = ndb.StringProperty()
  date = ndb.DateTimeProperty(auto_now_add=True)

frames = Frame.query().fetch(10)

for i in frames:
   channel.send_message(i.clientID, "some message to update")
4

1 回答 1

2

当您启用 channel_presence 时,您的应用程序会接收到以下 URL 路径的 POST:

POSTs to /_ah/channel/connected/ 
POSTs to /_ah/channel/disconnected/ 

这些信号表明客户端已连接到通道并且可以接收消息或已断开连接。

Tracking_Client_Connections_and_Disconnections

处理过期令牌:

默认情况下,令牌会在两小时后过期,除非您在生成令牌时通过向 create_channel() 函数提供 duration_minutes 参数来明确设置过期时间。如果客户端保持连接到通道的时间超过令牌持续时间,则调用套接字的 onerror() 和 onclose() 回调。此时,客户端可以向应用程序发出 XHR 请求以请求新令牌并打开新通道。

所以在你的onerror功能上,你基本上就像原来的连接一样重新做一遍。

代币和安全

要向许多打开的页面发送更新,只需遍历您的已连接用户列表并单独向他们发送消息。没有“传送给所有人”功能。

您可能还想构建一个“心跳”,将消息发送到假定连接的客户端,如果没有回复,则将其删除。这是因为有时(显然)在关闭浏览器窗口时不会发送断开连接的消息(电源故障等)。

于 2013-01-07T13:06:58.890 回答