Spacen Jasset
Spacen Jasset

Reputation: 976

dealing with server side event disconnections

I have a simple python bottle application that emits SSE events to a javascript listener.

This works without problems until the client 'goes away' via a browser refresh or page back etc.

Because the events from the application are delivered and then removed from an internal queue, one or two events are lost when the server tries to send them to a client that is no longer there.

I don't want the events to be lost, but I cannot currently see a way to fix this in a sensible manner.

I plan to switch to web sockets instead and use an event - acknowledgement model to solve the problem unless there is something I could do with the SSE to prevent the events from being lost in this way.

It seems to me that SEE may not be designed for my particular use case in mind.

Here is the code I am using:

@route('/stream/events')
def event_stream():
    response.content_type  = 'text/event-stream'
    response.cache_control = 'no-cache'
    # Set client-side auto-reconnect timeout, ms.
    yield 'retry: 1000\n\n'

    while True:
        event = event_queue.get()
        logging.debug("Received event from hal: %s", event)
        yield "data: " + json.dumps(event) + "\n\n"

A link to my solution for the problem can be found here. It uses weak references to 'detect' when a client has gone away, aswell as individual queues per SEE connection: http://blog.jason.spashett.com/python-bottle-server-side-events-one-way-to-handle-client-disconnects.html

Upvotes: 6

Views: 4384

Answers (2)

baynezy
baynezy

Reputation: 7066

You need to persist the events on your server so that on a reconnection or a page refresh you can retrieve them.

I talk about this subject in a blog post.

http://bayn.es/real-time-web-apps-with-server-sent-events-pt-2/

Upvotes: 6

mguijarr
mguijarr

Reputation: 7930

SSE (Server Sent Events, part of HTML 5 specification) are like a radio broadcast: once events are emitted, they are forgotten by the server.

It's a very good way of sending information from the server to clients, but it's only one-way.

As it is not possible to reliably detect client disconnection, in your use case a possible solution indeed is to do a kind of acknowledgement like you suggest. Web sockets are ok for this since it is a two-ways communication technique.

However you can think of another scheme, combining SSE with another mechanism, for example: client could emit an AJAX request every time an event is received (acknowledgement). In order to minimize latency due to connection time, you can use keep-alive requests. It depends on the frequency of your events, in case of a lot of events per second forget about this.

Upvotes: 0

Related Questions