How To Use Python To Create WebSocket Server & Client Example

This article will tell you how to use Python to develop a WebSocket server and client applications with examples. It will use the python websockets module and asyncio module.

1. Install The Python websockets Module.

  1. Open a terminal and run the command pip show websockets to see whether the Python websockets module has been installed or not.
    (MyPythonEnv) C:\Users\zhaosong>pip show websockets 
    WARNING: Package(s) not found: websockets
  2. If it shows can not find the websockets module, then you can install it with the command pip install websockets.
    (MyPythonEnv) C:\Users\zhaosong>pip install websockets
    Collecting websockets
      Downloading websockets-10.3-cp38-cp38-win_amd64.whl (98 kB)
         |████████████████████████████████| 98 kB 1.3 MB/s
    Installing collected packages: websockets
    Successfully installed websockets-10.3
  3. Run the command pip show websockets again to verify that the websockets module has been installed successfully.
    (MyPythonEnv) C:\Users\zhaosong>pip show websockets
    Name: websockets
    Version: 10.3
    Summary: An implementation of the WebSocket Protocol (RFC 6455 & 7692)
    Home-page: https://github.com/aaugustin/websockets
    Author: Aymeric Augustin
    Author-email: aymeric.augustin@m4x.org
    License: BSD
    Location: c:\users\zhaosong\anaconda3\envs\mypythonenv\lib\site-packages
    Requires:
    Required-by:

2. Python Client & Server WebSockets Example.

2.1 Create WebSockets Server.

  1. Before you can use the Python websockets module you should first import it.
    import websockets
  2. Define an async function as the handler that will handle the client websocket request. In this function, you can receive client request data using the websocket.recv() method and then sent data back to the client on the server-side using the websocket.send(response_data) method. In this example, the function is async def websocket_request_handler(websocket, path).
    async def websocket_request_handler(websocket, path):
     
        # receive the client websocket send data.
        client_data = await websocket.recv()
     
        # construct the response data.
        response_data = "Below is the data recieved from client:\n" + client_data
     
        await websocket.send(response_data)
  3. Call the websockets.serve(websocket_request_handler, host, port_number) method to start the WebSocket server and make it listen to the client websocket request.
    # create and start the websocket server listen on the provided host and port number.
    def start_websocket_server(host, port_number):
    
        # create the websocket server with the provided handler, host, and port_number.
        websocket_server = websockets.serve(websocket_request_handler, host, port_number)
     
        print('websocket server is running and listening on port number : ' + str(port_number))
    
        # run the websocket server asynchronouslly.
        asyncio.get_event_loop().run_until_complete(websocket_server)
        asyncio.get_event_loop().run_forever()
  4. In this example, the websocket server is implemented in the file WebSocketsServer.py, below is the file source code.
    import websockets
    import asyncio
    import time
    
    # create handler for each connection
    # when there is a connection to the websocket server, the handler function will be invoked.
    # You can receive data from the client websocket and send data back to the client in this function. 
    async def websocket_request_handler(websocket, path):
     
        # receive the client websocket send data.
        client_data = await websocket.recv()
    
        print(time.ctime() + '\n' + client_data + '\n\r')
     
        # construct the response data.
        response_data = "Below is the data recieved from client:\n" + client_data
     
        # send the data back to the client websocket.
        await websocket.send(response_data)
     
    
    # create and start the websocket server listen on the provided host and port number.
    def start_websocket_server(host, port_number):
    
        # create the websocket server with the provided handler, host, and port_number.
        websocket_server = websockets.serve(websocket_request_handler, host, port_number)
     
        print('websocket server is running and listening on port number : ' + str(port_number))
    
        # run the websocket server asynchronouslly.
        asyncio.get_event_loop().run_until_complete(websocket_server)
        asyncio.get_event_loop().run_forever()
    
    
    if __name__ == '__main__':
    
        host = "localhost"
    
        port_number = 9999
    
        start_websocket_server(host, port_number) 
    
  5. When you run the above python file with the command python .\WebSocketsServer.py, you will get the output like below. The text is the data sent from the client WebSocket, you will know it later.
    > python .\WebSocketsServer.py
    websocket server is running and listening on port number : 9999
    Fri May  6 18:51:59 2022
    hello
    how are you?
    I love python

2.2 Create WebSockets Client.

  1. The example client websockets file name is WebSocketsClient.py, you can run it with the command python .\WebSocketsClient.py.
    > python .\WebSocketsClient.py
    Please input the text send to the websocket server, type send to finish.
    
    >hello
    >how are you?
    >I love python
    >send
    Below is the data recieved from client:
    hello
    how are you?
    I love python
  2. Below is the WebSocketsClient.py source code.
    import asyncio
    import websockets
     
    # define the async function that send the text to the websocket server. 
    async def ping_websocket_server(send_text):
        
        # define the websocket server access URL.
        websocket_server_url = 'ws://localhost:9999/'
        
        # connect to the websocket server.
        async with websockets.connect(websocket_server_url) as websocket:
    
            # send the text to the websocket server and wait for the reply.
            await websocket.send(send_text)
    
            # get the websocket server return text.
            server_resp = await websocket.recv()
    
            # print out the server response text.
            print(server_resp)
    
    
    # this function will send the text to the websocket server by invoking the ping_websocket_server(send_text) function.  
    def create_websocket_client(send_text):
    
        # call the asyncio function to invoke the ping_websocket_server(send_text) function.
        asyncio.get_event_loop().run_until_complete(ping_websocket_server(send_text))
    
    
    
    if __name__ == '__main__':
    
        print('Please input the text send to the websocket server, type send to finish.\n\r')
    
        send_data_all = ''
        
        # loop to get the user input text to send.
        while True:
    
            input_data = input('>')
    
            # when user type 'send' then break the loop.
            if input_data.lower() == 'send':
    
                break
    
            send_data_all += input_data + '\n'
    
        
        create_websocket_client(send_data_all)

1 thought on “How To Use Python To Create WebSocket Server & Client Example”

  1. I am not sure how to use all this. I have a RPi that hosts my website.
    I want to add a page that displays data as it updates. In the simplest case, a python program is running waiting for the user to type a line. After the “Enter” I want the text line to appear on the webpage.
    Do I run the six programs in separate terminal windows simultaneously?
    Forgive me but I’m lost.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.