简体   繁体   中英

Detecting when a client disconnects with Django and Server-Sent Events on Heroku

Heroku's documentation about sending a streaming response says:

"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. "

I've been experimenting on Heroku with Server-Sent Events in Django, using django-sse . It uses an iterator that loops forever, reading messages from a Redis pub/sub channel and sending them to the client:

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

The problem is that I would like to break out of this loop if the client disconnects, so I can close the connection to Redis. How can I detect when the client disconnects?

I had similar problems with a Scala Play2 application on Heroku that wouldn't detect when an SSE connection was being closed by the client on either close() or refresh or window closing. Enabling the new Heroku Labs websockets feature fixed this for me.

An update:

I asked Heroku support and told them about my experience. This was their reply.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM