to my server are just two clients allowed to connect with. How to set the max of clients on two clients of socket.io?
this is how my server.js looks like:
var path = require('path');
var express = require('express'),
app = express(),
http = require('http'),
socketIo = require('socket.io');
var server = http.createServer(app);
var io = socketIo.listen(server);
server.listen(9000);
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + 'index.html'));
});
app.use(express.static(__dirname + '/'));
io.on('connection', function (socket) {
socket.on('data', function (data) {
socket.broadcast.emit('data', data)
});
socket.on('disconnect', function () {
console.log("disconnect")
});
});
This is untested, but you should be able to check number of users on connection and change it on connect/disconnect.
Here is an example:
const connectedUsers = 0;
const maxUsers = 2;
io.on('connection', function (socket) {
if(connectedUsers + 1 > maxUsers){ // check if the new connection will exceed the max connections allowed
socket.disconnect(); // if so, disconnect the user and exit https://stackoverflow.com/a/5560187/11518920
return;
}
connectedUsers++; // otherwise + 1 to the connectedUsers
socket.on('data', function (data) {
socket.broadcast.emit('data', data)
});
socket.on('disconnect', function () {
connecteUsers--; // on a disconnected decrease the connectedUsers count
console.log("disconnect")
});
});
Related
Need your help/guidance/suggestion for our scenario.
Issue: I am having some trouble connecting socket io client to socket io server. The error I got after running this code is connection time out.
My server code is :
const port = process.env.PORT || 4004;
const http = require('http');
const socket = require('socket.io');
const app = express();
const httpServer = http.createServer(app);
const io = new socket.Server(httpServer);
io.on('connection', (socket) => {
console.log("Socket connected");
});
httpServer.listen(port, () => {
console.log("Listening on port ",port);
});
My client code is:
<script src = "socket.io.min.js"> </script>
<script>
var socket = io.connect(`wss://${document.location.hostname}:${port}`);
console.log(socket);
socket.on('done', (data) => {
console.log(data);
});
</script>
Your server code does not start in my node installation.
I correct your server code with this below and seems to work
fine on my node installation. You forgot to link express library
const port = process.env.PORT || 4004;
const http = require('http');
const socket = require('socket.io');
const express = require('express');
const app = express();
const httpServer = http.createServer(app);
const io = new socket.listen(httpServer);
io.on('connection', (socket) => {
console.log("Socket connected");
});
httpServer.listen(port, () => {
console.log("Listening on port ", port);
});
You can do with this script. This is my personal working script for socket IO chat app.
Backend Server
require("dotenv").config();
const port = process.env.SOCKET_PORT || 3000;
const main_server_url = process.env.SERVER_URL;
var express = require("express");
var app = express();
var server = app.listen(port);
var connectionOptions = {
"force new connection": true,
"reconnection": true,
"reconnectionDelay": 2000, //starts with 2 secs delay, then 4, 6, 8, until 60 where it stays forever until it reconnects
"reconnectionDelayMax": 60000, //1 minute maximum delay between connections
"reconnectionAttempts": "Infinity", //to prevent dead clients, having the user to having to manually reconnect after a server restart.
"timeout": 10000, //before connect_error and connect_timeout are emitted.
"transports": ["websocket"] //forces the transport to be only websocket. Server needs to be setup as well/
}
var io = require("socket.io").listen(server, connectionOptions);
var axios = require("axios");
var users = [];
var connections = [];
console.log("Server connected done");
io.sockets.on("connection", function (socket) {
var server_url = main_server_url;
console.log(server_url);
console.log(people);
connections.push(socket);
console.log("Connected : total connections are " + connections.length);
// rest of events of socket
});
Front End JS for load IO for client
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script type="text/javascript">
var base_url = YOUR_BASE_URL;
var port = YOUR_SOCKET_PORT;
var socket_port_url = base_url + ":" + port;
var socket = io(socket_port_url);
socket.on('done', (data) => {
console.log(data);
});
</script>
Was trying to connect to jaeger using HTTP request using nodejs but the spans are not reaching the jaeger endpoint. please help with this code snippet.,
var initTracer = require('jaeger-client').initTracer;
var config = {
'serviceName': 'servicename1',
'reporter': {
'collectorEndpoint': 'http://jaeger-collector:14268/api/traces',
}
};
var options = {
tags: {
'servicename1': '1.0'
}
};
var tracer = initTracer(config, options);
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => {
const span = tracer.startSpan('http_request');
res.send('Hello Jaeger');
span.log({'event': 'request_end'});
span.finish();
});
app.get('/', function(req, res) {
res.send("Hello World!");
});
server.listen(3000);
console.log('Express server started on port %s', server.address().port);
Any help would be much appreciated!
Got it! We need to enable sampling strategy to reach the collector endpoint.
var initTracer = require('jaeger-client').initTracer;
var config = {
'serviceName': 'Jaeger_Service',
'reporter': {
'collectorEndpoint': 'http://jaeger-collector:14268/api/traces',
},
'sampler': {
'type': 'const',
'param' : 0.1
}
};
var options = {
'logger': {
'info': function logInfo(msg) {
console.log('INFO ', msg)
},
'error': function logError(msg) {
console.log('ERROR', msg)
}
}
};
var tracer = initTracer(config, options);
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => {
const span = tracer.startSpan('http_request');
res.send('Hello Jaeger');
span.log({'event': 'request_end'});
span.finish();
});
server.listen(8000);
console.log('Express server started on port %s', server.address().port);
I am trying to send data from one node server to another node server. But when i host the one server on heroku i am not able to obtain a socket connection.
Hope anybody can help. Thanks in advance
server.js
var express = require('express');
var socketIO = require('socket.io');
var path = require('path');
var value = "default";
var PORT = process.env.PORT || 3000;
// var engines = require('consolidate');
// app.set('views', __dirname + '/views');
// app.engine('html', engines.mustache);
// app.set('view engine', 'html');
var app = express();
//var server = app.listen(PORT, () => console.log(`Listening on ${
PORT }`));
var server = require('http').createServer(app);
var io = socketIO(server);
io.on('connection', (socket) => {
console.log('+Client connected successfully+');
socket.on('data', function (data) {
console.log('data from pi' + data);
});
socket.on('disconnect', () => console.log('Client
disconnected'));
});
//console.log(PORT + 'actual listening to'+server.address().port);
server.listen(PORT);
client.js
var io = require('socket.io-client');
var socket = io.connect('https://herokuappname.herokuapp.com/', {
reconnect: true });
console.log('2');
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});
I am looking to separate my Socket.io events/init from my main node server logic. The goal is to not only maintain the Socket.io code, but also maintain any events that I may emit.
I'm a little overwhelmed with understanding the scope of this and the method of encapsulation with Node and was hoping to get some clarification on a better way of doing things.
server.js
//-- Socket.io
var http = require('http').Server(app);
//-- Encapsulate Socket init/events
var io = require('./socket.js').listen(http)
var api = express.Router();
api.route('/users/:user_id')
.put(function(req, res) {
io.dispatch(req.body.event);
}
}
//-- Start Server
http.listen(port);
console.log('Server started on port: ' + port);
io.init(app);
socket.js
'use strict'
var io = require('socket.io');
var ioJwt = require('socketio-jwt');
var clientsConnected = 0;
var ioServer;
exports.listen = function(http, app) {
ioServer = io.listen(http);
return ioServer;
}
exports.init = function(app) {
ioServer.use(ioJwt.authorize({
secret: app.get('secret'),
handshake: true
}));
ioServer.on('connection', function(socket){
connect();
socket.on('error', function(err) {
console.log('Socket.IO error:');
console.log(err);
});
socket.on('disconnect', function(){
disconnect();
});
});
}
function connect() {
clientsConnected++;
console.log('user connected. ' + clientsConnected + ' total.');
}
function disconnect() {
clientsConnected--;
console.log('user disconnected. ' + clientsConnected + ' total.');
}
The minimal communication the two modules need to have is that the http server has to be provided to the sockets module so it can initialize itself properly and the http server must call the sockets module to dispatch appropriately. So, you can pursue modularization that has only those two connections:
server.js
var http = require('http').Server(app);
var dispatch = require('./sockets.js')(http);
var api = express.Router();
api.route('/users/:user_id')
.put(function(req, res) {
dispatch(req.body.event);
}
}
//-- Start Server
http.listen(port);
console.log('Server started on port: ' + port);
sockets.js
'use strict'
var io = require('socket.io');
var ioJwt = require('socketio-jwt');
var clientsConnected = 0;
var ioServer;
module.exports = function(server) {
ioServer = io.listen(server);
ioServer.use(ioJwt.authorize({
secret: app.get('secret'),
handshake: true
}));
ioServer.on('connection', function(socket){
connect();
socket.on('error', function(err) {
console.log('Socket.IO error:');
console.log(err);
});
socket.on('disconnect', function(){
disconnect();
});
// return dispatch function
return function(data) {
io.dispatch(data);
}
}
function connect() {
clientsConnected++;
console.log('user connected. ' + clientsConnected + ' total.');
}
function disconnect() {
clientsConnected--;
console.log('user disconnected. ' + clientsConnected + ' total.');
}
I am trying to build a small app in nodejs to publish and subscribe. I am stucked in how I can publish from client side. Here is the code I have.
Here is my server code (server.js)
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app);
app.use(express.bodyParser());
app.get('/', function(req, res) {
res.sendfile(__dirname + '/public/index.html');
});
app.post('/publish/:channel/:event/', function(req, res) {
console.log("**************************************");
var params = req.params;
console.log(req.params);
console.log(req.body);
var data = req.body;
console.log("**************************************");
var result = io.sockets.emit(params.channel,{event:params.event,data:data});
//console.log(result);
console.log("**************************************");
res.sendfile(__dirname + '/public/index.html');
});
//include static files
app.use(express.static(__dirname + '/public'));
server = server.listen(3000);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (s) {
socket = s
socket.emit('c1', { hello: 'world' });
socket.on('test', function (data) {
socket.emit('c1', { hello: 'world' });
console.log('test');console.log(data);
});
});
And here is client code
var narad = {};
narad.url = 'http://192.168.0.46:3000';
narad.lisentingChannels = {}
var socket = io.connect(narad.url);
function Channel(channelName) {
this.channelName = channelName; //serviceObject is the object of
this.events = {};
};
Channel.prototype.bind = function (event, callback) {
this.events[event] = callback;
};
narad.subscribe = function (channelName) {
var channel = new Channel(channelName)
this.lisentingChannels[channelName] = channel;
socket.on(channelName, this.callbackBuilder(channel))
return this.lisentingChannels[channelName];
}
narad.callbackBuilder = function (channel) {
return function (data) {
var callback = channel.events[data["event"]];
callback(data.data);
}
}
You can use the emit method on both the client and the server websocket connections, taken from Socket.io:
var socket = io.connect(narad.url);
socket.emit('publish', 'message');
Then on your server you listen for the message:
socket.on('publish', function (data) {
// Emit the published message to the subscribers
socket.emit('subscribers', data);
console.log(data);
});
This way you are using the bi-directional communication of websockets without having to use some POST api.