### Typical Server Usage Source: https://github.com/python-websockets/websockets/blob/main/docs/reference/asyncio/server.md Demonstrates a common pattern for initializing a server with additional setup before starting it. Use this when you need to perform actions after the server object is created but before it begins accepting connections. ```python server = await serve(..., start_serving=False) # perform additional setup here... # ... then start the server await server.start_serving() ``` -------------------------------- ### Install Websockets Client Source: https://github.com/python-websockets/websockets/blob/main/docs/deploy/render.md Sets up a virtual environment and installs the 'websockets' library, which includes an interactive client. This is used to test the deployed websockets server. ```bash python -m venv websockets-client . websockets-client/bin/activate pip install websockets ``` -------------------------------- ### Basic Route Configuration Example Source: https://github.com/python-websockets/websockets/blob/main/docs/reference/sync/server.md This example demonstrates how to set up a URL map with Werkzeug rules and use the `route` function to create a server that dispatches connections to specific handlers based on URL parameters like `channel_id`. ```python from websockets.sync.router import route from werkzeug.routing import Map, Rule def channel_handler(websocket, channel_id): ... url_map = Map([ Rule("/channel/", endpoint=channel_handler), ... ]) with route(url_map, ...) as server: server.serve_forever() ``` -------------------------------- ### Install websockets Client Source: https://github.com/python-websockets/websockets/blob/main/docs/deploy/koyeb.md Install the websockets Python package in a virtual environment to use the interactive client. ```console $ python -m venv websockets-client $ . websockets-client/bin/activate $ pip install websockets ``` -------------------------------- ### Start WebSocket Server Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial2.md Initializes and starts the WebSocket server on the specified host and port, using the connection handler. This is the main entry point for the server. ```python async def main(): async with serve(handler, "", 8001) as server: ``` -------------------------------- ### Install python-socks for SOCKS proxies Source: https://github.com/python-websockets/websockets/blob/main/docs/topics/proxies.md To use SOCKS proxies, you need to install the `python-socks` library with asyncio support. This command installs the necessary package. ```console $ pip install python-socks[asyncio] ``` -------------------------------- ### Start HTTP Server with Python Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial1.md Run this command in your terminal to start a simple HTTP server. This is often used for serving front-end files. ```console $ python -m http.server ``` -------------------------------- ### Start HTTP server with Python Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial1.md Command to start a simple HTTP server in Python. This is used to serve the game's HTML, CSS, and JavaScript files to the browser. ```console python -m http.server ``` -------------------------------- ### Install watchdog with watchmedo Source: https://github.com/python-websockets/websockets/blob/main/docs/howto/autoreload.md Install the watchdog library, which includes the `watchmedo` utility for monitoring file changes and automatically restarting processes. ```bash pip install 'watchdog[watchmedo]' ``` -------------------------------- ### Start a WebSocket Server Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/examples.md This server receives a name, sends a greeting, and closes the connection. It uses `websockets.asyncio.server.serve` to handle connections. ```python #!/usr/bin/env python import asyncio from websockets.asyncio.server import serve async def hello(websocket): name = await websocket.recv() print(f"<<< {name}") greeting = f"Hello {name}!" await websocket.send(greeting) print(f">>> {greeting}") async def main(): async with serve(hello, "localhost", 8765) as server: await server.serve_forever() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install websockets CLI Client Source: https://github.com/python-websockets/websockets/blob/main/docs/deploy/fly.md Install the websockets library and its command-line interface client in a virtual environment. This client is used for testing the deployed server. ```console python -m venv websockets-client . websockets-client/bin/activate pip install websockets ``` -------------------------------- ### Install websockets with pip Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/index.md Use this command to install the websockets library. Wheels are available for all platforms. ```console pip install websockets ``` -------------------------------- ### Define Application Startup Command Source: https://github.com/python-websockets/websockets/blob/main/docs/deploy/koyeb.md Specifies the command to run the web application. This Procfile is used by platforms like Koyeb to start the service. ```default web: python app.py ``` -------------------------------- ### Python Websockets Server Setup Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial3.md Sets up and runs an asynchronous websockets server. Includes signal handling for graceful shutdown. ```python async def main(): port = int(os.environ.get("PORT", "8001")) async with serve(handler, "", port, process_request=health_check) as server: loop = asyncio.get_running_loop() loop.add_signal_handler(signal.SIGTERM, server.close) await server.wait_closed() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install Werkzeug for Complex Routing Source: https://github.com/python-websockets/websockets/blob/main/docs/topics/routing.md Install the `werkzeug` library to enable advanced routing capabilities provided by the `route()` function. ```console $ pip install werkzeug ``` -------------------------------- ### Install websockets and Supervisor Source: https://github.com/python-websockets/websockets/blob/main/docs/deploy/supervisor.md Installs the necessary Python packages for the websockets server and the Supervisor process manager. ```bash pip install websockets pip install supervisor ``` -------------------------------- ### Handler for Initial Connection and Game Start Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial2.md Receives and parses the 'init' event from the UI, then calls the start coroutine to begin a new game. ```python async def handler(websocket): # Receive and parse the "init" event from the UI. message = await websocket.recv() event = json.loads(message) assert event["type"] == "init" # First player starts a new game. await start(websocket) ``` -------------------------------- ### Check websockets installation Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial1.md Verify that the websockets library has been installed correctly by checking its version. ```console websockets --version ``` -------------------------------- ### Install Werkzeug for Routing Source: https://github.com/python-websockets/websockets/blob/main/docs/reference/sync/server.md To use the routing features, you need to install the third-party Werkzeug library. This command installs the latest version. ```console $ pip install werkzeug ``` -------------------------------- ### Initialize and Serve Websockets Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial3.md This is the main entry point for the websockets server. It sets up signal handling for graceful shutdown and starts the server to listen for incoming connections. ```python #!/usr/bin/env python import asyncio import http import json import os import secrets import signal from websockets.asyncio.server import broadcast, serve from connect4 import PLAYER1, PLAYER2, Connect4 JOIN = {} WATCH = {} async def error(websocket, message): """ Send an error message. """ event = { "type": "error", "message": message, } await websocket.send(json.dumps(event)) async def replay(websocket, game): """ Send previous moves. """ # Make a copy to avoid an exception if game.moves changes while iteration # is in progress. If a move is played while replay is running, moves will # be sent out of order but each move will be sent once and eventually the # UI will be consistent. for player, column, row in game.moves.copy(): event = { "type": "play", "player": player, "column": column, "row": row, } await websocket.send(json.dumps(event)) async def play(websocket, game, player, connected): """ Receive and process moves from a player. """ async for message in websocket: # Parse a "play" event from the UI. event = json.loads(message) assert event["type"] == "play" column = event["column"] try: # Play the move. row = game.play(player, column) except ValueError as exc: # Send an "error" event if the move was illegal. await error(websocket, str(exc)) continue # Send a "play" event to update the UI. event = { "type": "play", "player": player, "column": column, "row": row, } broadcast(connected, json.dumps(event)) # If move is winning, send a "win" event. if game.winner is not None: event = { "type": "win", "player": game.winner, } broadcast(connected, json.dumps(event)) async def start(websocket): """ Handle a connection from the first player: start a new game. """ # Initialize a Connect Four game, the set of WebSocket connections # receiving moves from this game, and secret access tokens. game = Connect4() connected = {websocket} join_key = secrets.token_urlsafe(12) JOIN[join_key] = game, connected watch_key = secrets.token_urlsafe(12) WATCH[watch_key] = game, connected try: # Send the secret access tokens to the browser of the first player, # where they'll be used for building "join" and "watch" links. event = { "type": "init", "join": join_key, "watch": watch_key, } await websocket.send(json.dumps(event)) # Receive and process moves from the first player. await play(websocket, game, PLAYER1, connected) finally: del JOIN[join_key] del WATCH[watch_key] async def join(websocket, join_key): """ Handle a connection from the second player: join an existing game. """ # Find the Connect Four game. try: game, connected = JOIN[join_key] except KeyError: await error(websocket, "Game not found.") return # Register to receive moves from this game. connected.add(websocket) try: # Send the first move, in case the first player already played it. await replay(websocket, game) # Receive and process moves from the second player. await play(websocket, game, PLAYER2, connected) finally: connected.remove(websocket) async def watch(websocket, watch_key): """ Handle a connection from a spectator: watch an existing game. """ # Find the Connect Four game. try: game, connected = WATCH[watch_key] except KeyError: await error(websocket, "Game not found.") return # Register to receive moves from this game. connected.add(websocket) try: # Send previous moves, in case the game already started. await replay(websocket, game) # Keep the connection open, but don't receive any messages. await websocket.wait_closed() finally: connected.remove(websocket) async def handler(websocket): """ Handle a connection and dispatch it according to who is connecting. """ # Receive and parse the "init" event from the UI. message = await websocket.recv() event = json.loads(message) assert event["type"] == "init" if "join" in event: # Second player joins an existing game. await join(websocket, event["join"]) elif "watch" in event: # Spectator watches an existing game. await watch(websocket, event["watch"]) else: # First player starts a new game. await start(websocket) def health_check(connection, request): ``` -------------------------------- ### Serve WebSocket Connections with Complex Routing Source: https://github.com/python-websockets/websockets/blob/main/docs/topics/routing.md Use the `route()` function with a defined `url_map` to start a WebSocket server that handles connections based on complex routing rules. This example demonstrates serving indefinitely. ```python async def main(): async with route(url_map, "localhost", 8888) as server: await server.serve_forever() ``` -------------------------------- ### Start WebSocket Server with Python Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial1.md Execute this command to run your Python WebSocket application. Ensure your 'app.py' file contains the server logic. ```console $ python app.py ``` -------------------------------- ### Start WebSocket Server Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial2.md This snippet shows how to run the asyncio event loop to keep the WebSocket server running indefinitely. ```python await server.serve_forever() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/python-websockets/websockets/blob/main/docs/deploy/supervisor.md Sets up an isolated Python environment for project dependencies. Activate this environment before installing packages or running the application. ```bash python -m venv supervisor-websockets . supervisor-websockets/bin/activate ``` -------------------------------- ### Integrate Play Coroutine in Start Function (Python) Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial2.md Replace the temporary testing code in the 'start' function with a call to the 'play' coroutine to handle the game logic for the first player. ```python await play(websocket, game, PLAYER1, connected) ``` -------------------------------- ### Testing Websockets Connection via HAProxy Source: https://github.com/python-websockets/websockets/blob/main/docs/deploy/haproxy.md This command-line example demonstrates how to connect to the websockets server through HAProxy and send/receive messages. ```console $ websockets ws://localhost:8080/ Connected to ws://localhost:8080/. > Hello! < Hello! Connection closed: 1000 (OK). ``` -------------------------------- ### JavaScript Connect Four Client Setup Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial3.md Initializes the Connect Four game client. Sets up the WebSocket connection and event listeners for game interactions. ```javascript import { createBoard, playMove } from "./connect4.js"; function getWebSocketServer() { if (window.location.host === "python-websockets.github.io") { return "wss://websockets-tutorial.koyeb.app/"; } else if (window.location.host === "localhost:8000") { return "ws://localhost:8001/"; } else { throw new Error(`Unsupported host: ${window.location.host}`); } } function initGame(websocket) { websocket.addEventListener("open", () => { // Send an "init" event according to who is connecting. const params = new URLSearchParams(window.location.search); let event = { type: "init" }; if (params.has("join")) { // Second player joins an existing game. event.join = params.get("join"); } else if (params.has("watch")) { // Spectator watches an existing game. event.watch = params.get("watch"); } else { // First player starts a new game. } websocket.send(JSON.stringify(event)); }); } function showMessage(message) { window.setTimeout(() => window.alert(message), 50); } function receiveMoves(board, websocket) { websocket.addEventListener("message", ({ data }) => { const event = JSON.parse(data); switch (event.type) { case "init": // Create links for inviting the second player and spectators. document.querySelector(".join").href = "?join=" + event.join; document.querySelector(".watch").href = "?watch=" + event.watch; break; case "play": // Update the UI with the move. playMove(board, event.player, event.column, event.row); break; case "win": showMessage(`Player ${event.player} wins!`); // No further messages are expected; close the WebSocket connection. websocket.close(1000); break; case "error": showMessage(event.message); break; default: throw new Error(`Unsupported event type: ${event.type}.`); } }); } function sendMoves(board, websocket) { // Don't send moves for a spectator watching a game. const params = new URLSearchParams(window.location.search); if (params.has("watch")) { return; } // When clicking a column, send a "play" event for a move in that column. board.addEventListener("click", ({ target }) => { const column = target.dataset.column; // Ignore clicks outside a column. if (column === undefined) { return; } const event = { type: "play", column: parseInt(column, 10), }; websocket.send(JSON.stringify(event)); }); } window.addEventListener("DOMContentLoaded", () => { // Initialize the UI. const board = document.querySelector(".board"); createBoard(board); // Open the WebSocket connection and register event handlers. const websocket = new WebSocket(getWebSocketServer()); initGame(websocket); receiveMoves(board, websocket); sendMoves(board, websocket); }); ``` -------------------------------- ### Legacy HTTP Basic Auth Setup Source: https://github.com/python-websockets/websockets/blob/main/docs/howto/upgrade.md In older versions, HTTP Basic Authentication was configured by setting the `create_protocol` argument of `serve` to a factory function generated by `basic_auth_protocol_factory`. ```python from websockets.legacy.auth import basic_auth_protocol_factory from websockets.legacy.server import serve async with serve(..., create_protocol=basic_auth_protocol_factory(...)): ... ``` -------------------------------- ### Start New Game and Handle Connections Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial2.md Initializes a new Connect Four game, manages connected clients, generates a join key, and sends it to the first player. Includes temporary print statements for debugging. ```python import secrets JOIN = {} async def start(websocket): # Initialize a Connect Four game, the set of WebSocket connections # receiving moves from this game, and secret access token. game = Connect4() connected = {websocket} join_key = secrets.token_urlsafe(12) JOIN[join_key] = game, connected try: # Send the secret access token to the browser of the first player, # where it'll be used for building a "join" link. event = { "type": "init", "join": join_key, } await websocket.send(json.dumps(event)) # Temporary - for testing. print("first player started game", id(game)) async for message in websocket: print("first player sent", message) finally: del JOIN[join_key] ``` -------------------------------- ### Client Event for Game Initialization Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial2.md The first player sends an 'init' event to the server to signal the start of a new game. This event has no payload. ```javascript {type: "init"} ``` -------------------------------- ### Run WebSocket Authentication Experiment Source: https://github.com/python-websockets/websockets/blob/main/docs/topics/authentication.md Execute the Python application to test different WebSocket authentication techniques. This command starts a local HTTP server that facilitates the experiment. ```console $ python experiments/authentication/app.py Running on http://localhost:8000/ ``` -------------------------------- ### Procfile for Running Python App Source: https://github.com/python-websockets/websockets/blob/main/docs/deploy/fly.md Define the command to run your Python application using the Procfile. This specifies 'python app.py' to start the web server. ```text web: python app.py ``` -------------------------------- ### Handle Incoming WebSocket Connections Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial2.md Dispatches incoming WebSocket connections based on the initial 'init' event. It directs connections to 'join' for the second player, 'watch' for spectators, or 'start' for the first player. ```python async def handler(websocket): """ Handle a connection and dispatch it according to who is connecting. """ # Receive and parse the "init" event from the UI. message = await websocket.recv() event = json.loads(message) assert event["type"] == "init" if "join" in event: # Second player joins an existing game. await join(websocket, event["join"]) elif "watch" in event: # Spectator watches an existing game. await watch(websocket, event["watch"]) else: # First player starts a new game. await start(websocket) ``` -------------------------------- ### Get Data to Send Source: https://github.com/python-websockets/websockets/blob/main/docs/howto/sansio.md Retrieves data that needs to be sent over the network after calling a send method or fail(). This data should be sent before starting the next write operation. ```python data = await websocket.data_to_send() ``` -------------------------------- ### Asyncio WebSocket Echo Server Source: https://github.com/python-websockets/websockets/blob/main/README.rst An example of an echo server using the websockets library with Python's asyncio framework. It listens on localhost:8765 and echoes back any received messages. This requires the websockets library to be installed. ```python #!/usr/bin/env python import asyncio from websockets.asyncio.server import serve async def echo(websocket): async for message in websocket: await websocket.send(message) async def main(): async with serve(echo, "localhost", 8765) as server: await server.serve_forever() asyncio.run(main()) ``` -------------------------------- ### Initialize WebSocket Connection and Game Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial2.md Sets up the UI and establishes the WebSocket connection, then calls initGame to begin the initialization sequence. ```javascript window.addEventListener("DOMContentLoaded", () => { // Initialize the UI. const board = document.querySelector(".board"); createBoard(board); // Open the WebSocket connection and register event handlers. const websocket = new WebSocket("ws://localhost:8001/"); initGame(websocket); receiveMoves(board, websocket); sendMoves(board, websocket); }); ``` -------------------------------- ### Basic Synchronous Server Setup Source: https://github.com/python-websockets/websockets/blob/main/docs/reference/sync/server.md This snippet demonstrates the fundamental structure for creating a synchronous WebSocket server. It defines a handler function and uses a context manager to manage the server's lifecycle, ensuring proper startup and shutdown. ```python from websockets.sync.server import serve def handler(websocket): ... with serve(handler, ...) as server: server.serve_forever() ``` -------------------------------- ### Add and Commit Project Files Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial3.md Stage all project files and create an initial commit for your game. ```console $ git add . $ git commit -m "Initial implementation of Connect Four game." [main 7f0b2c4] Initial implementation of Connect Four game. 6 files changed, 500 insertions(+) create mode 100644 app.py create mode 100644 connect4.css create mode 100644 connect4.js create mode 100644 connect4.py create mode 100644 index.html create mode 100644 main.js ``` -------------------------------- ### Initialize Game with WebSocket Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial2.md Handles the WebSocket connection opening and sends an 'init' event based on URL parameters (join, watch, or new game). Requires 'createBoard' and 'playMove' from './connect4.js'. ```javascript import { createBoard, playMove } from "./connect4.js"; function initGame(websocket) { websocket.addEventListener("open", () => { // Send an "init" event according to who is connecting. const params = new URLSearchParams(window.location.search); let event = { type: "init" }; if (params.has("join")) { // Second player joins an existing game. event.join = params.get("join"); } else if (params.has("watch")) { // Spectator watches an existing game. event.watch = params.get("watch"); } else { // First player starts a new game. } websocket.send(JSON.stringify(event)); }); } ``` -------------------------------- ### Bootstrap WebSocket Server Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial1.md This is the main entry point for the WebSocket server. It sets up the server to listen on all interfaces and port 8001, and runs the connection handler. ```python #!/usr/bin/env python import asyncio from websockets.asyncio.server import serve async def handler(websocket): while True: message = await websocket.recv() print(message) async def main(): async with serve(handler, "", 8001) as server: await server.serve_forever() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Configure URL Map and Route Connections Source: https://github.com/python-websockets/websockets/blob/main/docs/reference/asyncio/server.md Set up a URL map with rules and use the `route` function to create a server that dispatches connections to handlers. The server can be configured with `server_name` and `ssl` options for reverse proxy scenarios. ```python from websockets.asyncio.router import route from werkzeug.routing import Map, Rule import asyncio async def channel_handler(websocket, channel_id): pass url_map = Map([ Rule("/channel/", endpoint=channel_handler), ... ]) # set this future to exit the server stop = asyncio.get_running_loop().create_future() async with route(url_map, ...) as server: await stop ``` -------------------------------- ### Initialize Git Repository Source: https://github.com/python-websockets/websockets/blob/main/docs/deploy/render.md Initializes a new git repository and creates an empty initial commit. This is a prerequisite for hosting the project on platforms like GitHub or GitLab. ```bash mkdir websockets-echo cd websockets-echo git init -b main Initialized empty Git repository in websockets-echo/.git/ git commit --allow-empty -m "Initial commit." [main (root-commit) 816c3b1] Initial commit. ``` -------------------------------- ### WebSocket Counter Server (Python) Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/examples.md A Python WebSocket server using `websockets` and `asyncio` to manage a shared counter. It handles client connections, state updates (increment/decrement), and broadcasts changes to all users. Ensure `websockets` is installed (`pip install websockets`). ```python #!/usr/bin/env python import asyncio import json import logging from websockets.asyncio.server import broadcast, serve logging.basicConfig() USERS = set() VALUE = 0 def users_event(): return json.dumps({"type": "users", "count": len(USERS)}) def value_event(): return json.dumps({"type": "value", "value": VALUE}) async def counter(websocket): global USERS, VALUE try: # Register user USERS.add(websocket) broadcast(USERS, users_event()) # Send current state to user await websocket.send(value_event()) # Manage state changes async for message in websocket: event = json.loads(message) if event["action"] == "minus": VALUE -= 1 broadcast(USERS, value_event()) elif event["action"] == "plus": VALUE += 1 broadcast(USERS, value_event()) else: logging.error("unsupported event: %s", event) finally: # Unregister user USERS.remove(websocket) broadcast(USERS, users_event()) async def main(): async with serve(counter, "localhost", 6789) as server: await server.serve_forever() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize Git Repository Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial3.md Initialize a new Git repository and set the main branch name. ```console $ git init -b main Initialized empty Git repository in websockets-tutorial/.git/ ``` ```console $ git commit --allow-empty -m "Initial commit." [main (root-commit) 8195c1d] Initial commit. ``` -------------------------------- ### Dockerfile for Websockets Application Source: https://github.com/python-websockets/websockets/blob/main/docs/deploy/kubernetes.md A minimal Dockerfile to containerize a Python websockets application. Installs websockets and copies the application code. ```dockerfile FROM python:3.13-alpine RUN pip install websockets COPY app.py . CMD ["python", "app.py"] ``` -------------------------------- ### Initialize Git Repository Source: https://github.com/python-websockets/websockets/blob/main/docs/deploy/koyeb.md Initializes a new Git repository and creates an empty commit. This is the first step before pushing to a remote repository like GitHub. ```console mkdir websockets-echo cd websockets-echo git init -b main Initialized empty Git repository in websockets-echo/.git/ git commit --allow-empty -m "Initial commit." [main (root-commit) 740f699] Initial commit. ``` -------------------------------- ### Select Subprotocol for Chat Source: https://github.com/python-websockets/websockets/blob/main/docs/reference/sansio/server.md Implement custom logic to select a subprotocol. This example prioritizes the 'chat' subprotocol if offered by the client. ```python def select_subprotocol(protocol, subprotocols): if "chat" in subprotocols: return "chat" ``` -------------------------------- ### Initialize Git Repository Source: https://github.com/python-websockets/websockets/blob/main/docs/deploy/heroku.md Initializes a new git repository and creates an empty initial commit. This is a prerequisite for deploying to Heroku. ```bash mkdir websockets-echo cd websockets-echo git init -b main Initialized empty Git repository in websockets-echo/.git/ git commit --allow-empty -m "Initial commit." [main (root-commit) 1e7947d] Initial commit. ``` -------------------------------- ### Get Websocket Latency Source: https://github.com/python-websockets/websockets/blob/main/docs/topics/keepalive.md Access the latency attribute to retrieve the measured latency during the last Ping and Pong frame exchange. ```python latency = websocket.latency ``` -------------------------------- ### Send WebSocket Binary Frame Source: https://github.com/python-websockets/websockets/blob/main/docs/reference/sansio/server.md Send a binary frame with arbitrary data. Set `fin=False` to indicate the start of a fragmented message. ```python server_protocol.send_binary(data, fin=True) ``` -------------------------------- ### Send Pong Frame Source: https://github.com/python-websockets/websockets/blob/main/docs/howto/sansio.md Sends a pong frame in response to a ping. Call data_to_send() afterwards to get data to send over the network. ```python await websocket.send_pong() ``` -------------------------------- ### Send Ping Frame Source: https://github.com/python-websockets/websockets/blob/main/docs/howto/sansio.md Sends a ping frame to the remote peer. Call data_to_send() afterwards to get data to send over the network. ```python await websocket.send_ping() ``` -------------------------------- ### Send WebSocket Text Frame Source: https://github.com/python-websockets/websockets/blob/main/docs/reference/sansio/server.md Send a text frame with UTF-8 encoded data. Set `fin=False` to indicate the start of a fragmented message. ```python server_protocol.send_text(data, fin=True) ``` -------------------------------- ### Configure logging for production Source: https://github.com/python-websockets/websockets/blob/main/docs/topics/logging.md Set up basic logging configuration for a server in a production environment. This sets the log level to INFO and specifies a simple format. ```python logging.basicConfig( format="%(asctime)s %(message)s", level=logging.INFO, ) ``` -------------------------------- ### Using basic_auth with serve Source: https://github.com/python-websockets/websockets/blob/main/docs/reference/sync/server.md This snippet demonstrates how to integrate basic_auth into the serve() function for HTTP Basic Authentication. It shows the required imports and the structure for setting a realm and hardcoded credentials. ```python from websockets.sync.server import basic_auth, serve with serve( ..., process_request=basic_auth( realm="my dev server", credentials=("hello", "iloveyou"), ), ): ``` -------------------------------- ### websockets.asyncio.server.unix_serve Source: https://github.com/python-websockets/websockets/blob/main/docs/reference/asyncio/server.md Create a WebSocket server listening on a Unix socket. This function is similar to `serve()` but uses a file system path for the socket instead of host and port, and is only available on Unix-like systems. ```APIDOC ## websockets.asyncio.server.unix_serve ### Description Create a WebSocket server listening on a Unix socket. This function is identical to [`serve()`](#websockets.asyncio.server.serve), except the `host` and `port` arguments are replaced by `path`. It’s only available on Unix. It’s useful for deploying a server behind a reverse proxy such as nginx. ### Parameters #### Path Parameters * **handler** (*Callable* *[* *[*[*ServerConnection*](#websockets.asyncio.server.ServerConnection) *]* *,* *Awaitable* *[**None* *]* *]*) – Connection handler. It receives the WebSocket connection, which is a [`ServerConnection`](#websockets.asyncio.server.ServerConnection), in argument. * **path** (*str* *|* *None*) – File system path to the Unix socket. ### Other Keyword Arguments: Any other keyword arguments are passed to the event loop’s `create_server()` method. For example: * You can set `ssl` to a `SSLContext` to enable TLS. * You can set `sock` to provide a preexisting TCP socket. You may call `socket.create_server()` (not to be confused with the event loop’s `create_server()` method) to create a suitable server socket and customize it. * You can set `start_serving` to `False` to start accepting connections only after you call [`start_serving()`](#websockets.asyncio.server.Server.start_serving) or [`serve_forever()`](#websockets.asyncio.server.Server.serve_forever). ### Request Example ```python await websockets.asyncio.server.unix_serve(handler, "/tmp/my.sock") ``` ### Response #### Success Response (200) This function returns a `Server` object. #### Response Example ```python server = await websockets.asyncio.server.unix_serve(handler, "/tmp/my.sock") ``` ``` -------------------------------- ### Asyncio WebSocket Client Source: https://github.com/python-websockets/websockets/blob/main/docs/index.md A client example using the asyncio API to connect to a WebSocket server, send a message, and print the received response. ```python #!/usr/bin/env python """Client using the asyncio API.""" import asyncio from websockets.asyncio.client import connect async def hello(): async with connect("ws://localhost:8765") as websocket: await websocket.send("Hello world!") message = await websocket.recv() print(message) if __name__ == "__main__": asyncio.run(hello()) ``` -------------------------------- ### Server Response for Game Initialization Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial2.md After initializing a new game, the server responds to the first player with an 'init' event that includes a 'join' key. This key is used to identify the game and is included in the URL for the second player. ```javascript {type: "init", join: ""} ``` -------------------------------- ### Asyncio WebSocket Echo Server Source: https://github.com/python-websockets/websockets/blob/main/docs/index.md An example of an echo server using the asyncio API. It listens for incoming messages and sends them back to the client. ```python #!/usr/bin/env python """Echo server using the asyncio API.""" import asyncio from websockets.asyncio.server import serve async def echo(websocket): async for message in websocket: await websocket.send(message) async def main(): async with serve(echo, "localhost", 8765) as server: await server.serve_forever() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize WebSocket Connection and Event Handlers in JavaScript Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial1.md Sets up the WebSocket connection and registers event listeners for receiving and sending moves when the DOM is loaded. Ensure the WebSocket server is running before initializing. ```javascript window.addEventListener("DOMContentLoaded", () => { // Initialize the UI. const board = document.querySelector(".board"); createBoard(board); // Open the WebSocket connection and register event handlers. const websocket = new WebSocket("ws://localhost:8001/"); receiveMoves(board, websocket); sendMoves(board, websocket); }); ``` -------------------------------- ### New HTTP Basic Auth Setup Source: https://github.com/python-websockets/websockets/blob/main/docs/howto/upgrade.md The new implementation uses the `basic_auth` function to generate a `process_request` coroutine for HTTP Basic Authentication. ```python from websockets.asyncio.server import basic_auth, serve async with serve(..., process_request=basic_auth(...)): ... ``` -------------------------------- ### Initialize and Store New Game Source: https://github.com/python-websockets/websockets/blob/main/docs/intro/tutorial2.md When the first player starts a game, initialize the game instance, the set of connected WebSockets, and generate a unique join key. Store this information in the global JOIN dictionary. Ensure cleanup by deleting the entry from JOIN in a finally block. ```python import secrets async def handler(websocket): ... # Initialize a Connect Four game, the set of WebSocket connections # receiving moves from this game, and secret access token. game = Connect4() connected = {websocket} join_key = secrets.token_urlsafe(12) JOIN[join_key] = game, connected try: ... finally: del JOIN[join_key] ``` -------------------------------- ### Send Close Frame Source: https://github.com/python-websockets/websockets/blob/main/docs/howto/sansio.md Initiates the WebSocket closing handshake by sending a close frame. Call data_to_send() afterwards to get data to send over the network. ```python await websocket.send_close() ``` -------------------------------- ### Add and Commit Application Files Source: https://github.com/python-websockets/websockets/blob/main/docs/deploy/render.md Stages all new and modified files in the current directory and commits them with a descriptive message. This prepares the application code for pushing to a remote repository. ```bash ls app.py requirements.txt git add . git commit -m "Initial implementation." [main f26bf7f] Initial implementation. 2 files changed, 37 insertions(+) create mode 100644 app.py create mode 100644 requirements.txt ``` -------------------------------- ### Declare Websockets Dependency Source: https://github.com/python-websockets/websockets/blob/main/docs/deploy/render.md Specifies the 'websockets' library as a dependency for the Python project. This file is used by package managers like pip to install necessary libraries. ```text websockets ```