Home Backend Development Python Tutorial Using WebSocket with Python

Using WebSocket with Python

Oct 11, 2024 pm 08:16 PM

Using WebSocket with Python

What is WebSocket?

WebSocket is a protocol that enables real-time, bidirectional communication between a browser and a server. Traditional HTTP communication involves the client sending a request and the server responding to exchange data. In contrast, with WebSocket, once the initial connection is established, both the client and the server can send and receive messages to each other without needing to repeatedly establish new connections.

Recently, interactive services like the OpenAI Realtime API and Hume AI have become more common, leading to an anticipated increase in demand for WebSocket. This article introduces the basics of how to use WebSocket, along with a look into related asynchronous processing.

Using WebSocket with Python

In Python, you can use WebSocket as shown below:

import asyncio
import websockets

uri = "ws://..."

async def hello():
    async with websockets.connect(uri) as websocket:
        await websocket.send("Hello, Server!")
        response = await websocket.recv()
        print(f"Server says: {response}")

asyncio.run(hello())
  1. Connect to the WebSocket server using websockets.connect(uri).
  2. Send a message with websocket.send(message).
  3. Receive a message using websocket.recv().

Asynchronous Processing

The async and await used in the previous code represent asynchronous processing. Asynchronous processing is especially effective when executing multiple tasks simultaneously.

import asyncio

async def task1():
    print("Task 1: Start")
    await asyncio.sleep(2)  # Wait for 2 seconds
    print("Task 1: End")

async def task2():
    print("Task 2: Start")
    await asyncio.sleep(1)  # Wait for 1 second
    print("Task 2: End")

async def main():
    await asyncio.gather(task1(), task2())

asyncio.run(main())

In functions that use await, other tasks can run while waiting for the completion of the current task. This allows for efficient switching between tasks.

Asynchronous Processing and Multithreading

Multithreading also handles multiple tasks, but there is a difference in how threads are utilized:

  • In multithreading, each task has its own thread, and the program switches between tasks while waiting for certain processes to complete.
  • Asynchronous processing, on the other hand, does not create new threads but switches between tasks.

Multithreading is effective when working with CPU-intensive or blocking operations. However, it has drawbacks such as overhead from thread switching (context switching) and increased memory consumption.

In contrast, asynchronous processing reduces the overhead from context switching because it doesn’t rely on threads. However, if a heavy task is running, other tasks may have to wait. As such, it is suitable for IO-bound operations like API requests.

(For tasks that are computationally intensive or require precise timing, multiprocessing is often more effective. Unlike multithreading, multiprocessing allows multiple tasks to run simultaneously.)

For example, when using the OpenAI Realtime API to receive audio from a microphone in real-time and send the audio data to the API, you can use a combination of multithreading and asynchronous processing:

import asyncio
import threading
import queue
import pyaudio
import websockets

# Use a queue to share data between threads
audio_queue = queue.Queue()

# Thread to capture audio using PyAudio
def audio_stream():
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paInt16,
                    channels=1,
                    rate=44100,
                    input=True,
                    frames_per_buffer=1024)

    print("Start recording...")
    while True:
        data = stream.read(1024)
        audio_queue.put(data)

# Asynchronous function to send audio data via WebSocket
async def send_audio():
    uri = "ws://localhost:8765"
    async with websockets.connect(uri) as websocket:
        while True:
            # Get audio data from the queue
            data = audio_queue.get()
            if data is None:
                break
            await websocket.send(data)
            print("Sent audio data")

# Start the audio capture thread and run the asynchronous task
def main():
    audio_thread = threading.Thread(target=audio_stream)
    audio_thread.start()

    # Run the WebSocket sending task
    asyncio.run(send_audio())

if __name__ == "__main__":
    main()

The audio capture process is a blocking operation, so it is executed in a separate thread using threading. In contrast, sending the audio data, which involves IO-bound operations like interacting with an API, is done using asynchronous processing. (Note: PyAudio can also be run non-blocking using callbacks. )

Conclusion

In this article, we introduced WebSocket and asynchronous processing.

I found these concepts particularly confusing while working with the OpenAI Realtime API, so I put this together as a personal note. If you find any errors or have any feedback, I would appreciate your input.

Thank you for reading until the end.

The above is the detailed content of Using WebSocket with Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1596
276
python connect to sql server pyodbc example python connect to sql server pyodbc example Jul 30, 2025 am 02:53 AM

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

SQLAlchemy 2.0 Deprecation Warning and Connection Close Problem Resolving Guide SQLAlchemy 2.0 Deprecation Warning and Connection Close Problem Resolving Guide Aug 05, 2025 pm 07:57 PM

This article aims to help SQLAlchemy beginners resolve the "RemovedIn20Warning" warning encountered when using create_engine and the subsequent "ResourceClosedError" connection closing error. The article will explain the cause of this warning in detail and provide specific steps and code examples to eliminate the warning and fix connection issues to ensure that you can query and operate the database smoothly.

python shutil rmtree example python shutil rmtree example Aug 01, 2025 am 05:47 AM

shutil.rmtree() is a function in Python that recursively deletes the entire directory tree. It can delete specified folders and all contents. 1. Basic usage: Use shutil.rmtree(path) to delete the directory, and you need to handle FileNotFoundError, PermissionError and other exceptions. 2. Practical application: You can clear folders containing subdirectories and files in one click, such as temporary data or cached directories. 3. Notes: The deletion operation is not restored; FileNotFoundError is thrown when the path does not exist; it may fail due to permissions or file occupation. 4. Optional parameters: Errors can be ignored by ignore_errors=True

Python for Data Engineering ETL Python for Data Engineering ETL Aug 02, 2025 am 08:48 AM

Python is an efficient tool to implement ETL processes. 1. Data extraction: Data can be extracted from databases, APIs, files and other sources through pandas, sqlalchemy, requests and other libraries; 2. Data conversion: Use pandas for cleaning, type conversion, association, aggregation and other operations to ensure data quality and optimize performance; 3. Data loading: Use pandas' to_sql method or cloud platform SDK to write data to the target system, pay attention to writing methods and batch processing; 4. Tool recommendations: Airflow, Dagster, Prefect are used for process scheduling and management, combining log alarms and virtual environments to improve stability and maintainability.

How to automate data entry from Excel to a web form with Python? How to automate data entry from Excel to a web form with Python? Aug 12, 2025 am 02:39 AM

The method of filling Excel data into web forms using Python is: first use pandas to read Excel data, and then use Selenium to control the browser to automatically fill and submit the form; the specific steps include installing pandas, openpyxl and Selenium libraries, downloading the corresponding browser driver, using pandas to read Name, Email, Phone and other fields in the data.xlsx file, launching the browser through Selenium to open the target web page, locate the form elements and fill in the data line by line, using WebDriverWait to process dynamic loading content, add exception processing and delay to ensure stability, and finally submit the form and process all data lines in a loop.

How to execute SQL queries in Python? How to execute SQL queries in Python? Aug 02, 2025 am 01:56 AM

Install the corresponding database driver; 2. Use connect() to connect to the database; 3. Create a cursor object; 4. Use execute() or executemany() to execute SQL and use parameterized query to prevent injection; 5. Use fetchall(), etc. to obtain results; 6. Commit() is required after modification; 7. Finally, close the connection or use a context manager to automatically handle it; the complete process ensures that SQL operations are safe and efficient.

python pandas styling dataframe example python pandas styling dataframe example Aug 04, 2025 pm 01:43 PM

Using PandasStyling in JupyterNotebook can achieve the beautiful display of DataFrame. 1. Use highlight_max and highlight_min to highlight the maximum value (green) and minimum value (red) of each column; 2. Add gradient background color (such as Blues or Reds) to the numeric column through background_gradient to visually display the data size; 3. Custom function color_score combined with applymap to set text colors for different fractional intervals (≥90 green, 80~89 orange, 60~79 red,

How to create a virtual environment in Python How to create a virtual environment in Python Aug 05, 2025 pm 01:05 PM

To create a Python virtual environment, you can use the venv module. The steps are: 1. Enter the project directory to execute the python-mvenvenv environment to create the environment; 2. Use sourceenv/bin/activate to Mac/Linux and env\Scripts\activate to Windows; 3. Use the pipinstall installation package, pipfreeze>requirements.txt to export dependencies; 4. Be careful to avoid submitting the virtual environment to Git, and confirm that it is in the correct environment during installation. Virtual environments can isolate project dependencies to prevent conflicts, especially suitable for multi-project development, and editors such as PyCharm or VSCode are also

See all articles