使用socket.io和nodeJS集群,看起来像Websocket协议失败并且它回退到长轮询,任何想法为什么它不使用websocket?
这是控制台中唯一的错误
WebSocket连接到 ' WS://本地主机:5050 / socket.io / EIO = 3及运输=网页套接字&安培; SID = 82qh7nBXGusxyelJAAAG' 失败:在收到握手响应之前关闭连接
这是我的节点应用程序
if (cluster.isMaster) {
// we create a HTTP server, but we do not use listen
// that way, we have a socket.io server that doesn't accept connections
var server = require('http').createServer();
var io = require('socket.io').listen(server);
var redis = require('socket.io-redis');
var fs = require('fs');
io.adapter(redis({host: '127.0.0.1', port: 6379}));
var i = 0;
setInterval(function () {
// all workers will receive this in Redis, and emit
io.sockets.in('EURUSD').emit('message', 'EURUSD ' + i++);
io.sockets.in('GBPUSD').emit('message', 'GBPUSD ' + i++);
}, 1000);
for (var i = 0; i < os.cpus().length; i++) {
cluster.fork();
}
cluster.on('online', function (worker) {
console.log("New Worker with ID ", worker.id);
});
cluster.on('exit', function (worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
}
if (cluster.isWorker) {
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(config.port);
var io = require('socket.io').listen(server);
var redis = require('socket.io-redis');
io.adapter(redis({host: '127.0.0.1', port: 6379}));
io.sockets.on('connection', function (socket) {
console.log('connected to worker id ', cluster.worker.id);
socket.on('join', function (room) {
socket.join(room);
});
});
app.get("/", function (req, res) {
res.sendFile('views/index.html', {root: __dirname});
});
}
客户端代码
var socket = io();
socket.on('message', function (data) {
var item = $('<li>' + data + '</li>');
$('ul').prepend(item);
});
socket.emit("join", "GBPUSD");
答案 0 :(得分:0)
对于那些可能面临类似问题的人,事实证明我有以下两行
var io = require('socket.io')(server);
删除一个,解决了问题。