I'm trying to implementing cluster on nodejs and using Socket.io in my application, after some search and introduced about that and finding sticky-socket-cluster i try to use that, here is sample code which i use the documentetion of library, but login socket not working and dont print log
require('sticky-socket-cluster/replace-console')();
var options = {
workers : require('os').cpus().length, // total workers (default: cpu cores count).
first_port : 8000, // 8000, 8001 are worker's ports (default: 8000).
proxy_port : 3000, // default (5000).
session_hash: function (req, res) {
return req.connection.remoteAddress;
},
no_sockets: false // allow socket.io proxy (default: false).
};
require('sticky-socket-cluster')(options, start);
function start(port) {
var express = require('express');
var http = require('http');
var app = express();
var server = http.Server(app);
var socket = require('socket.io')(server);
socket.on('connection', function (socket) {
console.log("socket.io connection handler...");
});
socket.on('login', function (data) {
console.log(data.username);
});
server.listen(port, function () {
console.log('Express and socket.io listening on port ' + port);
});
}
Related
My client is making a WebSocket request to this URL: ws://localhost:3000/feed/XBTMUR
In my server, I have NodeJs running express. I want to use Socket.io to listen to clients connecting to this URL and send feed data regularly.
I tried this but it is not working:
var app = require('../app');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
var io = require('socket.io')(server);
var feed =
io.of('/feed/XBTMUR').on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
io.on('connection', function(socket) {
console.log('a user connected, id ' + socket.id);
socket.on('disconnect', function() {
console.log('a user disconnected, id ' + socket.id);
})
})
setInterval(()=>{
io.sockets.emit('this', { receivers: 'everyone'});
},1000)
server.listen(port);
The client is not using Socket io.
I feel the the implementation is wrong while reading the documentation.
var feed = io.of('/feed') // `/feed` is the namespace
.on('connection', function (socket) {
socket.to('XBTMUR', { hello: 'world' }); // `XBTMUR` is the room / socket id
});
Hope this helps.
I'm not getting an error but io.on('connection', function(socket){
console.log('a user connected', socket.client.id);
}); doesn't seem to work when I deployed my application in Linode.
But in the development it's working fine.
server.js ( socket io )
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = 8002;
io.on('connection', function (socket) {
console.log('a user connected', socket.client.id); // triggering in the development
});
http.listen(port, function () {
console.log('Express server listening on port ' + port);
console.log('env = ' + app.get('env') +
'\n__dirname = ' + __dirname +
'\nprocess.cwd = ' + process.cwd());
});
client html ( note: i change the localhost to my web app ip)
<script src="http://localhost:8002/socket.io/socket.io.js"></script>
and my application seem to be using the socket.io polling-xhr.js
I'm kind of new to this.
I don't know if this will fix your particular problem, but in order to set up socket.io on the same port that your application uses you can configure it this way:
const express = require('express');
const app = express();
const http = require('http');
const hostname = 'localhost';
const port = 80;
// the express app is registered with the server
const server = http.createServer(app);
// setup socket.io and register it with the server
const io = require('socket.io').listen(server);
// tell the application to listen on the port specified
server.listen(port, hostname, function (err) {
if (err) {
throw err;
}
console.log('server listening on: ', hostname, ':', port);
});
Now socket.io runs on the same port as your application.
I am trying to build a small websocket application. I am trying to implement it on a website that already runs on a secure HTTPS protocol thus the websocket has to be on wss to work.
I build the server using the following code:
var express = require('express');
var app = express();
var fs = require('fs');
var key = fs.readFileSync('/etc/apache2/ssl/www.bigriss.com_private_key.key');
var cert = fs.readFileSync( '/etc/apache2/ssl/www.bigriss.com_ssl_certificate.crt' );
var ca = fs.readFileSync( '/etc/apache2/ssl/bigriss.com_ssl_certificate_INTERMEDIATE.crt' );
var options = {
key: key,
cert: cert,
ca: ca
};
var https = require('https').createServer(options, app);
var io = require('socket.io')(https);
var port = process.env.PORT || 8080;
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
var token = socket.handshake.query.token;
io.emit('chat message', msg + token);
});
});
https.listen(port, function () {
console.log('listening on *:' + port);
});
Which would seem to me to be a quite simple and standard implementation. I can access the url https://example.com:8080 properly and it is giving the contents that are read at index.html. On this html file is where I try to establish a connection using:
var socket = io.connect('https://bigriss.com:8080/?token=abc', {
transports: ['websocket'],
upgrade: false,
secure: true,
reconnect: true,
rejectUnauthorized : false
});
Having played several times with the options. Regardless, I get an error in the Chrome Console as being:
failed: Connection closed before receiving a handshake response
failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
In the terminal I get the following node error:
nodejs: ../src/util-inl.h:196: TypeName* node::Unwrap(v8::Local<v8::Object>) [with TypeName = node::TLSWrap]: Assertion `(object->InternalFieldCount()) > (0)' failed.
Aborted
I have testing this same setup with HTTP and it works correctly. Is there anything in particular that I am missing with HTTPS?
You suppose i have 3 room such as room1, room2 and room3
i want to join some users to this rooms, how can i do that?
my code doesn't correct and i can't do that
var socket = require('socket.io'),
express = require('express'),
fs = require('fs'),
app = express(),
server = require('http').createServer(app),
io = socket.listen(server),
port = process.env.PORT || 3000,
redis = require("redis"),
redisClient = redis.createClient(),
forever = require('forever'),
log = require('log4node');
var io_redis = require('socket.io-redis');
io.adapter(io_redis({host: 'localhost', port: 6379}));
require('sticky-socket-cluster/replace-console')();
var options = {
workers : require('os').cpus().length,
first_port : 8000,
proxy_port : 3000,
session_hash: function (req, res) {
return req.connection.remoteAddress;
},
no_sockets: false
};
var room = ["room1","room2","room3"];
require('sticky-socket-cluster')(options, start);
function start(port) {
io.sockets.on('connection', function (socket) {
socket.on('room1', function (room) {
socket.join(room[0])
});
socket.on('room2', function (room) {
socket.join(room[1])
});
});
server.listen(port, function () {
console.log('Express and socket.io listening on port ' + port);
});
}
when i use this code to join users as :
socket.on('room1', function (room) {
socket.join(room[0])
});
i get no result and code doesn't work and i don't know how can i do that
I'm using express.js server-side and I followed the socket.io setup guide. Unfortunately the socket connection is never successful, and I receive an unruly amount of GET requests that look like this:
Here's my setup:
CLIENT - index.html
<script src="https://cdn.socket.io/socket.io-1.3.7.js"></script>
<script>
// var socket = io.connect('http://localhost');
var socket = io.connect('http://localhost:9000/');
socket.on('connected', function (serverData) {
console.log(serverData);
});
</script>
SERVER - /io/index.js
'use strict';
var socketio = require('socket.io');
var io = null;
module.exports = function(server) {
if (io) return io;
io = socketio(server);
io.on('connection', function(socket) {
console.log('Sockets connected!');
socket.emit('connected', 'Sockets connected!')
})
return io;
};
SERVER - app.js
'use strict';
// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var express = require('express');
var mongoose = require('mongoose');
var config = require('./config/environment');
// Connect to MongoDB
mongoose.connect(config.mongo.uri, config.mongo.options);
mongoose.connection.on('error', function(err) {
console.error('MongoDB connection error: ' + err);
process.exit(-1);
});
// Populate databases with sample data
if (config.seedDB) { require('./config/seed'); }
// Setup server
var app = express();
var server = require('http').createServer(app);
require('./config/express')(app);
require('./routes')(app);
// Setup sockets
require('./io')(server);
// Start server
function startServer() {
server.listen(config.port, config.ip, function() {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
}
setImmediate(startServer);
// Expose app
exports = module.exports = {
app: app,
server: server
}
This is tipically what happen, when client does not reach the server.
The client try again and again . . .
For that you have to check your config server-side, checking the port and the path is often the first things you should check.
In your case, maybe you should check this part :
//require('./io')(server); typo error ??
require('./io/index.js')(server);
More further you don't seem to give the good part :
( maybe depending on version you use)
// Setup server
var app = express();
var server = require('http').createServer(app);
require('./config/express')(app);
require('./routes')(app);
// Setup sockets
require('./io')(server);
I think it should be :
// Setup server
var app = express();
var server = require('http').createServer(app);
require('./config/express')(app);
require('./routes')(app);
// Setup sockets
//require('./io')(server); |O----------------------------------|
require('./io/index.js')(app);//<---we pass app as argument----|
I hope this will help you.