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 definedorio is not defined—these confirm missing libraries. - Go to the Network tab and look for
socket.iorequests. 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

