sysid / sse-starlette

BSD 3-Clause "New" or "Revised" License
505 stars 36 forks source link

add sse comment support #22

Closed synodriver closed 2 years ago

synodriver commented 2 years ago

According to the MDN Web Docs, sse servers can send messages that start with a colon.

A colon as the first character of a line is in essence a comment, and is ignored.

Note: The comment line can be used to prevent connections from timing out; a server can send a comment periodically to keep the connection alive.

This pr add supoport for sending comment messages, and API compatible with previous versions.

synodriver commented 2 years ago

In this way, is it better to send comment messages instead of ping?

synodriver commented 2 years ago

And here is an example

import asyncio

from fastapi import FastAPI, APIRouter
from fastapi.staticfiles import StaticFiles
from sse_starlette.sse import EventSourceResponse

app = FastAPI(title=__name__)
router = APIRouter(prefix="/sse")

async def numbers(minimum, maximum):
    for i in range(minimum, maximum + 1):
        yield {"comment": "You can't see\r\nme"}
        await asyncio.sleep(1)
        yield f"You\r\ncan see me and I'm the {i}"

@router.get("")
async def handle():
    generator = numbers(1, 100)
    return EventSourceResponse(generator, headers={"Server": "nini"})

app.include_router(router)
app.mount("/", StaticFiles(directory="./statics"))

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var es = new EventSource('sse');

    es.onmessage = function (e) {
        console.log(e.data);
    };
    es.addEventListener('myevent', function (e) {
        console.log(e.data);
    });

</script>
<h1>look at the console</h1>
</body>
</html>
sysid commented 2 years ago

Hi synodriver, thanks for your input, much appreciated! Sorry for the late reply, different priorities currently. Will check it asap.

synodriver commented 2 years ago

Thanks for your review.

sysid commented 2 years ago

Thanks synodriver for your contribution, much appreciated! Apologies again for the sluggish response.