1

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

  • Please have a look at [this answer](https://stackoverflow.com/a/74639030/17865804) and [this answer](https://stackoverflow.com/a/70996841/17865804). – Chris Feb 10 '23 at 16:38
  • Thanks Chris, I understood, my problem is that open different connections. I solved it by attaching all connections to the websocket. – Arnold Coto Feb 11 '23 at 04:06

1 Answers1

0

This is how I resolved

customers = []
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    customers.append(websocket)
    await websocket.accept()
    while True:
        message = await websocket.receive_text()
        for customer in customers:
                await customer.send_text(message)