I am trying to send a message to the websocket from an ulr and another url receives it to update some data, let's say to make a dasboard, currently both connections are open,I can to send the message to the backend but the other url does not receive it, I would like to do it in pure javascript to understand this well, what other libraries could I use? And what is the problem that you can identify in the code?
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.websockets import WebSocket
app = FastAPI()
@app.get("/send")
def index():
return HTMLResponse(content="""
<html>
<head>
<title>Send Message</title>
</head>
<body>
<h1 id="message">Mensaje</h1>
<button id="send-button">Enviar</button>
<script>
const socket = new WebSocket("ws://localhost:8000/ws");
socket.onopen = function(e) {
console.log("Connect");
};
const sendButton = document.getElementById("send-button");
sendButton.addEventListener("click", function() {
socket.send("Hola");
});
</script>
</body>
</html>
""")
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
message = await websocket.receive_text()
print(message)
await websocket.send_text(message)
@app.get("/receive")
def enviar():
return HTMLResponse(content="""
<html>
<head>
<title>Receive</title>
</head>
<body>
<h1 id="received-message">Mensaje recibido</h1>
<script>
const socket = new WebSocket("ws://localhost:8000/ws");
socket.onopen = function(e) {
console.log("Connect");
};
socket.onmessage = function(event) {
const receivedMessage = document.getElementById("received-message");
receivedMessage.innerHTML = event.data;
};
</script>
</body>
</html>""")
Why my code dont work, best approach to handle websocket