Websocket Communication

WebSocket is a protocol for machine-to-machine communication that keeps a TCP connection open for bi-directional passing of information. The websocket is a connection between two computers. The connection can be used to either send or receive information from either computer. The websocket can be configured as a server or client. A websocket server listens for requests and returns a result based on the input. The server can also function as a client by sending information without a specific request.

Install websockets

The websockets package is a Python library for building WebSocket servers and clients.

pip install websockets

There are other programming languages where websocket server and client are written such as JavaScript and PHP. Websocket communication occurs over TCP so that various programming languages can seamlessly communicate. For example, a Python client can call an API running on a server with JavaScript node.js.

Websocket Server

The Python websockets package is build on top of asyncio for asynchronous actions from the server as it listens for client requests. Create a simple WebSocket server and run the Python script to start the API. The API listens for a name and returns a greeting.

import asyncio
import websockets

async def hello(websocket):
    name = await websocket.recv()
    print(f'Server Received: {name}')
    greeting = f'Hello {name}!'

    await websocket.send(greeting)
    print(f'Server Sent: {greeting}')

async def main():
    async with websockets.serve(hello, "localhost", 8765):
        await asyncio.Future()  # run forever

if __name__ == "__main__":
    asyncio.run(main())

Websocket Client

The websockets client sends a name and listens for a return response.

import asyncio
import websockets

async def hello():
    uri = "ws://localhost:8765"
    async with websockets.connect(uri) as websocket:
        name = input("What's your name? ")

        await websocket.send(name)
        print(f'Client sent: {name}')

        greeting = await websocket.recv()
        print(f"Client received: {greeting}")

if __name__ == "__main__":
    asyncio.run(hello())

✅ Activity

Create a buzzer beater program that awaits a spacebar press response from one or more users. Record the time that each of the users responds, display the response time of the user, and notify the first user that they were the fastest response.

  • Websocket server: Set up a websocket server using the websockets library, and define a function that handles incoming messages from clients. This function should check if the incoming message is a valid response action, and if it is, it should record the time at which the response was sent and send a response back to the client indicating whether they were the first to press the spacebar.
  • Websocket client: Set up a websocket client that connects to the server and sends a message when the user presses the spacebar on their keyboard. The client should also display a message indicating whether they were the first to press the button or how long after the first-place response.

✅ Knowledge Check

1. Which statement about WebSockets is true?

A. WebSockets are used exclusively for sending data from server to client.
B. WebSockets maintain a continuous open connection for bi-directional communication.
C. WebSockets can only communicate with servers and clients written in the same programming language.
D. Every time a client wants to send data via WebSockets, a new connection is established.

2. How does a WebSocket differ from traditional HTTP requests?

A. WebSockets are slower than HTTP because they keep the connection open.
B. WebSockets are used for downloading large files, while HTTP requests are not.
C. WebSockets support bi-directional communication, whereas traditional HTTP is mainly unidirectional.
D. WebSocket communications are not encrypted, while HTTP communications are always encrypted.
Streaming Chatbot
💬