How can I get socket room name in socket 1.4? - node.js

I'm looking for a method or a command line to get the socket room name if possible. Any ideas or tips are highly appreciated! For example if the name of the room is 'roomName', I'm looking to get this value, ty!

A socket.io socket can be in multiple rooms. In fact, it is automatically placed into a room with the same name as the socket.id value when the socket first connects.
If what you're trying to do is get a list of all the rooms a socket is in on the server-side of the connection, you can use socket.rooms. That is an object that lists all the rooms the socket is in. If you want just an array of room names the socket is in, you can use this:
let rooms = Object.keys(socket.rooms);
If you want to eliminate the auto-generated room that matches the socket.id, you can do this:
let rooms = Object.keys(socket.rooms).filter(function(item) {
return item !== socket.id;
});
If you're trying to get this information from the client-end of things, it is not available from the client-side socket. You would have to ask the server which rooms this client is in or you'd have to have a system where the client was kept notified of what rooms it was being put in and it kept track of that data. The socket.io client does not know what rooms it is in.
One other thing to be careful of in socket.io. I've seen some asynchronous behavior in joining rooms which means that if you socket.join("someRoom") and then immediately query socket.rooms, the new room might not be there yet. If you query socket.rooms on the next tick, it will be there. I'm not sure if this always happens or just happens in some circumstances.

Related

socket.io leave current room and join after button is clicked

my question is about socket rooms and leave and joining in rooms .my problem is that : i am creating chatroom and i want whenever user (socket) clicks "next person" button (in my case link) i want socket to disconnect (leave) its current room and join another one where another socket is waiting for second socket. like in Omegle
Heading
so i tried this code
client-side:
N.addEventListener('click', function(e){
socket.emit('next')
});
socket.on('next',function(){
socket.disconnect()
document.GetElementById('divd').style.display = "inline";
socket.connect()
});
server-side:
socket.on('next', function(){
socket.leave(socket.current_room)
chnm.in(socket.current_room).emit('next');
socket.join(room)
});
but whenever i click "next" it only shows both socket disconnect div like in disconnect event but does not lets socket which triggered that event to join other room
rooms in my case is like that
var room = "room" + numb;
socket.current_room = room;
but what i want is to show in room (where socket disconnected) that socket disconnected and socket which triggered that event to be joined in other room .
(example: in room 1 socket triggered "next" link he/she disconnects from the room 1 and joins to room 2 and in room 1 appears disconnect div, i think it will appear anyway if i use socket.disconnect() because i already created disconnect event . thanks guys for help <3
There's still not enough code shown or enough of the overall design described that you're trying to achieve, but here's what I can see from what you've shown so far.
Here's your sequence of events:
User clicks button
Client code does socket.emit('next')
Server receives next message
Server calls socket.leave(socket.current_room) to leave the current room
Server does a .emit('next') to everyone still in that room
Server calls socket.join(room) (I have no idea where the room variable comes from)
Clients receive next message and that causes them to socket.disconnect() and thensocket.connect()` (no idea why it's doing that).
The things that seem odd to me about this sequence of events are:
The socket.disconnect() followed by the socket.connect() is completely unnecessary and probably causing problems. First off, these events are asynchronous. If you really wanted to do one followed by the other, you need to wait for the disconnect to finish before trying to do the reconnect. But, mostly, there should be no reason to disconnect and then reconnect. Just update the state of the connection you already have.
I don't follow why when you assign someone to a new room, you then disconnect everyone else who was in that room.
Please don't use the same message name next to mean one thing when the client receives it and something completely different when the server receives it. This isn't a programming error per se, but it really makes your code hard to understand. Give each its own descriptive name.

socket.io How Can I Get "Socket object" list in room

folks. So far, I have been searching "How can I get socket list in room". I was able to find a lot of results.
like this link.
How to get room's clients list in socket.io 1.0
example, console.log(io.nsps['/'].adapter.rooms);
But, That answers can get the socket list in room not "Object".
I need socket object list of that into the socket in the room.
How can I get socket's object list in rooms. Please tell me solution.
io.sockets.connected[SOCKET_ID_GOES_HERE]
You can use io.nsps['/'].adapter.rooms to find socket ids and then get the objects you need with the following code:
var sockets_in_room = io.nsps['/'].adapter.rooms[ROOM_NAME_GOES_HERE]
var socket_objects = []
for (socketId in sockets_in_room) {
socket_objects.push(io.sockets.connected[socketId])
}

[Node.JS Socket.io]communication between two targeted sockets

I'm currently working on a small node.js game.
Game supposedly has a global chat, with a "logged in" list to challenge people.
For the chat and the logged in list, i'm using the default socket.io room/namespace.
I successfully send the challenge request with following code
// When a user sends a battle challenge
socket.on("sendChallenge", function(data) {
// Try with room
socket.join('battleRoom');
var data= {
"userID": data.targetID,
"challengerName": data.challengerName
};
console.log(data.challengerName + " challenged " + data.userID);
// broadcast the message, but only the concerned player will answer thanks to his ID
socket.broadcast.emit('receiveChallenge', data);
});
Client side, I then have this code :
socket.on('receiveChallenge', function (data) {
if (data.userID == userID) {
alert("received challenge from " + data.challengerName);
socket.emit('ack');
}
});
The right player indeed receive the alert, and sends 'ack' to the server :
socket.on('ack', function() {
socket.join('battleRoom');
socket.to('battleRoom').broadcast.emit('receiveMessage', 'SYSTEM: Battle begun');
//socket.to('battleRoom').emit('receiveMessage', 'SYSTEM: Battle begun');
})
Except that the "socket.to('battleRoom').broadcast.emit('receiveMessage', 'SYSTEM: Battle begun');" is only received by the challenger and not by the challenged, and I'm stuck.
(the 2nd line is commented because challenger received 2 messages and challenged received none)
The way i understand it, on the server, the functions socket.on() have "socket" as the client that sent the message, and then you use broadcast to send to all others.
Why is why, in the sendChallenge event, i have the socket.join('battleRoom') for the challenger to enter battleRoom.
I then broadcast the challenge, and asks the client to acknowledge the challenge.
In the ack, the client then supposedly joins battleRoom too.
But i'm obviously doing something wrong, and i can't seem to see what...
I want both the challenger and the challenged communicating through the server.
A link to an image more or less showing the situation : Here
(screen is during the second time i clicked on the quickFight button, showing the Battle begun of the 1st click on the left, and the alert that user was challenged on the right)
Thanks in advance for your help!
As per the socket.io documentation broadcast does the following:
Broadcasting messages
To broadcast, simply add a broadcast flag to emit and send method calls. Broadcasting means sending a message to everyone else except for the socket that starts it.
So when you do:
socket.to('battleRoom').broadcast.emit('receiveMessage', 'SYSTEM: Battle begun');
You do not emit to the socket that broadcasted to the room. Simply replace that line with the following:
io.to('battleRoom').emit('receiveMessage', 'SYSTEM: Battle begun');
This is assuming that you named your socket.io object io, if you named it differently use that.
Just as a side-note, it's not necessary here to broadcast your original message to everyone if you create an associative array with all your connected socket id's (or sockets themselves). Then you can find the challenged socket id in your array and only emit to them specifically with the challenge. This would cut down on your server calls.

how to omit in sails.js two or more sockets in sails.sockets.broadcast?

I need to know how to omit in sails.js two or more sockets in sails.sockets.broadcast? I tried this:
function sendMessage(data){
var socketIds = ['socketId1','socketId2'];
sails.sockets.broadcast("room","event",data,socketIds);
//sending data to ALL sockets in the room :/
}
but it doesn't work.
I need know this because I need omit the sockets which belong to the same session. (example: session of user in computer browser and android browser)
somebody help?
There's nothing built-in that will do this for you, but broadcast is just a wrapper around emit anyway, so you can just roll your own by getting all of the socket IDs in the room you want to broadcast to, and omitting the IDs in your array.
// Get all the IDs of the sockets subscribed to "room"
var socketIds = sails.sockets.subscribers("room");
// Remove the IDs you want to omit
socketIds = _.difference(socketIds, ['socketId1','socketId2']);
// Emit your event to the rest!
sails.sockets.emit(socketIds, "event", data);

socket.io get socket.id from client who emits something

Is it possible to get the socket.id from the client thats emits something?
Like:
Clientside:
socket.emit("lol", "data")
Server side:
socket.on("lol", function(data) {
// get the socket.id from the client who sended this!!
});
So, I`m making a Tic Tac Toe game in multiplayer. I'm using rooms. In each room there are 2 players. But I need to detect in which room the player is that clicked a field.
I can also explain it like this:
Server side:
player1.on("click", function(data) {
console.log(data + " in room" + playRoom);
});
But this is not working.
I'm going to use answer format, but this may be only directionally correct :) If you want to send data to a room, the client has to specify what room to send to. For example:
socket.broadcast.to('room').emit('event_name', data);
To join a room:
socket.join('room');
This SO answer has a nice way of showing how a single socket could emit to multiple rooms (but I don't see the emitter actually subscribed to the room): https://stackoverflow.com/a/16475058/1861459
To your actual question of the client's ID - I might debug through socket.rooms to see if you can divine what specific ID each room's subscription has: https://github.com/Automattic/socket.io/wiki/Rooms#rooms-a-client-has-joined however, I don't see how this helps you - if you join a room and broadcast to a room the library is taking care of the namespacing for you.

Resources