You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python返回正确HTTP响应?WebSocket通信问题咨询

问题分析与解决方案

Hey there! Let's break down what's going wrong here and how to fix it—you're mixing two different communication protocols, which is why your setup isn't working as expected.

核心问题:WebSocket vs 普通TCP Socket

Your JavaScript code uses WebSocket, which isn't just a plain TCP connection—it's a protocol that starts with an HTTP handshake, then switches to a binary frame-based format for messages. Your Python code, though, is a basic TCP server that's trying to handle HTTP-like responses, but it doesn't understand the WebSocket handshake process or message framing. That's why you're seeing weird data on the server instead of your "Hello, world!" message.

Let's fix this step by step.


第一步:修正JavaScript的URL错误

First, your WebSocket URL has a small syntax mistake—you're missing the double slashes after ws:. It should be:

function getData(){ 
    var socket = new WebSocket("ws://your-server-ip:6474"); 
    socket.onopen = () => socket.send("Hello, world!");
    // Add error handling to debug issues
    socket.onerror = (error) => console.error("WebSocket error:", error);
    socket.onmessage = (event) => console.log("Received from server:", event.data);
}

Adding error and message handlers will help you debug connection issues in the browser console.


第二步:用Python WebSocket库实现兼容的服务器

For a beginner, the easiest way to make this work is to use a dedicated WebSocket library for Python instead of raw sockets. The websockets library is perfect for this—it handles all the handshake and framing logic for you.

1. Install the library

First, install it via pip:

pip install websockets

2. Write the WebSocket server code

Replace your existing Python code with this:

import asyncio
import websockets

async def handle_client(websocket):
    # Receive message from client
    message = await websocket.recv()
    print(f"Received: {message}")
    
    # Send a response back (optional)
    await websocket.send("Hi from the Python server!")

async def main():
    async with websockets.serve(handle_client, "0.0.0.0", 6474):
        await asyncio.Future()  # Run forever

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

3. How this works

  • The websockets.serve function sets up a WebSocket server that automatically handles the HTTP handshake.
  • When a client connects, the handle_client coroutine runs—it waits for messages from the client, prints them, and can send responses back.
  • This matches exactly what your JavaScript client is expecting.

如果非要用原生Socket(不推荐新手)

If you want to learn how the WebSocket protocol works under the hood, you'd need to:

  1. Parse the client's HTTP upgrade request to extract the Sec-WebSocket-Key header.
  2. Compute the Sec-WebSocket-Accept value using that key (with a fixed UUID and SHA-1 hashing).
  3. Send a valid HTTP 101 Switching Protocols response back to complete the handshake.
  4. Decode/encode WebSocket frames (since messages are sent in framed format, not plain text).

This is pretty complex for a beginner, so using the websockets library is the smarter path to get your setup working quickly.


测试你的 setup

  1. Run the Python server.
  2. Open your index.html in a browser, click the button to trigger getData().
  3. You should see "Received: Hello, world!" in the Python console, and "Hi from the Python server!" in your browser's developer console.

内容的提问来源于stack exchange,提问作者user12315589

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 10:52:57