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

Node.js WebSocket服务无法与Python通信,求完整解决方案

WebSocket跨语言通信代码方案(Node.js/PHP/Python)

Node.js WebSocket 服务代码

解决请求头和跨域问题,同时打印请求头方便排查:

const WebSocket = require('ws');
const http = require('http');

// 创建HTTP服务器预处理请求,解决跨域OPTIONS预检
const server = http.createServer((req, res) => {
  if (req.method === 'OPTIONS') {
    res.writeHead(200, {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': '*'
    });
    res.end();
    return;
  }
});

// 初始化WebSocket服务,绑定到HTTP服务器
const wss = new WebSocket.Server({ server });

wss.on('connection', (ws, req) => {
  console.log('新客户端接入');
  // 打印完整请求头,用于排查握手问题
  console.log('握手请求头:', req.headers);

  // 接收并广播消息
  ws.on('message', (data) => {
    console.log(`收到消息: ${data}`);
    wss.clients.forEach(client => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(data);
      }
    });
  });

  ws.on('close', () => console.log('客户端断开'));
  ws.on('error', err => console.error('连接错误:', err));
});

const PORT = 8080;
server.listen(PORT, () => {
  console.log(`WebSocket服务运行在 ws://localhost:${PORT}`);
});

PHP 前端消息展示页面

直接嵌入原生WebSocket的PHP页面,实时展示收到的消息:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>WebSocket实时消息</title>
    <style>
        #msg-container {
            height: 350px;
            overflow-y: auto;
            border: 1px solid #eee;
            padding: 15px;
            margin: 20px 0;
        }
        .msg-item {
            padding: 8px 12px;
            margin: 6px 0;
            background: #f8f9fa;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <h2>WebSocket消息接收展示</h2>
    <div id="msg-container"></div>

    <script>
        const ws = new WebSocket('ws://localhost:8080');
        const msgContainer = document.getElementById('msg-container');

        ws.onopen = () => console.log('前端已连接WebSocket服务');

        ws.onmessage = e => {
            const msgEl = document.createElement('div');
            msgEl.className = 'msg-item';
            msgEl.textContent = `[${new Date().toLocaleString()}] ${e.data}`;
            msgContainer.appendChild(msgEl);
            msgContainer.scrollTop = msgContainer.scrollHeight;
        };

        ws.onerror = err => console.error('WebSocket错误:', err);
        ws.onclose = () => console.log('WebSocket连接关闭');
    </script>
</body>
</html>

Python 消息发送脚本

设置匹配服务端的请求头,确保握手成功:

import websocket

# 替换为你的WebSocket服务地址
WS_SERVER = "ws://localhost:8080"

def send_ws_message():
    try:
        # 建立连接时设置Origin头,匹配服务端CORS配置
        ws = websocket.create_connection(
            WS_SERVER,
            header={
                "Origin": "http://localhost",
                "User-Agent": "Python WebSocket Client"
            }
        )
        print("已连接到WebSocket服务")

        # 发送测试消息
        test_msg = "Python脚本发送的WebSocket消息"
        ws.send(test_msg)
        print(f"消息已发送: {test_msg}")

        # 可选:接收服务端广播的消息
        # recv_msg = ws.recv()
        # print(f"收到服务端响应: {recv_msg}")

        ws.close()
        print("连接已关闭")
    except Exception as e:
        print(f"发送失败: {str(e)}")

if __name__ == "__main__":
    send_ws_message()

使用说明

  1. Node.js服务:先安装ws依赖(npm install ws),运行脚本启动服务。
  2. Python脚本:先安装websocket-client依赖(pip install websocket-client),运行脚本发送消息。
  3. PHP页面:直接在浏览器打开,即可实时查看WebSocket消息。

内容的提问来源于stack exchange,提问作者Lucas Silva Dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 03:25:04