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

Flask-SocketIO无法接收消息求助(SocketIO 1.3.6、Python3.6)

Let's break down the issues and fixes for your Flask-SocketIO setup where messages aren't reaching the client:

1. You're Missing Critical Client-Side Libraries

Looking at your HTML code, there's no reference to either jQuery or the Socket.IO client library. Your JavaScript code uses $ (jQuery) and io (Socket.IO), but without loading these libraries first, the browser has no idea what those functions are—this is almost certainly a core issue.

Fix this by adding these script tags to your HTML's <head> or right before the closing </body> tag:

<!-- jQuery (required for your DOM manipulation code) -->
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<!-- Socket.IO client matching your server's 1.3.6 version -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>

2. Broadcast Messages Don't Go Back to the Sender by Default

When you use send(msg, broadcast=True), Flask-SocketIO sends the message to every connected client except the one that sent it. If you're testing by sending a message from your only client and expecting to see it in your own console, this won't happen unless you explicitly include the sender.

Update your server-side handler to include the sender:

@socketio.on('message')
def handleMessage(msg):
    print('Message: ' + msg)
    # Add include_self=True to send the message back to the sender too
    send(msg, broadcast=True, include_self=True)

3. Double-Check Client-Server Version Compatibility

You're using Socket.IO 1.3.6 on the server, so your client-side Socket.IO library must match this major version (1.x). If you accidentally loaded a newer 2.x or 3.x version of the client library, it won't properly communicate with your old server. The script tag I provided above uses 1.3.6, which matches your server setup.

Troubleshooting Steps to Verify

  • Open your browser's DevTools (F12) and check the Console tab for errors like $ is not defined or io is not defined—these confirm missing libraries.
  • Go to the Network tab and look for socket.io requests. You should see a WebSocket connection (or long-polling requests if WebSocket isn't supported) with 200 OK statuses.
  • Test with two browser windows: send a message from one, and check if the other receives it. This helps rule out the "sender exclusion" issue.
  • Add extra logging in your server handler to confirm messages are being processed:
    @socketio.on('message')
    def handleMessage(msg):
        print(f'Received message: {msg}')
        response = send(msg, broadcast=True, include_self=True)
        print(f'Message broadcast completed')
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:25:13