Node+Express+Socket.io持续轮询异常求助:频繁触发Polling GET请求
Hey there! Let’s tackle why your Socket.io setup is stuck on continuous polling instead of using WebSocket like it should. Here’s what to check and fix:
1. Remove Extra Spaces in Client Connection URL
First, look at your client code:
socket = io.connect(' http://localhost:8890 ')
The spaces around the URL are causing a parsing issue—Socket.io can’t properly negotiate the WebSocket handshake with that malformed URL. Fix it by trimming the spaces:
socket = io.connect('http://localhost:8890')
This is the most likely culprit here, so start with this fix!
2. Verify Socket.io Initialization & CORS Settings
Your server code looks correct (using http.Server to wrap Express before passing to Socket.io), but if your client runs on a different port/domain later, you’ll need to configure CORS explicitly to avoid handshake failures:
var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server, { cors: { origin: "http://your-client-origin:port", // e.g., "http://localhost:3000" methods: ["GET", "POST"] } }); server.listen(8890); io.on('connection', function (socket) { console.log(socket['id'] + " client connected"); });
For local localhost development, CORS usually isn’t an issue, but it’s good to keep this in mind if you expand your setup.
3. Check for Version Mismatches
Make sure your client-side Socket.io version matches the server-side one. If there’s a major version gap (e.g., server uses v4, client uses v2), the handshake will fail, and Socket.io will fall back to polling indefinitely.
- Check server version: Look at
package.jsonfor thesocket.ioversion - Match client version: If using a CDN, use the corresponding version (e.g., for v4.7.2:
<script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script>)
4. Debug with Browser Dev Tools
Open your browser’s developer tools (F12) and check:
- Console tab: Look for errors related to WebSocket connections (e.g., 404 errors, CORS blocks)
- Network tab: Filter by "WS" to see if a WebSocket connection attempt was made and failed. If you only see polling requests, that confirms the handshake never succeeded.
After making these changes, your Socket.io should switch to WebSocket once the handshake works, and the polling requests will stop.
内容的提问来源于stack exchange,提问作者Amiya Ranjan

