| 1 |
import asyncio |
| 2 |
from datetime import datetime |
| 3 |
|
| 4 |
from aiohttp import web |
| 5 |
|
| 6 |
from aiohttp_sse import sse_response |
| 7 |
|
| 8 |
|
| 9 |
async def hello(request: web.Request) -> web.StreamResponse: |
| 10 |
async with sse_response(request) as resp: |
| 11 |
while resp.is_connected(): |
| 12 |
data = f"Server Time : {datetime.now()}" |
| 13 |
print(data) |
| 14 |
await resp.send(data) |
| 15 |
await asyncio.sleep(1) |
| 16 |
return resp |
| 17 |
|
| 18 |
|
| 19 |
async def index(_request: web.Request) -> web.StreamResponse: |
| 20 |
html = """ |
| 21 |
<html> |
| 22 |
<body> |
| 23 |
<script> |
| 24 |
var eventSource = new EventSource("/hello"); |
| 25 |
eventSource.addEventListener('message', event => { |
| 26 |
document.getElementById('response').innerText = event.data; |
| 27 |
}); |
| 28 |
</script> |
| 29 |
<h1>Response from server:</h1> |
| 30 |
<div id="response"></div> |
| 31 |
</body> |
| 32 |
</html> |
| 33 |
""" |
| 34 |
return web.Response(text=html, content_type="text/html") |
| 35 |
|
| 36 |
|
| 37 |
if __name__ == "__main__": |
| 38 |
app = web.Application() |
| 39 |
app.router.add_route("GET", "/hello", hello) |
| 40 |
app.router.add_route("GET", "/", index) |
| 41 |
web.run_app(app, host="127.0.0.1", port=8080) |