L
L
LakeForest2021-08-22 13:03:30
Python
LakeForest, 2021-08-22 13:03:30

How to send request to websockets server? And what is better to use to handle long running requests on the server?

1. I wrote a client, but I don't understand how to send a message to the server for a test? ...

client.

import asyncio
import logging
import websockets
from websockets import WebSocketServerProtocol
import os

def log_message(message: str) -> None:
    logging.info(f"Message: {message}")

async def consumer_handler(ws: WebSocketServerProtocol) -> None:
    async for message in ws:
        log_message(message)



async def consume(host: str, port: int) -> None:
    ws_url = f"ws://{host}:{port}"
    async with websockets.connect(ws_url) as ws:
        await consumer_handler(ws)
        ws.send("test test")
        print(await ws.recv())

if __name__ == '__main__':
    HOST = "server"
    PORT = 8001
    loop = asyncio.get_event_loop()
    loop.run_until_complete(consume(host=HOST, port=PORT))
    loop.run_forever()


2. What is better to use for long processing on the server side?
response = await loop.run_in_executor(pool, send_to_api, message)

Or is it okay to just write
response = await send_to_api(message) ?

(3.) I tried to deal with web sockets according to this article: https://nuancesprog.ru/p/6466/
Maybe someone understands where to run produce? I didn't understand its role in the code at all...

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question