杰瑞科技汇

Python 2.7 WebSocket 如何实现与兼容?

Of course. Working with WebSockets in Python 2.7 is possible, but it's important to understand the context and the recommended approach.

Python 2.7 WebSocket 如何实现与兼容?-图1
(图片来源网络,侵删)

Key Consideration: Python 2.7 is End-of-Life (EOL)

First and foremost, Python 2.7 reached its official end-of-life on January 1, 2025. This means it no longer receives security updates, bug fixes, or improvements. Any new project should strongly consider using a modern version of Python (3.6+) where WebSocket support is more robust and standardized.

However, if you are maintaining a legacy system that must run on Python 2.7, here is how to work with WebSockets.


Choosing a Library

For Python 2.7, your main options are:

  1. websocket-client: The most popular and straightforward library for creating a WebSocket client. It's easy to use and well-documented.
  2. websockets (by liris): A more powerful library that can act as both a client and a server. It's more feature-rich but has a slightly more complex API.
  3. Django Channels: If you are using the Django framework, Django Channels is the de-facto solution for adding WebSocket support to your Django project. It's a full-featured package.

For this guide, we'll focus on the most common use case: creating a client with websocket-client.

Python 2.7 WebSocket 如何实现与兼容?-图2
(图片来源网络,侵删)

Installation

You'll need to install the chosen library using pip. It's highly recommended to use pip2 to be explicit about the Python 2.7 environment.

# For the client library
pip2 install websocket-client
# If you need a server/client library
pip2 install websockets

Example 1: WebSocket Client with websocket-client

This is the simplest way to connect to a WebSocket server, send messages, and receive responses.

Let's create a simple script that connects to a public echo server (a server that sends back any message it receives).

File: simple_client.py

Python 2.7 WebSocket 如何实现与兼容?-图3
(图片来源网络,侵删)
# -*- coding: utf-8 -*-
import websocket
import thread
import time
# This function will run in a separate thread to listen for messages
def on_message(ws, message):
    print("### Received Message ### : " + message)
def on_error(ws, error):
    print("### Error ### : " + error)
def on_close(ws):
    print("### Connection Closed ###")
def on_open(ws):
    print("### Connection Opened ###")
    # Send an initial message once the connection is established
    ws.send("Hello from Python 2.7 Client!")
    # You can send more messages here
    # ws.send("This is a second message.")
if __name__ == "__main__":
    # URL of the WebSocket server (a public echo server in this case)
    websocket.enableTrace(True) # Enable verbose logging (optional)
    ws = websocket.WebSocketApp("wss://ws.postman-echo.com/raw",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    # The run_forever() method blocks and starts the event loop.
    # It handles the connection, sends messages, and calls the callback functions.
    ws.run_forever()

How to Run It:

  1. Save the code as simple_client.py.
  2. Open your terminal or command prompt.
  3. Run the script: python2 simple_client.py

Expected Output:

You will see the verbose trace (if enableTrace is true) and then the connection messages.

--- request header ---
GET /raw HTTP/1.1
...
Host: ws.postman-echo.com
Upgrade: websocket
Connection: Upgrade
...
--- response header ---
HTTP/1.1 101 Web Socket Protocol Handshake
...
Connection: Upgrade
...
### Connection Opened ###
### Received Message ### : Hello from Python 2.7 Client!
### Connection Closed ###

The server echoes back the message we sent, and the on_message callback prints it.


Example 2: Simple WebSocket Server with websockets library

If you need to create your own WebSocket server in Python 2.7, the websockets library is a good choice. It uses asyncio-like patterns, which were introduced in Python 3.4 but backported for Python 2.7.

File: simple_server.py

# -*- coding: utf-8 -*-
import websockets
import asyncio
# This is the core function that handles a single client connection.
# It runs every time a new client connects.
async def handle_connection(websocket, path):
    print("A new client connected!")
    print("Client address:", websocket.remote_address)
    print("Path:", path)
    try:
        # The server will loop forever, waiting for messages from this client.
        async for message in websocket:
            print(f"Received message from {websocket.remote_address}: {message}")
            # Echo the message back to the client
            await websocket.send("Server says: " + message)
    except websockets.exceptions.ConnectionClosed as e:
        print(f"Client {websocket.remote_address} disconnected: {e.code} {e.reason}")
# Start the WebSocket server
# 'localhost' means it only accepts connections from the same machine.
# Use '0.0.0.0' to make it accessible from other machines on the network.
# Port 8765 is used.
start_server = websockets.serve(handle_connection, "localhost", 8765)
# The event loop runs forever, keeping the server alive.
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

How to Run It:

  1. Save the code as simple_server.py.
  2. Open a terminal and run: python2 simple_server.py
  3. The server will now be running, waiting for connections. It won't print anything until a client connects.

Connecting to Your Python 2.7 Server

You can test your server using the client script from Example 1, but you need to change the URL.

Modify simple_client.py:

# ... (rest of the imports and functions are the same)
if __name__ == "__main__":
    websocket.enableTrace(False) # Disable verbose log for clarity
    ws = websocket.WebSocketApp("ws://localhost:8765", # Changed URL to our server
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

Now, run the server in one terminal: python2 simple_server.py

And run the client in a second terminal: python2 simple_client.py

Expected Output (in the server terminal):

A new client connected!
Client address: ('127.0.0.1', 54321) # Port will vary
Path: /
Received message from ('127.0.0.1', 54321): Hello from Python 2.7 Client!

Expected Output (in the client terminal):

### Connection Opened ###
### Received Message ### : Server says: Hello from Python 2.7 Client!
### Connection Closed ###

Summary and Final Recommendation

Task Recommended Library for Python 2.7 Key Feature
Client websocket-client Very simple, easy-to-use API.
Server / Client websockets More powerful, supports async patterns.
Django Project Django Channels Integrates WebSockets seamlessly into Django.

While these libraries will work for Python 2.7, please prioritize migrating your project to a supported version of Python 3. Modern Python has a built-in websockets library in the standard library (since Python 3.7), and the ecosystem is far more active and secure.

分享:
扫描分享到社交APP
上一篇
下一篇