Socket.io for NodeJS doesn\'t seem to work as a websocket server
For some reason, socket.io ALWAYS fallback to the long polling and if I force the w
In my case the problem was that I am proxying the server through browser-sync
browserSync({
//server: {
// // src is included for use with sass source maps
// baseDir: ['public', 'src']
//},
proxy: "localhost:4045",
port: 4046
So this will fail, however in production it works fine.
I had the exact same issue because I was defining 'io' twice. Double check where you are defining io in your code and ensure you are not defining the variable io twice.
Example of what I was doing wrong:
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var io = require('socket.io').listen(server.listen(config.port, config.ip, function () {
console.log('Express server listening on %d, in %s mode', config.port,
app.get('env'));
}));
Example of what fixed the issue:
var server = require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(config.port, config.ip, function () {
console.log('Express server listening on %d, in %s mode', config.port,
app.get('env'));
});
Here is the complete working example from one of our working projects:
const websocket = require('ws');
const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
wss = new websocket.Server({ server });
app.on('upgrade', wss.handleUpgrade);
wss.on('connection', ws => {
console.log('web socket connection is alive');
}
server.listen(8080, () => {
console.log('server started on PORT 8080');
});
translated from Medium
It worked for me!
restUrl = 'http://x.x.x.x:5555;
socket = io(this.restUrl, {
transports: ["websocket"],
upgrade: true,
upgradeTimeout: 6000000,
pingTimeout: 15000000000,
pingInterval: 1500000000,
maxHttpBufferSize: 10000000,
});
connect() {
if (this.socket.connected == false) {
var temp = this;
this.socket.connect();
this.socket.on('event', function (data) {
temp.socketData.next(data);
});
}
}
Slightly related to what @Lucas Klaassen answered: I had the following:
let express = require('express');
let app = express();
let http = require('http').Server(app);
let io = require('socket.io')(http);
// this is the culprit:
app.listen(port);
Changing last line is what fixed it:
http.listen(port);