aio-libs / aiohttp-sse

Server-sent events support for aiohttp

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Client doesn't close the connection

glaslos opened this issue · comments

Hey, I am using your example code with a simple change:

@asyncio.coroutine
def ws(request):
    resp = EventSourceResponse()
    resp.start(request)
    resp.send(json.dumps({'key': 'val'}))
    resp.stop_streaming()
    return resp

For some reason the client side keeps reconnecting to the server despite the resp.stop_streaming(). I am using Chrome Version 42.

Hi glaslos!

This behavior is by design:

Event streams requests can be redirected using HTTP 301 and 307 redirects as with normal HTTP
requests. Clients will reconnect if the connection is closed; a client can be told to stop reconnecting
using the HTTP 204 No Content response code.

See specification: http://www.w3.org/TR/2012/WD-eventsource-20120426/

Ah, I was under the assumption that resp.stop_streaming() tells the client that the server finished sending data.

What is then the correct way to close the connection from the server side?

I idea behind SSE is to persist connection, like websockets, so server can do push notification at any time. That is why client tries to reconnect. If you have short time connections you should use regular ajax instead.

Regarding you question, just return response object, but you almost never want to close connection from server side.

My pattern is: Client connects to page, server launches many asynchronous tasks and populates the page. When all data is fetched, close the connection. As the data is not changing, I don't see a reason to keep the connection open. I tried your approach to just return the response object but wasn't successful, the client tried to reconnect.

The new(#15) async context manager interface should clarify this question.
Feel free to re-open if you still have concerns.