'How do I run the consumer, producer, and server files in python websockets
I have three python files here, (I read a tutorial), and they are a producer, a consumer, and a server file.
The goal being to send "hi" from the producer to the consumer. Assuming I wanted to send it to my laptop from my PC, (on same LAN), how would I do that? When I run any of the programs individually, it gives me the error:
ConnectionRefusedError: [WinError 1225] The remote computer refused the network connection
(When used with localhost, port 4000)
Here is server.py:
import asyncio, logging, websockets
from websockets import WebSocketServerProtocol
logging.basicConfig(level=logging.INFO)
class Server():
clients = set()
async def register(self, ws: WebSocketServerProtocol) -> None:
self.clients.add(ws)
logging.info(f"{ws.remote_address} connects.")
async def unregister(self, ws: WebSocketServerProtocol) -> None:
self.clients.remove(ws)
logging.info(f"{ws.remote_address} disconnects.")
async def send_to_clients(self, message: str) -> None:
if self.clients:
await asyncio.wait([client.send(message) for client in self.clients])
async def ws_handler(self, ws: WebSocketServerProtocol, uri: str) -> None:
await self.register(ws)
try:
await self.distribute(ws)
finally:
await self.unregister(ws)
async def distribute(self, ws: WebSocketServerProtocol) -> None:
async for message in ws:
await self.send_to_clients(message)
Here is consumer.py:
import asyncio, logging, websockets
from websockets import WebSocketClientProtocol
from websockets import WebSocketServerProtocol
logging.basicConfig(level=logging.INFO)
async def consumer_handler(websocket: WebSocketClientProtocol) -> None:
async for message in websocket:
log_message(message)
async def consume(hostname: str, port: int) -> None:
websocket_resource_url = f"ws://{hostname}:{port}"
async with websockets.connect(websocket_resource_url) as websocket:
await consumer_handler(websocket)
def log_message(message: str) -> None:
logging.info(f"Message: {messaage}")
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(consume(hostname="localhost", port=4000))
loop.run_forever()
server=Server()
start_server = websockets.serve(server.ws_handler, "localhost", 4000)
loop = asyncio.get_event_loop()
loop.run_until_complete(start_server)
loop.run_forever()
And here is producer.py:
import asyncio, websockets
async def produce(message: str, host: str, port: int) -> None:
async with websockets.connect(f"ws://{host}:{port}") as ws:
await ws.send(message)
await ws.recv()
asyncio.run(produce(message='hi', host='localhost', port=4000))
Can someone please tell me how to run this!?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
