socket.get() AND socket.set() gives problems - node.js

I'm using NodeJs v0.10.28 and everytime i try to login to the chat i get a error
TypeError: Object #<Socket> has no method 'set' at Socket.<anonymous>
And if i'm deleting the lines it works but not working right.
What is the wrong thing in this code
// get the name of the sender
socket.get('nickname', function (err, name) {
console.log('Chat message by ', name);
console.log('error ', err);
sender = name;
});
AND
socket.set('nickname', name, function () {
// this kind of emit will send to all! :D
io.sockets.emit('chat', {
msg : "Welcome, " + name + '!',
msgr : "Nickname"
});
});
FULL CODE
http://pastebin.com/vJx7MYfE

You have to set the nickname property directly in the socket!
From socket.io website:
The old io.set() and io.get() methods are deprecated and only supported for backwards compatibility. Here is a translation of an old authorization example into middleware-style.
Also, from an example of the socket.io website :
// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;
// when the client emits 'add user', this listens and executes
socket.on('add user', function (username) {
// we store the username in the socket session for this client
socket.username = username;
// add the client's username to the global list
usernames[username] = username;
++numUsers;
addedUser = true;
socket.emit('login', {
numUsers: numUsers
});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username,
numUsers: numUsers
});
});
Check the example here : https://github.com/Automattic/socket.io/blob/master/examples/chat/index.js

Like what Ludo said, set the nickname property directly in the socket:
// get the name of the sender
var name = socket.nickname;
console.log('Chat message by ', name);
console.log('error ', err);
sender = name;
and
// this kind of emit will send to all! :D
socket.nickname = name;
io.sockets.emit('chat', {
msg : "Welcome, " + name + '!',
msgr : "Nickname"
});

Related

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.io disconnects when refreshed?

I am trying to build a live chat, I am using mongodb and socket.io to store the messages and users.
When a new user is created that user is stored in the mongodb and in the socket object.
If a user refreshes the page the user is removed from the socket object, meaning now in order for that person to get back in they have to create a new username and that generates a new socket.
Here is what my server side code looks like
/*
|--------------------------------------------------------------------------
| Live socket communication with front end:
|--------------------------------------------------------------------------
|
|
*/
var users = {};
io.sockets.on('connection', function (socket) {
// Listen to a new user then emit the user to all clients
socket.on('new user', function (data) {
// Check mongodb to see if the user exists and emit proper message
models.Message.findOne({username:data},function(err,user){
if(err){
console.log('something went wrong')
}
else if(user){
socket.emit('username taken', 'something');
}
else{
socket.emit('create user', data);
socket.userName = data;
socket.connected = true;
users[socket.userName] = socket;
io.sockets.emit('user name', Object.keys(users));
}
});
});
socket.on('facebook id', function(data) {
models.User.findOne({username:data.name}, function(err, user) {
if (user) {
console.log('User already exists');
socket.userName = data.name;
socket.facebook_id = data.id;
socket.connected = true;
users[socket.userName] = socket;
io.sockets.emit('user name', Object.keys(users));
}
else {
var newUser = new models.User({
username: data.name,
facebook_id: data.id
});
newUser.save(function(err, user) {
console.log('successfully inserted user/user: ' + user._id);
});
}
});
});
// Listen to a new message then emit the message to all clients
socket.on('send message', function (data, callback) {
io.sockets.emit('new message', {message: data, username: socket.userName, facebook_id: socket.facebook_id});
});
// Logic when client disconnects
socket.on('disconnect', function (data) {
if(!socket.userName) return;
seeder.disconnect(socket.userName);
delete users[socket.userName]
io.sockets.emit('user disconnected', Object.keys(users));
});
});
You see in my disconnect I remove the socket from the users object.
My question would be is there a way to save the socket info on disconnect then if the same socket tries to connect have it recognize the user and continue?
Additonal: I am thinking maybe I need to focus on creating a user login with mongodb first, then using that log in session data and pass that to the socket, creating a socket object with current database details? Does that sound like something that makes more sense, is that possible?
You can use cookies to identify users. Generate a random hash, put it in cookies, and thus this data will be transferred when establishing connection between client and server.
The client code may look like:
function generateHash(len) {
var symbols = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
var hash = '';
for (var i = 0; i < len; i++) {
var symIndex = Math.floor(Math.random() * symbols.length);
hash += symbols.charAt(symIndex);
}
return hash;
}
if (!/\buser_id=/.test(document.cookie)) { //if no 'user_id' in cookies
document.cookie = 'user_id=' + generateHash(32); //add cookie 'user_id'
}
//here goes establishing connection to server via `io.connect`
On the server-side you can write:
io.sockets.on('connection', function (socket) {
var cookie = socket.handshake.headers.cookie;
var match = cookie.match(/\buser_id=([a-zA-Z0-9]{32})/); //parse cookie header
var userId = match ? match[1] : null;
//...
Thus you have userId variable which is unique for each user. Then you can comment this line:
delete users[socket.userName]
because you should keep the user data.
You may now store your users object with userId (not username) as a key, and on each connection check whether users[userId] != null. And if such user exists, use their socket info

Socket.io Private messaging, with multiple users online at the same time

So I am building, a chat app and need help figuring out how to send private messages. This is the code I have, to 'send a message'.
users = {}
socket.on('send message', function(data, callback){
var msg = data.trim();
console.log(users);
console.log('after trimming message is: ' + msg);
var name = req.params.posteruname;//reciever
var msg = msg;
if(name in users){
var message = new Chat({
msg : msg,
sender : req.user.username,
reciever : name
}).save(function(err, savedMessage){
if(err) {
users[name].emit('whisper', {msg: "Error, some tried sending you a message but something went wrong", nick: socket.nickname});
} else {
users[name].emit('whisper', {
reciever: name,
sender:req.user.username,
msg:msg
});
}
});
} else{
callback("Something went wrong");
}
});
This code isn't working very well. When I try to send message, it still displays to all users.
Take a look in this document. You should specify rooms. Every one will be a "room", when you send a message with event and room specified the correct user will receive it.
Your users object is just a plain object, don't reflect what I'm talking about.

Handle variables from multiple login for real-time chat

I'm writing a nodejs server that combine a login function and real-time chat. The problem came when I try to get all the users that logged in and connected with my real-time chat server then return to the client (so they can choose a specific user to chat with).
This is my code for log in function. I declared a variable so when client request the /doLogin, the username will be stored in it
var userLogged = {name: null, socketid: null};
app.post('/doLogin', function(req,res){
db.users.findOne({username: req.body.username}, function(err, user) {
if( err ) {
console.log("Login fail");
}
else if (user != null) {
if (req.body.password == user.password) {
req.session.user_role = "user";
userLogged.name = req.body.username;
} else {
req.session.user_role = "null";
}
}
res.send({redirect: "/"});
});
});
And in real-time chat function (using Socket.io), when user connect (after logged in), I will store the socket.id into the variable before, and save that variable in mongodb.
io.sockets.on('connection', function(socket){
var address = socket.handshake.address;
userLogged.socketid = socket.id;
db.clientList.save({name: userLogged.name, socketid: userLogged.socketid}, function(err, saved){
});
console.log("Connection " + address.address + " accepted.");
//
//
socket.on('disconnect', function(){
db.clientList.remove({socketid: userLogged.socketid});
});
});
And the problem is, when other users log in, the variable change so I cannot save the right information in to database.
Please help me!
socket.io allow you to read cookies:
// app.js
io = io.listen(server);
io.set('authorization', function (handshakeData, accept) {
handshakeData.cookie = cookie.parse(handshakeData.headers.cookie);
});
the right way to do is:
cookies --> sessionID --> user --> username
document: http://howtonode.org/socket-io-auth
More simple:
if security is not important to you, you can set username to cookie, then you read username in easily in server: cookies->username
// login handler
res.cookie('username', username)
res.send({redirect: "/"});
// io connection handler
io = io.listen(server);
io.set('authorization', function (handshakeData, accept) {
console.log(handshakeData.headers.cookie)
}
note that, any web user can change their own cookie to fake your name, so this is for test, you should NOT use this for production.

socket.io returns [object Object] from mongojs query

I've started looking at socket.io and some MongoDB with mongojs.
Summary: Client doesn't send data to server through socket.io so mongojs doesn't have anything to look for and just returns first document in collection, I'd like it to return null or false so I can take appropriate action.
Any help appreciated, very new to node.js and this.
I need a log in function, but when I click the link I've made to log in this should run from the client:
<script>
var socket = io.connect('http://localhost:13163');
socket.on('connect', function () {
socket.emit(console.log('Client connected'));
});
socket.on('queryResponse', function (res, err) {
if (res == "[object Object]") {
console.log('EMPTY OBJ SERVER: ' + res + ' ' + err);
}
else{
console.log('IF NOT EXEC' + res[0].email)
}
});
//socket.send('client hello');
//pageload
$(function () {
$('#login').click(function () {
var username = $('#username').val();
var password = $('#password').val();
if (!username || !password) {
event.preventDefault();
console.log('Need data in both fields');
}
else {
event.preventDefault();
socket.emit('querydata', function (username, password) {
console.log("CLIENT: Querying server for data...");
});
}
});
});
</script>
This should send the username and password to the server which should then run this:
socket.on('querydata', function (user_username, user_password) {
db.users.find({email: user_username, pass: user_password}, function (err, docs) {
if (err || !docs) {
socket.emit('queryResponse', 'No users found', err);
console.log('if - ' + docs[0].email);
}
else {
socket.emit('queryResponse', docs);
console.log('else - ' + docs[0].email + 'user_password' + user_password + 'user_username' + user_username);
}
});
});
What's weird about this is that, it finds only the first document of the collection.
I've just found out that the 'user_username' and 'user_password' overloads are undefined, is this just some retarded mistake from my side?
You are doing it wrong. In a first look, i see couple of mistakes in your code.
The first one here
if (res == "[object Object]")
You can not control response content in that way. You probably see [object Object] string in your javascript debugger. You have to do this comparison according to the server response as a json data. If it will lead you a trouble you can use JSON.parse(response).
The second one, you do not send username and password to the server actually. You have to use
socket.emit('querydata', { username: username, password: password }, function (data) {
// Server Ack here
}
instead of
socket.emit('querydata', function (username, password) ...
And try this
socket.emit('queryResponse', {err: 'No User Found'});
instad of
socket.emit('queryResponse', 'No User Found', err);
And in your client check the response as
if(response.hasOwnProperty('err')) / /Handle error
In you client side queryResponse listener, try this;
socket.on('queryResponse', function (res) {
if(res.hasOwnProperty('err')) / Handle Error
else // You have an array in `res`
});

Resources