我用 Express、SocketIO 和 Redis 创建了我的 Socket 服务器
server.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(8890, function (e) {
console.log(e);
});
io.on('connection', function (socket) {
console.log("new client connected");
var redisClient = redis.createClient();
redisClient.subscribe('message');
redisClient.on("message", function(channel, message) {
console.log("mew message in queue "+ message + "channel");
socket.emit(channel, message);
});
socket.on('disconnect', function() {
redisClient.quit();
});
socket.on('connect_error', function() {
redisClient.quit();
});
});
我从命令行运行 node server.js
。它的工作。
我还创建了一个 html 文件来连接到该服务器。
在浏览器控制台中,我运行 io.connect('http://localhost:8890')
。我得到了结果
如我所见,连接(请求)过多。 会发生什么?我的代码有什么问题?
最佳答案
您的客户端和服务器版本不匹配,导致初始连接失败,而旧的客户端愚蠢到只能一遍又一遍地尝试。如果您在服务器上使用 2.0.4,那么您也必须为客户端使用该版本。如果您直接从您的服务器提供客户端版本:
<script src="http://localhost:8890/socket.io/socket.io.js"></script>
然后,socket.io 服务器会自动为您提供正确的客户端版本。
或者,您可以手动链接到 CDN 上的正确版本,例如 https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js
。但客户端和服务器版本必须匹配。
直接从您自己的服务器获取客户端的优势在于,无论何时您更新 socket.io 的服务器版本,客户端版本都会自动为您升级并保持完美同步,因为匹配的客户端版本内置于服务器版本。
关于javascript - 为什么 socketIO 调用太多连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47708284/