I am now starting in this world of Node.js, I've done several tests, initially as the typical "Hello World", up to the creation of a simple chat, I have embarked on the creation of one a bit more complex, which I describe below:
A chat in which users already exist, which are housed in a MySQL database.
It should create multiple chat rooms, where every conversation is one to one.
Initially I did Mysql connection tests, achieving it efficiently, but coming across problems when closing the connection to it, so I found another "solution" which will ask if it is advisable to do it or the Otherwise it would be a big mistake.
To chat'm making use of Seller Socket.io known, which, reading the documentation I have found related to the ID of the session, you can associate more information, what I'm doing is the following:
I a room through socket.join option (room)
With the property "set" of socket.io, I am storing information related to the connected user, such as name, database id and url of the picture, through an object.
Using io.sockets.clients (room), get users who are in the room, given that a user can have more than one session (several windows / tabs), so do the validation client side with the user id, to show just one.
Server:
var io = require("socket.io").listen(8080, {log: false});
io.on("connection", function(socket)
{
socket.on("newUser", function(data)
{
var participants = [];
var room = data.ig;
socket.set('iduser', data.d, function ()
{
socket.join(room);
for (var ver in pas = io.sockets.clients(room))
{
participants.push({id: pas[ver].store.data.iduser[0].id, n: pas[ver].store.data.iduser[0].n, f: pas[ver].store.data.iduser[0].f});
}
io.sockets.in(room).emit("newConnection", {participants: participants});
});
});
socket.on("disconnect", function()
{
var rooms = io.sockets.manager.roomClients[socket.id];
for(var room in rooms)
{
if(room.length > 0)
{
room = room.substr(1);
}
}
var idusuario = 0;
for(var ver in pas = io.sockets.clients(room))
{
if(pas[ver].id == socket.id)
{
idusuario = pas[ver].store.data.iduser[0].id;
break;
}
}
if(idusuario != 0)
{
//El número de veces que tiene una sesión...
var num = 0;
for(var ver in pas = io.sockets.clients(room))
{
if(pas[ver].store.data.iduser[0].id == idusuario)
{
num++;
}
}
if(num <= 1)
{
io.sockets.in(room).emit("userDisconnected", {id: idusuario, sender:"system"});
}
}
});
});
Client
Appreciate their opinions or suggestions on how to deal with this difficulty.
Thanks in advance for their help.