如何用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.servefunction sets up a WebSocket server that automatically handles the HTTP handshake. - When a client connects, the
handle_clientcoroutine 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:
- Parse the client's HTTP upgrade request to extract the
Sec-WebSocket-Keyheader. - Compute the
Sec-WebSocket-Acceptvalue using that key (with a fixed UUID and SHA-1 hashing). - Send a valid HTTP 101 Switching Protocols response back to complete the handshake.
- 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
- Run the Python server.
- Open your index.html in a browser, click the button to trigger
getData(). - 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

