Receiving Data from WebSockets in Python

Feb 1, 2024 ยท 2 min read

WebSockets provide bidirectional communication between a client and server, allowing for real-time data transfer. In Python, we can use the websocket library to receive data from a WebSocket.

To start, we need to establish a WebSocket connection. We'll use the websocket.WebSocketApp class:

import websocket

ws = websocket.WebSocketApp("ws://")

Next, we need to define a callback function to handle messages received from the server. This function will be called when the client receives data:

def on_message(ws, message):

ws.on_message = on_message

Inside the callback, message contains the data sent by the server. We can process it however we want - print it out, analyze it, save it to a database, etc.

To start receiving messages, we run the WebSocketApp:


This method blocks execution and waits for data from the WebSocket. When messages come in, it will call our on_message callback.

Some tips:

  • Set a on_error callback to handle any errors that occur.
  • Send messages to the server using ws.send().
  • Close the connection with ws.close().
  • Use a thread or asynchronous library like asyncio so run_forever() doesn't block.
  • To implement backpressure, you can set a gettimeout() value. This will cause run_forever to regularly return control to your app even if no messages were received.

    So in just a few lines of code, we can receive real-time data over a WebSocket in Python! The websocket library abstracts away the protocol details, making it easy to focus on the messaging logic.

    Browse by language:

    Tired of getting blocked while scraping the web?

    ProxiesAPI handles headless browsers and rotates proxies for you.
    Get access to 1,000 free API credits, no credit card required!