Closed synodriver closed 2 years ago
In this way, is it better to send comment messages instead of ping?
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>
Hi synodriver, thanks for your input, much appreciated! Sorry for the late reply, different priorities currently. Will check it asap.
Thanks for your review.
Thanks synodriver for your contribution, much appreciated! Apologies again for the sluggish response.
According to the MDN Web Docs, sse servers can send messages that start with a colon.
This pr add supoport for sending comment messages, and API compatible with previous versions.