socket.io with node cluster only long poll works - node.js

Using socket.io and nodeJS cluster, looks like Websocket protocol fails and it falls back to long polling, any idea why it isnt using websocket?
This is the only error in console
WebSocket connection to
'ws://localhost:5050/socket.io/?EIO=3&transport=websocket&sid=82qh7nBXGusxyelJAAAG'
failed: Connection closed before receiving a handshake response
Here is my node application
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});
});
}
Client code
var socket = io();
socket.on('message', function (data) {
var item = $('<li>' + data + '</li>');
$('ul').prepend(item);
});
socket.emit("join", "GBPUSD");

For those who may face similar issue, it turned out that I have the following line twice
var io = require('socket.io')(server);
Removing one, solved the issue.

Related

WebSocket connection to 'ws://X.XXX.XXX.XXX:5858/socket.io/?EIO=3&transport=websocket' failed:

I am trying to solve this issue since a long but not getting an accurate answer on the stackoverflow.
We are checking on this URL.
http://amritb.github.io/socketio-client-tool/v1/
and getting the following error.
Connecting to: http://x.xxx.xxxx.xxx:5858/ with options: {"path":"","transports":["websocket"]}
Here is the code snippet.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const port = process.env.PORT || 5858;
var compression = require('compression');
app.use(compression());
io.on('connection', function (socket) {
// Socket connection for Drivers
socket.on('join', function (data) {
socket.join(data.room); // join room
console.log('New user joined on room:' + data.room);
console.log(data);
});
socket.on('disconnect', function () {
socket.leave(socket.room);
});
});
http.listen(port, function () {
console.log('Socket Listening on Port: ' + port);
});

socket.io client reconnect with server automatically

I have implemented socket.io with node.js http server. The server pushes the Realtime data to the clients. I noticed a problem that when the server is restarted the client does not get data automatically means it does not reconnect automatically with the server. Please suggest the solution. My client code is as below
client index.html
<script>
var socket = io.connect('http://localhost');
socket.on('field', function (data) {
console.log(data); });
</script>
server.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8070);
var mysocket = 0;
function handler(req, res)
{
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
console.log('index.html connected');
mysocket = socket;
});
//udp server on 41181
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
console.log("msg: " + msg);
if (mysocket != 0){
mysocket.emit('field', "" + msg);
}
});
server.on("listening", function () {
var address = server.address();
console.log("udp server listening " + address.address + ":" +
address.port);
});
server.bind(41181);

How to run websocket and client on different ports

I have the following client ( serves the chat interface ) and a websocket, which are connected by the http. Http at the moment runs on the port 8080. So I would like to run the client on one port and the websocket on another, but if I disconnect them by http and of course the websocket doesn´t work on the client.
So is there a way to run them on different ports but still have them connected by the http ?
server:
var express = require('express');
var app = express()
app.use(express.static(__dirname + '/public'));
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs')
var port = 8080;
/************************************************ */
if (process.argv.indexOf('--port') >= 0) {
port = process.argv[process.argv.indexOf('--port') + 1]
}
/************************************************ **/
var sIndexHtmlTemplate = fs.readFileSync(__dirname + '/index1.html', 'utf8');
/************************************************ ***/
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
});
});
io.on('connection', function (socket) {
socket.on('chat message', function (msg) {
console.log('message: ' + msg);
io.emit('chat message', msg);
});
});
/************************************************ ***/
http.listen(port, function () {
console.log('listening on *' + port);
});

Nodejs , Redis,Sockets

I have a nodejs app which reads data from redis and I am unable to push it into socket. In the c.write(message) part, if I hardcode(example c.write('hello') ,the messages are being put to the socket but when i put it as c.write(message), nothing is going to the socket. Thanks in advance,
var net = require('net');
var split = require('split');
var Redis = require('ioredis');
var redis = new Redis();
var server = net.createServer(function(c) {
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
redis.subscribe('test-channel');
redis.on('message', function(channel, message) {
console.log(message);
c.write(message);
c.pipe(c);
});
});
server.on('error', (err) => {
throw err;
});
server.listen(3005, 'localhost', () => {
console.log('server bound');
});
I have got the answer.
Just add below lines to your code :
var message_redis = message+'\r'+'\n';
c.write(message_redis);

Why is my code printing illogical patterns everytime I run my node.js application?

I am creating a pub-sub application using node.js, redis, socket.io.
For my server side this is the code I have for app.js:
var express = require('express');
var app = express();
var redis = require('redis');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
app.use(express.static(__dirname + '/public'));
var port = process.env.PORT || 8000;
var sub = redis.createClient();
var pub = redis.createClient();
io.on('connection', function(socket){
socket.on('subscribe', function(channel){
sub.subscribe(channel);
console.log("Successfully subscribed");
});
socket.on('publish', function(msg, channel){
pub.publish(channel, msg);
if(pub.publish(channel, msg)){
socket.emit('message', msg);
}
else{
socket.emit('message', "The channel doesn't exist!");
}
})
})
http.listen(port, function(){
console.log('listening on port ' + port);
});
for index.js on the front-end, I am using jquery to fetch the html elements and use socket.io to communicate with the server:
$(function(){
$("#sub-btn").click(function(){
var socket = new io.connect('http://localhost');
var channelName = $("#channel").val();
var content = $('#content');
socket.emit('subscribe', channelName);
})
$("#pub-btn").click(function(){
var socket = new io.connect('http://localhost');
var msg = $("#published_message").val();
var channelName = $("#channel").val();
var content = $('#content');
socket.emit('publish', msg, channelName);
socket.on('message', function(msg){
content.append(msg);
})
})
})
When I run my node application this is what I get:
After I insert some input for the first time, say for example:
After I insert some other input:
I can't tell why this bug is happening.
you are appending new message to previous messages. this is where the bug happens!
var content = $('#content');
socket.emit('publish', msg, channelName);
socket.on('message', function(msg){
content.append(msg);
});
here when new message arrives, it appends to previous messages and cause the problem.

Resources