Created
July 28, 2023 15:54
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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