我一直在尝试解决一个非常奇怪的Socket.io错误。
如果我在服务器运行时在客户端上打开页面,它将无法连接消息:
universalModuleDefinition:3 WebSocket连接 'WS://本地主机:4000 / socket.io / EIO = 3及运输=网页套接字&安培; SID = f6LwPIDZubiPKE-TAAAA' 失败:在收到握手响应之前关闭连接
如果我重新启动服务器,同时让页面保持打开状态,那么它会毫无问题地连接。
app.js
const app = express();
const server = require('http').Server(app);
require('./socket')(server);
// More code here
server.listen(app.get('port'))
socket.js
const io = require('socket.io');
const jackrabbit = require(`jackrabbit`);
const rabbit = jackrabbit(process.env.RABBIT_URI);
const exchange = rabbit.default();
function Socket (app) {
this.io = io(app);
this.io.on('connection', socket => {
socket.emit('sync');
socket.on('room', room => {
socket.join(room);
});
})
this.queue = exchange.queue({ name: 'worker.socket' });
this.queue.consume(this.onMessage.bind(this), { noAck: true });
}
Socket.prototype.onMessage = function (message) {
this.io.to(message.report).emit('photo', message.photo);
}
module.exports = function (app) {
return new Socket(app);
}
客户端
var socket = io.connect();
socket.on('connect', function () {
// This gets triggered every time (after the error above)
console.log('Connected');
// This is never logged by the server
socket.emit('room', value); // value set by template engine
});
socket.on('sync', function(){
// will not execute first time I connect, but if I restart
// the server, it runs no problem
alert('Synced with server');
})
socket.on('photo', function(data) {
// also will not be run the first time, but works if the
// server is restarted when the page is open
})
修改
我尝试过将其重写为
server.listen
websocket
这些方法都没有起作用
答案 0 :(得分:0)
找到我的问题的解决方案(实际上不是我发布的任何代码的问题)。我正在使用Express的compression
中间件,这似乎打破了socket.io。解决方案是添加以下内容:
app.use((req, res, next) => {
// Disable compression for socket.io
if (req.originalUrl.indexOf('socket.io') > -1) {
return next();
}
compression()(req, res, next);
});