Route websocket client messages to websocket server
NickName:xchrisbradley Ask DateTime:2022-08-23T03:48:12

Route websocket client messages to websocket server

I'm trying to ingest data from an external WebSocket using Websocket Client A and send those messages to WebSocket Server B for clients connected to B to view. (Reason being, I'm trying to connect multiple external WebSockets and feed their messages to a single point, if this is a bad design can someone suggest an alternative)

Running server B uvicorn server:app --reload then visit http://127.0.0.1:8000/

WebSocket Server B

from typing import List

from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse

app = FastAPI()

html = """
<!DOCTYPE html>
<html>
    <head>
        <title>Screener</title>
    </head>
    <body>
        <h2>Your ID: <span id="ws-id"></span></h2>
        <ul id='messages'>
        </ul>
        <script>
            var client_id = Date.now()
            document.querySelector("#ws-id").textContent = client_id;
            var ws = new WebSocket(`ws://localhost:8000/ws/${client_id}`);
            ws.onmessage = function(event) {
                var messages = document.getElementById('messages')
                var message = document.createElement('li')
                var content = document.createTextNode(event.data)
                message.appendChild(content)
                messages.appendChild(message)
            };
            function sendMessage(event) {
                var input = document.getElementById("messageText")
                ws.send(input.value)
                input.value = ''
                event.preventDefault()
            }
        </script>
    </body>
</html>
"""


class ConnectionManager:
    def __init__(self):
        self.active_connections: List[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def send_personal_message(self, message: str, websocket: WebSocket):
        await websocket.send_text(message)

    async def broadcast(self, message: str):
        for connection in self.active_connections:
            await connection.send_text(message)


manager = ConnectionManager()


@app.get("/")
async def get():
    return HTMLResponse(html)


@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: int):
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await manager.send_personal_message(f"You wrote: {data}", websocket)
            await manager.broadcast(f"Client #{client_id} says: {data}")
    except WebSocketDisconnect:
        manager.disconnect(websocket)
        await manager.broadcast(f"Client #{client_id} left the chat")

WebSocket ClientA

#!/usr/bin/env python
import websocket
import _thread
import time
import asyncio
import websockets

from concurrent.futures import ThreadPoolExecutor

_EXECUTOR_ = ThreadPoolExecutor(1)

async def main_loop():
  async with websockets.connect("ws://localhost:8000/ws/1") as server_ws:
    await server_ws.send("main_loop")
    
    def send_message(message):
      server_ws.send(message)

    def ws_message(ws, message):
      loop = asyncio.get_event_loop()
      loop.run_in_executor(_EXECUTOR_, send_message, message)
      print("WebSocket thread: %s" % message)

    def ws_open(ws):
      ws.send('{"event":"subscribe", "subscription":{"name":"trade"}, "pair":["XBT/USD","XRP/USD"]}')

    def ws_thread(*args):
      ws = websocket.WebSocketApp("wss://ws.kraken.com/", on_open = ws_open, on_message = ws_message)
      ws.run_forever()

    _thread.start_new_thread(ws_thread, ())

    while True:
        time.sleep(5)
        print("Main thread: %d" % time.time())

asyncio.run(main_loop())

Copyright Notice:Content Author:「xchrisbradley」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/73450315/route-websocket-client-messages-to-websocket-server

More about “Route websocket client messages to websocket server” related questions

Route websocket client messages to websocket server

I'm trying to ingest data from an external WebSocket using Websocket Client A and send those messages to WebSocket Server B for clients connected to B to view. (Reason being, I'm trying to connect

Show Detail

Websocket - browser websocket is not receiving messages from server

I built a websocket server and client with Node and both is working fine. But, I built a client on a single html page and there, websocket is listening messages just when I call sendUTF from browse...

Show Detail

Websocket server not getting all messages from client

Using a .net console app, I've created a websocket server. And a separate app for the client end. I've used this webpage to create the server side code (https://developer.mozilla.org/en-US/docs/We...

Show Detail

Handling websocket client messages with aleph

During my quest to learn Clojure I am currently facing problems with setting up websocket communitation. After many different approaches, I ended up using aleph. What I managed to achieve: handli...

Show Detail

Pinging Websocket server with Websocket .NET client

I'm trying to figure out how to send ping/pong heartbeats in order to be sure to maintain a connection with a Websocket server using Websocket .NET client in a .NET Core WPF Application, so I'm tes...

Show Detail

sending messages to a websocket server using em-websocket-client

I am new to websockets and am trying to send messages to an existing websocket server that expects a subscription request. I tried: require 'em-websocket-client' EM.run do ws = EventMachine::

Show Detail

Websocket server memory leak: large messages

I have a simple websocket server in nodejs using npm ws (the behavior is the same with npm websocket). I have a .NET core back-end communicating directly with the ws server feeding a react front en...

Show Detail

Erlang websocket client with cowboy server

Im trying to use this websocket client library but with little success. Erlang websocket client If someone used this library to build a client talking to a remote server, how were you able to send

Show Detail

Websocket server sending spontaneous messages (without requests from the client)

I must admit I may have missed something fundamental. If so, please point it out. All that follows is how I understand a websocket server. I'm trying to write a websocket server that should keep a

Show Detail

Sending messages from Android Websocket client

I want to send a message from Android okhttp3 websocket client, not just echoing the messages coming from the server. here is my websocket class: // Websocket public final class EchoWebSocketList...

Show Detail