python – 检测客户端何时与Heroku上的Django和Server-Sent Events断开连接
作者:互联网
Heroku关于sending a streaming response的文档说:
“If you’re sending a streaming response, such as with server-sent
events, you’ll need to detect when the client has hung up, and make
sure your app server closes the connection promptly. “
我一直在使用django-sse在Django中使用服务器发送事件对Heroku进行实验.它使用一个永远循环的迭代器,从Redis发布/订阅子频道读取消息并将它们发送到客户端:
def iterator(self):
connection = _connect()
pubsub = connection.pubsub()
pubsub.subscribe(self.get_redis_channel())
for message in pubsub.listen():
if message['type'] == 'message':
event, data = json.loads(message['data'])
self.sse.add_message(event, data)
yield
问题是,如果客户端断开连接,我想打破这个循环,所以我可以关闭与Redis的连接.如何检测客户端何时断开连接?
解决方法:
我在Heroku上的Scala Play2应用程序遇到了类似的问题,无法检测客户端在close()或刷新或窗口关闭时何时关闭SSE连接.启用新的Heroku Labs websockets feature为我解决了这个问题.
更新:
我问Heroku支持并告诉他们我的经历.这是他们的答复.
Hi Lloyd,
This is a known issue, and you are correct that the new WebSocket
endpoints fix the problem. We don’t plan to address the problem in
existing endpoints, but we will eventually rollout the WebSocket
endpoints to a wider audience.Best,
Jake
标签:python,heroku,django,server-sent-events 来源: https://codeday.me/bug/20190703/1370721.html