Skip to content

Instantly share code, notes, and snippets.

@ignassew
Created July 28, 2023 15:54
Show Gist options
  • Save ignassew/1bed1caaaad8bbded14fa9a0a3767354 to your computer and use it in GitHub Desktop.
Save ignassew/1bed1caaaad8bbded14fa9a0a3767354 to your computer and use it in GitHub Desktop.
A websocket server that you can use for testing. It will print all received messages to stdout
import argparse
import asyncio
def start_server(host, port):
async def handle_client(websocket):
client_addr = f"{websocket.remote_address[0]}:{websocket.remote_address[1]}"
print(f"[{client_addr}] Client connected")
# This function will be called each time a new client connects
try:
while True:
message = await websocket.recv()
print(f">>> {client_addr}: {message}")
except websockets.exceptions.ConnectionClosed:
print(f"[{client_addr}] Client connection closed")
print(f"Listening on {host}:{port}")
server = websockets.serve(handle_client, host, port)
# Start the WebSocket server
asyncio.get_event_loop().run_until_complete(server)
asyncio.get_event_loop().run_forever()
if __name__ == "__main__":
try:
import websockets
except:
print("Failed to import websockets. Try `pip install websockets`.")
parser = argparse.ArgumentParser(
prog="python test-websocket-server.py",
description="This is a websocket server that you can use for testing. It will print all received messages to stdout",
)
parser.add_argument("-H", "--host", default="0.0.0.0")
parser.add_argument("-p", "--port", default=8765)
args = parser.parse_args()
start_server(args.host, args.port)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment