socket.io random chatroom one to one - node.js

so there is my code i am trying to create chatroom with Socket.io with rooms (one-to-one random chatroom) but i think there is bug because when i connect first two sockets it works perfectly but when i connect third socket it does not work anymore i think it is because of "numb++" but i don't know how to correct it because i have not many experience in rooms. i wanna implement : chat between 2 socket and when third client joins i wanna create second room and wait for forth socket to join to chat and etc. , and u i know i wanna one to one random chatroom like Omegle.
var numb = 1;
var chnm = io.of('/STchat')
app.get('/STchat', function(req, res){
res.sendFile('C:\\Users\\tuna\\Desktop\\JUSTFOL\\views\\Tchat.html')
chnm.once('connect', function(socket){
socket.join("room" + numb)
console.log('made socket connection', socket.id);
chnm.in("room" + numb).clients(function(err, clients){
if(clients.length > 2) {
numb++
}
});
socket.on('chat', function(data) {
chnm.in("room" + numb).emit('chat',data)
})
socket.on('disconnect', function(){
console.log('socket disconnected')
});
}
});
app.get('/StvChat', function(req ,res){
res.sendFile(__dirname + '/views/VideoC.html');
});
var socket = io.connect('http://localhost:5000/STchat')
var message = document.getElementById('message');
handle = document.getElementById('handle');
btn = document.getElementById('send');
output = document.getElementById('output');
typing = document.createElement('p');
typing.className = "tycl";
input = document.getElementById("message");
$('form').submit(function(){
socket.emit('chat',{
message: message.value,
});
$('#message').val('');
return false;
});
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("send").click();
}
});
socket.on('chat', function(data){
output.innerHTML += '<p>' +' '+ data.message +'</p>'
});

This was too long to fit in the comments so I have added as an answer. To clarify, here is an issue I am seeing in the way you are emitting the chat event. Lets walk through a scenario.
var numb = 1;
Two users (User A, and User B) connect to the socket and are put into room "room1". Now, numb should be incremented by your code and now numb will be == 2.
Now, User A (who is in "room1") emits a "chat" event. Here is the issue I see:
socket.on('chat', function(data) {
chnm.in("room" + numb).emit('chat', data)
})
User A's chat event is emitted to "room2" but User A is in "room1". This happens because numb == 2 at this point in the scenario and you are using numb to emit that event, basically this is what happens chnm.in("room" + 2). User B does not get User A's emit, because it was sent to the wrong room (room2). If I misunderstood what you are trying to do please let me know.
EDIT: As requested here is some modifications to your code that I have tested locally with success. Two users per each room.
var numb = 1;
var chnm = io.of('/STchat');
app.get('/STchat', function(req, res) {
res.sendFile('C:\\Users\\tuna\\Desktop\\JUSTFOL\\views\\Tchat.html');
chnm.once('connect', function(socket) {
// store the room in a var for convenience
var room = "room" + numb;
// join socket to the next open room
socket.join(room);
// store room on socket obj for use later - IMPORTANT
socket.current_room = room;
// log some stuff for testing
console.log('made socket connection', socket.id);
console.log("Joined room: ", socket.current_room);
// Check room occupancy, increment if 2 or more
chnm.in(room).clients(function(err, clients) {
if (clients.length >= 2) {
numb++;
}
});
socket.on('chat', function(data) {
// emit to that sockets room, now we use that current_room
chnm.in(socket.current_room).emit('chat', data);
});
socket.on('disconnect', function() {
console.log('socket disconnected');
});
});
});
app.get('/StvChat', function(req, res) {
res.sendFile(__dirname + '/views/VideoC.html');
});

Related

How to organize connection only once (node.js +express+ socket.io)

I have many functions where I need use socket.io but I want organize connection only once. Users are connected like this:
exports.sendInvite = function(io) {
let usersMap = new Map;
io.on('connection', function(socket) {
console.info(`client connected socketId = ${socket.id}`);
console.log("session_id: " + socket.request.session.session_id);
usersMap.set(socket.request.session.session_id, socket.id);
console.log("Map size: " + usersMap.size);
//some actions....
//and disconnect
socket.on('disconnect', function(){
usersMap.delete(socket.request.session.session_id);
console.log('user disconnected');
console.log("Map size: " + usersMap.size);
});
});
}
But I have another functions where I need use socket.io. How can I connect users only once and use their socket.id many times in other functions. Please, help me.

The socket.io is emitting to all rooms instead of the specified ones

I'm new to node and socket io. I'm trying to implement a realtime notification system for couple of my own apps. So, using node, express and socket io, the code is given below:
Server Side Code:
io.on('connection', function (socket) {
socket.on('subscribe', function(room) {
socket.join(room);
});
socket.on('unsubscribe', function(room) {
socket.leave(room);
});
});
Client Side Code:
var sio = io.connect('http://localhost:9000');
var ch1 = sio.emit('subscribe', 'channel1');
ch1.on('log', function (data) {
console.log('channel1: ', data);
});
var ch2 = sio.emit('subscribe', 'channel2');
ch2.on('log', function (data) {
console.log('channel2: ', data);
});
I'm firing/emitting the event from a route (express) for example:
app.get('/', function(req, res) {
var data1 = {
channel: 'channel1',
evennt: 'log',
message: 'Hello from channel1...'
};
io.to(data1.channel).emit(data1.event, data1);
});
When I'm hitting the route, the io.to(data1.channel).emit(data1.event, data1); is working but it sending the data to both rooms/channels but I was expecting to get the data only in ch1 because data1.channel contains channel1 so I was expecting the following handler will receive the data:
ch1.on('log', function (data) {
console.log('channel1: ', data);
});
Notice that, both channels have same log event. Am I on the right track. Is it possible at all?
var ch1 = sio.emit('subscribe', 'channel1');
var ch2 = sio.emit('subscribe', 'channel2');
You're subscribing the same socket (sio) to both rooms. Also, ch1 and ch2 are references to sio.
If you want to test it properly, you should create a second socket for the second channel:
var sio2 = io.connect('http://localhost:9000');
var ch2 = sio2.emit('subscribe', 'channel2');

socket.broadcast.to(receiver_socket_id) emitting n number of data (instead of one) to the receiver, where n is the number of user connected

I am using socket.io for private chatting for the server side I am using
socket.broadcast.to(receiver_socket_id).emit('message', data); // where data is a json object containing text
And at the client side code I catch the data using
socket.on('message', function (data) {
alert(data. text);
});
Its working properly and showing the alert on that specific user (socket id) ‘s panel when only two socket are connected (sender and receiver). But the problem appears when one more user connects to that socket then I see two alerts and when total 4 user connected (sender + receiver + two others) then see 3 alerts. But the good point is I can see the alerts only that specific client's panel not the others.
I can’t understand the problem, please help.
Please have a look on it
gyazo.com/a98d3a64a9fc6487e6ded8ccd90fd5ab
it prints test three times because three browsers are opened.
Full code here:
Sever side (I have used Redis):
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(8080);
var usernames = {};
io.on('connection', function (socket) {
console.log(socket.id);
socket.on('adduser', function (userId) {
usernames[userId] = socket.id;
});
var redisClient = redis.createClient();
redisClient.subscribe('message-channel');
redisClient.on('message', function (channel, data) {
var jsonObj = JSON.parse(data);
var rcvrId = jsonObj.rcvrId;
socket.broadcast.to(usernames[rcvrId]).emit('message', data); // Not throwing error....should work
});
socket.on('disconnect', function () {
console.log(socket.id + ' Disconnected');
redisClient.quit();
});
});
Client side:
var socket = io.connect('http://localhost:8080');
var userId = $('input[name="userId"]').val();
var rcvrId = $('input[name="rcvrId"]').val();
socket.on('connect', function () {
// call the server-side function 'adduser' and send one parameter (value of prompt)
socket.emit('adduser', userId);
});
socket.on('message', function (data) {
data = jQuery.parseJSON(data);
console.log(data);
$("#messages").append("<div><strong>" + data.userId + " : </strong><span>" + data.message + "</span></div>");
});
You can use io.of('/').sockets[rcvrId].emit('message', data). In case you are using a different namespace just replace the / with your namespace.

Socket.io: How to correctly join and leave rooms

I'm trying to learn Socket.io by building a set of dynamically created chatrooms that emit 'connected' and 'disconnected' messages when users enter and leave. After looking at a couple of questions I've put together something functional but most of the response linked are from people who admit they've hacked together answers and I've noticed there's a more general - and recent - discussion about the right way to do this on the Socket.io repo (notably here and here)
As I'm such a novice I don't know if the work below is an acceptable way to do things or it just happens to incidentally function but will cause performance issues or result in too many listeners. If there's an ideal - and official - way to join and leave rooms that feels less clunky than this I'd love to learn about it.
Client
var roomId = ChatRoomData._id // comes from a factory
function init() {
// Make sure the Socket is connected
if (!Socket.socket) {
Socket.connect();
}
// Sends roomId to server
Socket.on('connect', function() {
Socket.emit('room', roomId);
});
// Remove the event listener when the controller instance is destroyed
$scope.$on('$destroy', function () {
Socket.removeListener('connect');
});
}
init();
Server
io.sockets.once('connection', function(socket){
socket.on('room', function(room){ // take room variable from client side
socket.join(room) // and join it
io.sockets.in(room).emit('message', { // Emits a status message to the connect room when a socket client is connected
type: 'status',
text: 'Is now connected',
created: Date.now(),
username: socket.request.user.username
});
socket.on('disconnect', function () { // Emits a status message to the connected room when a socket client is disconnected
io.sockets.in(room).emit({
type: 'status',
text: 'disconnected',
created: Date.now(),
username: socket.request.user.username
});
})
});
Socket.IO : recently released v2.0.3
Regarding joining / leaving rooms [read the docs.]
To join a room is as simple as socket.join('roomName')
//:JOIN:Client Supplied Room
socket.on('subscribe',function(room){
try{
console.log('[socket]','join room :',room)
socket.join(room);
socket.to(room).emit('user joined', socket.id);
}catch(e){
console.log('[error]','join room :',e);
socket.emit('error','couldnt perform requested action');
}
})
and to leave a room, simple as socket.leave('roomName'); :
//:LEAVE:Client Supplied Room
socket.on('unsubscribe',function(room){
try{
console.log('[socket]','leave room :', room);
socket.leave(room);
socket.to(room).emit('user left', socket.id);
}catch(e){
console.log('[error]','leave room :', e);
socket.emit('error','couldnt perform requested action');
}
})
Informing the room that a room user is disconnecting
Not able to get the list of rooms the client is currently in on disconnect event
Has been fixed (Add a 'disconnecting' event to access to socket.rooms upon disconnection)
socket.on('disconnect', function(){(
/*
socket.rooms is empty here
leaveAll() has already been called
*/
});
socket.on('disconnecting', function(){
// socket.rooms should isn't empty here
var rooms = socket.rooms.slice();
/*
here you can iterate over the rooms and emit to each
of those rooms where the disconnecting user was.
*/
});
Now to send to a specific room :
// sending to all clients in 'roomName' room except sender
socket.to('roomName').emit('event', 'content');
Socket.IO Emit Cheatsheet
This is how I inform users of a "disconnecting user"
socket.on('disconnecting', function(){
console.log("disconnecting.. ", socket.id)
notifyFriendOfDisconnect(socket)
});
function notifyFriendOfDisconnect(socket){
var rooms = Object.keys(socket.rooms);
rooms.forEach(function(room){
socket.to(room).emit('connection left', socket.id + ' has left');
});
}
Here is a working method.
I am using socketio "socket.io": "^2.3.0" on server side. On Client side is android
// SocketIO
implementation('io.socket:socket.io-client:1.0.0') {
// excluding org.json which is provided by Android
exclude group: 'org.json', module: 'json'
}
Following is the code that is working for me.
// Join Chat Room
socket.on('ic_join', function(data) {
// Json Parse String To Access Child Elements
let messageJson = JSON.parse(data)
let room1 = messageJson.room1
console.log('======Joined Room========== ')
console.log(room1)
socket.join(room1, function(err) {
console.log(io.sockets.adapter.rooms[room1].length);
console.log(err)
})
})
// Leave Chat Room
socket.on('ic_leave', function(data) {
// Json Parse String To Access Child Elements
let messageJson = JSON.parse(data)
let room1 = messageJson.room1
console.log('======Left Room========== ')
console.log(room1)
socket.leave(room1, function(err) {
if (typeof io.sockets.adapter.rooms[room1] !== 'undefined' && io.sockets.adapter.rooms[room1] != null) {
console.log(io.sockets.adapter.rooms[room1].length);
console.log(err)
} else{
console.log("room is deleted")
}
})
})
For anyone reading this beyond 2/1/2021, using socket.io 3.1.0 and hopefully later, you can reference my example. I have found that the example on how to do this in socket.io's documentation is incorrect. They claim that in the disconnect event that socket.rooms is an object. While is uses the block container and is comma separated, there are no key pairs, meaning their demonstration of const rooms = Object.keys(socket.rooms) returns an empty value. It's creating an array out of an object that is really just an array. To my knowledge {} can only be used for block statements and objects. By some quirk, NodeJS is treating it like a normal array. I assign custom, 4 digit rooms on each connect event. So I have on the disconnect event I have the server skim through all the rooms, and if it encounters a room name with a length of 4, it tells everyone in the room that the size of the room decreased by one. On the client side, I have a socket event listener monitoring for this and when it's detected, updates a innerHTML property so that the clients can display the number of connected users.
//client side code:
socket.on('roomSize', (roomSize) => {
document.getElementById('clientCount').innerHTML = roomSize + ' clients connected';
});
//Server side code:
io.on("connection", (socket) => {
socket.on('createRoom', () => {
let ID = makeID(4)
while (io.sockets.adapter.rooms.has(ID)) {
ID = makeID(4)
}
socket.join(ID);
socket.emit('setID', ID);
});
socket.on("joinRoom", (room) => {
socket.join(room);
let roomSize = io.sockets.adapter.rooms.get(room).size
io.in(room).emit('roomSize', roomSize);
socket.emit('roomJoined', room, roomSize);
});
socket.on('disconnecting', function() {
let rooms = socket.rooms;
rooms.forEach(function(room) {
if (room.length === 4) {
let roomSize = io.sockets.adapter.rooms.get(room).size - 1
io.in(room).emit('roomSize', roomSize);
}
});
});
function makeID(length) {
var result = '';
var characters = '0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
})

Socket 1.0 repeating connect multiple times

I'm using Heroku + RedisToGo + Express 4.0 + socket.io 1.0.6.
I just recently upgraded to 1.0 from 0.9, and it's half working now. I've hacked together a app from tutorials but my lack of understanding socket.io is showing, so I'm taking a step back. The first question I have is that now socket.on('connect') is happening repeatedly, without stop, even when a connection is successful. My client-side console.log just keeps going and going. Here's client-side:
// Connect the user
socket.on('connect', function(){
var currentUserId = '<%= currentUser.id %>';
// Add user to redis
socket.emit('login', { userID: currentUserId});
// Retrieve presence info
socket.emit('presence');
});
// Show Presence
socket.on('presence', function(data) {
var userID = data.user;
var presence = data.presence;
if (presence) {
$('#red-dot-' + userID).css("display", "none");
$('#green-dot-' + userID).css("display", "inline");
// Show the hangout button
$('#hangout-' + userID).show();
$('#hangout-unavail-' + userID).hide();
}
else {
$('#red-dot-' + userID).css("display", "inline");
$('#green-dot-' + userID).css("display", "none");
}
});
And server-side:
io.sockets.on('connection', function (socket) {
var savedUserID;
socket.on('login', function(data){
var userID = data.userID;
savedUserID = userID;
// add first user
redis.sadd("users", userID);
redis.hmset("users:"+userID, "socketID", socket.id, "userID", userID);
});
socket.on('presence', function(){
// Get the list of online users and show Presence
redis.smembers("users", function(err,results) {
var onlineUsers = results;
for (var i in onlineUsers) {
var userID = redis.hget("users:"+onlineUsers[i],"userID", function(err,reply) {
var userID = reply;
// Emit presence
io.sockets.emit('presence', {
user: userID,
presence: "true"
});
});
}
});
});
As you can see I'm manually adding users to redis.
I found the answer in this Google Group thread.
The problem occurred because I had socket.emit('presence'); in my socket.on('connect', function(){}); client-side.
This in turn called socket.on('presence', function(){}); server-side, which was the problem.

Resources