Sunday, October 9, 2022

Websockets and asyncio with web server and client

 server side=>

import asyncio
import websockets
async def response(websocket, path):
message = await websocket.recv()
print(f"We got the message from the client: {message}")
await websocket.send("I can confirm I got your message!")
start_server = websockets.serve(response, 'localhost', 1234)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

client side=>

import asyncio
import websockets
async def message():
async with websockets.connect("ws://localhost:1234") as socket:
msg = input("What do you want to send: ")
await socket.send(msg)
print(await socket.recv())
asyncio.get_event_loop().run_until_complete(message())

No comments:

Post a Comment

file tree for nodejs project

 find . \( -path "*/node_modules" -o -path "*/.git" \) -prune -o -print | tree -a -I 'node_modules|.git'