import asyncio import random from sanic.response import html, stream from sanic.blueprints import Blueprint blueprint = Blueprint("blueprint") @blueprint.websocket("/sock/real-price") async def sock_price(request, ws): i = 1 while True: await asyncio.sleep(random.random()) s = "data: " + str(i) + "\r\n\r\n" await ws.send(s) i += 1 @blueprint.route("/sse/real-price") async def stream_price(request): async def streaming_func(response): i = 1 while True: await asyncio.sleep(random.random()) s = "data: " + str(i) + "\r\n\r\n" await response.write(s.encode()) i += 1 return stream(streaming_func, content_type="text/event-stream") def init_app(app) -> None: """ Register Blueprints to App """ app.blueprint(blueprint) # Base Route @app.route("/", methods=["GET"]) def home(request): with open("app/templates/index.html", encoding="utf-8") as f: return html(f.read()) @app.route("/sock") async def sock(request): with open("app/templates/socket.html", encoding="utf-8") as f: return html(f.read())
This is my code in router.py. And I’m trying to test
When I’m using SSE, I’m restricted to only 6 index.html,
and after that, additional network connection to /sse/real-price is pending.
Existing 6 same pages work well, but additional page freeze because of the pending connection.
When I’m using websocket, it works regardless of the number of pages.
Is it natural or did I do something wrong? if it’s natural, websocket is better than sse in webpages with many users.