How to send additional param for connection - node.js

I use Socket.io
Client:
var socket = new io.Socket(null, {port: 8081, ...
Server:
io.on('connection', function(client){ ...
Sow actually I try to do multiroom chat app - so how can I pass chat_id or something like that?

I'm on the same issue and finally decided to go with [Push-It].1
Documentation is a bit rare, but it's quite easy to use.

Related

How to check socket is alive (connected) in socket.io with multiple nodes and socket.io-redis

I am using socket.io with multiple nodes, socket.io-redis and nginx. I follow this guide: http://socket.io/docs/using-multiple-nodes/
I am trying to do: At a function (server site), I want to query by socketid that this socket is connected or disconnect
I tried io.of('namespace').connected[socketid], it only work for current process ( it mean that it can check for current process only).
Anyone can help me? Thanks for advance.
How can I check socket is alive (connected) with socketid I tried
namespace.connected[socketid], it only work for current process.
As you said, separate process means that the sockets are only registered on the process that they first connected to. You need to use socket.io-redis to connect all your nodes together, and what you can do is broadcast an event each time a client connects/disconnects, so that each node has an updated real-time list of all the clients.
Check out here
as mentioned above you should use socket.io-redis to get it work on multiple nodes.
var io = require('socket.io')(3000);
var redis = require('socket.io-redis');
io.adapter(redis({ host: 'localhost', port: 6379 }));
I had the same problem and no solution at my convenience. So I made a log of the client to see the different methods and variable that I can use. there is the client.conn.readystate property for the state of the connection "open/closed" and the client.onclose() function to capture the closing of the connection.
const server = require('http').createServer(app);
const io = require('socket.io')(server);
let clients = [];
io.on('connection', (client)=>{
clients.push(client);
console.log(client.conn.readyState);
client.onclose = ()=>{
// do something
console.log(client.conn.readyState);
clients.splice(clients.indexOf(client),1);
}
});
When deploying Socket.IO application on a multi-nodes cluster, that means multiple SocketIO servers, there are two things to take care of:
Using the Redis adapter and Enabling the sticky session feature: when a request comes from a SocketIO client (browser) to your app, it gets associated with a particular session-id, these requests must be kept connecting with the same process (Pod in Kubernetes) that originated their ids.
you can learn more about this from this Medium story (source code available) https://saphidev.medium.com/socketio-redis...

emits from client must be called again in server?

I have a problem with understanding how socket.io and node.js works.
I tried few examples with emitting messages and it worked. What I don't understand is emitting from clients.
I use emit in client, for example: socket.emit('custom_event');, but it doesn't work in other clients unless I add something like this in my server:
var io = require('socket.io').listen(app);
io.sockets.on('connection', function(socket) {
socket.on('custom_event', function() {
socket.emit('custom_event');
});
});
Am I doing something wrong or do I need to always add definition on server side for something that client should be emitting to other clients?
this is not possible, socketio need the server logic between your clients.
You can do:
socket.broadcast.emit
Broadcasting means sending a message to everyone else except for the socket that starts it.
io.sockets.emit
Emits to all, (inc the socket that starts the action.)
But allways from the server
Can you connect client to client via web sockets without touching the server?

How can I get the hostname of a socket?

When I receive a certain event from a connected socket, I have to send a request with as parameter my hostname and port. I was hoping to be able to retrieve this information from the socket object. Unfortunately, there is little documentation on this and I can't seem to be able to find out if and how this is possible.
So, is it possible to do something like this in Socket.io:
io.sockets.on('connection', function(socket){
console.log(socket.manager.server.hostname)
})'
(Or, alternatively: which thinking error am I making here in thinking that this should be possible in the first case?)
try this:
console.log(socket.handshake.headers.host);
split port if necessary:
console.log(socket.handshake.headers.host.split(":").shift());
The accepted answer does not work anymore in 2022.
Today this information can be accessed like this:
const socket = io()
socket.on('connect', () => {
console.log('Socket is connected with', this.socket.io.uri)
})

Are you supposed to leave Redis open, or open and quit it after each use in node?

I have a socket.io server using redis called "server.js" that fires up a node server. Currently it is something like this:
var client = redis.createClient()
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
client.set(); // do something with redis
});
Then I fire up my server and it just stays alive. Is this wrong? Should it be like this?
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
var client = redis.createClient()
client.set(); // do something with redis
client.quit();
});
Am I supposed to keep opening and closing redis, or can I just open it once and leave it open? Which one of the above snippets is the proper way to start a server?
The first one is the preffered syntax because you don't want to make a new redis connection each time a clients connects to Socket.IO. If you have 1000 users connected would you want to have 1000 connections to Redis or just one (ok maybe more since you'd spawn more servers)?
As #racar suggested, you should take a look also at this question:
How to reuse redis connection in socket.io?

Socket.io, Redis Store and IE

I got a game using Redis, Socket.io, theres 2 nodejs servers running diff socket.io clients. I am communicating with both socket.io clients through the redis store, that way I can emit to all sockets whenever I want. And it works.
io.sockets.emit('successful_connection', { success : true }); return;
My problem is, when ie calling a specific socket by id, it fails.
io.sockets.socket(socketId).emit('successful_connection', { success : true }); return;
I have no idea why, it works in all other browsers. Heres the code for socket.io/redis store config
io.configure(function(){
var RedisStore = require('socket.io').RedisStore,
opts = {host: **.***.**.**, port: ****};
io.set('store', new RedisStore({redisPub:opts, redisSub:opts, redisClient:opts}));
});
Any advice would be helpful, right now my main thought is "why have nodejs/socket.io servers." Is there really a benefit if i have to deal with this. Thanks
This blog post with example code might help you.

Resources