Reputation: 8352
I'm trying to get a websocket connection to automatically restart after it has been closed by the server.
My example code works, when I open the page in a browser at "http://127.0.0.1:5082/". The websocket counter counts up, the debug text "message" is displayed.
When I turn off the server, the debug message "close" appears, then "start/close" alternate.
When I turn the server on again, there are dozens of websockets running and the debug message quickly changes between "message" and "close"
How do I make sure that only one websocket connection is alive at a time?
Minimal example, using Python's FastAPI as a server:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Websocket test</title>
</head>
<body>
<div id="container">
OK - wait for websocket
</div>
<hr noshade>
<div id="debug">
Some debug text here
</div>
<script>
var debug_container = document.getElementById("debug")
debug_container.innerHTML = "Debug: Javascript is running"
function my_websocket() {
debug_container.innerHTML = "starting"
var ws = new WebSocket("ws://localhost:5082/ws")
ws.addEventListener('message', function (event) {
debug_container.innerHTML = "message"
var container = document.getElementById("container")
container.innerHTML = event.data
})
ws.addEventListener('open', function (event) {
debug_container.innerHTML = "open"
})
ws.addEventListener('close', function (event) {
debug_container.innerHTML = "close";
setInterval(my_websocket, 5000);
})
ws.addEventListener('error', function (event) {
debug_container.innerHTML = "error"
})
}
my_websocket()
</script>
</body>
</html>
The websocket is served by a Python FastAPI server
import uvicorn
import websockets
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
from pathlib import Path
import asyncio
app = FastAPI()
@app.get('/')
def index():
return HTMLResponse(Path("index.html").read_text())
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
cnt = 1
while True:
cnt += 1
try:
await websocket.send_text(f"{cnt}")
except websockets.exceptions.ConnectionClosedOK:
break
await asyncio.sleep(0.25)
if __name__ == '__main__':
uvicorn.run(app=app, host="0.0.0.0", port=5082)
Upvotes: 0
Views: 1147
Reputation: 340
The reason why the client establishes multiple websocket connections is due to the following code:
ws.addEventListener('close', function (event) {
debug_container.innerHTML = "close";
setInterval(my_websocket, 5000);
})
Using setInterval causes it to create a new websocket connection every 5 seconds. I think you meant to use setTimeout() instead.
Upvotes: 1