Socket not saving data inside handshake object? - javascript

I am trying to save session data inside a handshake object from io.set('authorization')
var io = sio.listen(server);
io.set('authorization', function (handshake, callback) {
if(handshake.headers.cookie) {
var cookies = cookie.parse(handshake.headers.cookie);
var sid = cookieParser.signedCookie(cookies['xygaming'], secrets.sessionSecret);
sessionStore.load(sid, function(err, session) {
if(err || !session) {
return callback('Error retrieving session!', false);
}
// this is not storing the data into the handshake object
handshake.balloons = {
user: session.passport.user,
room: /\/(?:([^\/]+?))\/?$/g.exec(handshake.headers.referer)[1]
};
return callback(null, true);
});
} else {
return callback('No cookie transmitted.', false);
}
});
I have an adapter for pub sub
io.adapter(redisIo({
host: 'localhost',
port: 6379,
pubClient: pub, // just redis.createClient()
subClient: sub // just redis.createClient()
}));
Then I want to access the handshake data inside the io.sockets.on('connection') but its not there? Any idea why its not passing? In the original repo it works on express 3x, but since I upgraded to 4x and made some modifications of my own it does not pass through?
io.sockets.on('connection', function (socket) {
console.log(socket.handshake);
// I want to pass the handshake data here, but its undefined??
var hs = socket.handshake
, nickname = hs.balloons.user.username
, provider = hs.balloons.user.provider
, userKey = provider + ":" + nickname
, room_id = hs.balloons.room
, now = new Date()
// Chat Log handler
, chatlogFileName = './chats/' + room_id + (now.getFullYear()) + (now.getMonth() + 1) + (now.getDate()) + ".txt"
// , chatlogWriteStream = fs.createWriteStream(chatlogFileName, {'flags': 'a'});
socket.join(room_id);
});

Related

Allow only one connection at a time in websocket

When someone connect to my websocket , I want the last opened connection to be active and close all other old connections.Every users has unique token.Following is the code I created
wss.on('connection', function connection(ws,req) {
const myURL = new URL("https://example.com"+req.url);
var token = myURL.searchParams.get('token');
ws.send("success");
exists = users.hasOwnProperty(token);
if(exists)
{
//console.log("Token exists already");
// ws.send("fail");
// ws.close();
users[token]["ws"].send("fail");
users[token]["ws"].close();
users[token] = [];
users[token]["ws"] = ws;
}
else
{
users[token] = [];
users[token]["ws"] = ws;
//console.log('connected: ' + token + ' in ' + Object.getOwnPropertyNames(users));
}
ws.on('close', function () {
delete users[token]
//console.log('deleted: ' + token);
})
});
But above code works only first time , If I open third time both 2nd and 3rd connection is live.I want to close the 2nd and keep the 3rd alive.Any help is appreciated Thank you.
You probably meant to use an object instead of array
so
users[token] = {};
instead of
users[token] = [];
I would close all other connections when a new connection comes so new connection handler is something like this
wss.on('connection', function connection(ws, req) {
const myURL = new URL("https://example.com" + req.url);
var token = myURL.searchParams.get('token');
ws.send("success");
exists = users.hasOwnProperty(token);
for(const token in users){ // close all existing connections
users[token]["ws"].send("fail");
users[token]["ws"].close();
}
if (exists) {
users[token]["ws"] = ws; // update websocket
}
else {
users[token] = {ws: ws}; // add new websocket to users
// same thing as
// users[token] = {}
// users[token]["ws"] = ws
}
}

Socketio 1.0 get attributes from all clients

I am currently working on a simple socketio application in which i am sending some parameters to envents and i am storing them into each socket.
socket.on('add user', function (data) {
if (addedUser) return;
// we store the username in the socket session for this client.
socket.nickname = data.nickname;
socket.userId = data.userId;
...
Then i am getting all socketio clients using var io.engine.clients and i am trying to obtain that parameters in other event like this:
socket.on('new message', function (data) {
var clientsRoom = io.engine.clients;
for(var c in clientsRoom){
console.log(" Client: " + c.userId); //Error
console.log(" Client: " + c); //outputs the socket ID
console.log(" Client: " + c['userId']); //Error
}
...
but i am unable to get my userID previously stored for all sockets. ¿What am i doing wrong?
Thanks.
Instead of io.engine.clients, you should use io.sockets.sockets (they aren't the same, socket.io adds an extra layer on top of engine.io). Also make sure that you treat it as an object, not an array:
var clientsRoom = io.sockets.sockets;
for (var id in clientsRoom) {
var c = clientsRoom[id];
console.log(" Client: " + c.userId);
console.log(" Client: " + id);
}

Updating retrieved data from a Mysql Query? Node.js node-mysql

I am currently working on a socket.io-client/socket.io login system, the problem is when I start the server, a query is performed, retrieving the current data in the database, if a user registers they are not able to login until the server is restarted, if I use:
SELECT * FROM mytable ORDER BY id DESC LIMIT 1
Then only the user that just registered can login, and not users that are already registered, how can I resolve this issue?
I have it so when the username and passwords are submitted from the client to the server, the function containing the Mysql code is performed, logically I thought this would run the query again for each new connection, but it doesn't.
My Code:
Server:
console.log("Berdio - A Awesome socket server for everyone!")
console.log("Created with Love, by OzzieDev! Enjoy the awesomeness!")
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
function dosql(){
var mysql = require('mysql')
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'Berd'
})
connection.query('SELECT * FROM Berd_Data', function(err, rows, fields, result){
if (err) throw err;
var usrname = rows[0].Username
var psword = rows[0].Password
global.usrname = usrname
global.psword = psword
});
}
io.on('connection', function(socket){
})
socket.on('user-name', function(data){
dosql()
socket.broadcast.emit('user-connected',data.u);
console.log(u,p)
var u = data.u
var p = data.p
console.log(u,p + " " + "emitted Data");
if (u === global.usrname && p === global.psword){
socket.emit('AuthGood')
}else{
socket.emit('AuthFail')
}
socket.on('msg',function(data){
var message = data.message
if (typeof message !== "undefined"){
socket.broadcast('newmsg',msg)
}
if(message === "quit"){
process.exit();
}
})
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Client:
var socket = require('socket.io-client')('http://127.0.0.1:3000');
socket.on('connect_error', function(){
console.log('Failed to establish a connection to the servers, or lost connection');
return process.exit();
});
var prompt = require("prompt-sync")()
console.log("Your Ip has been logged, but encrypted. Please see website for more info")
var news = "Add news: Will be from database. "
var username = prompt("Username>: ")
var password = prompt("Password>: ")
if (typeof username, password !== "undefined"){
socket.emit('request')
socket.emit('user-name', { u: username, p: password });
}
socket.on('AuthGood',function(socket){
console.log("Your details have been authenticated, hello again!")
var message = prompt("message>: ")
})
socket.on('AuthFail',function(socket){
console.log("Your details failed to authenticate, Wrong Pass/Username combination, quitting!")
return process.exit();
})
if (typeof message !== "undefined"){
socket.emit('msg',{m: message})
}
socket.on('user-connected',function(data){
var userconn = data.username
console.log(username +" " +"Has joined us!")
})
socket.on('newmsg',function(data){
var newmsg = data.msg
console.log("-----------------------------------")
console.log(username+">:" + " " +msg)
})
Using MySql query:
SELECT * FROM Berd_Data WHERE `Username` = ?', [u]
Fixed the issue.

Websockets: send messages and notifications to all clients except sender

I am developing chat based on websockets and webrtc. I would like to send messages to all connected users except sender but I cannot find suitable solution. To be more specific, I would like to send notifications to other connected users that new user has joined to the chat.
I am trying to give a unique ID to every connected user, but the first assigned ID is re-writed by every new user and I cannot diferentiate users.
Server:
// list of users
var CLIENTS=[];
var id;
// web server is using 8081 port
var webSocketServer = new WebSocketServer.Server({ port: 8081 });
// check if connection is established
webSocketServer.on('connection', function(ws) {
id = Math.random();
CLIENTS[id] = ws;
CLIENTS.push(ws);
ws.on('message', function(message) {
console.log('received: %s', message);
var received = JSON.parse(message);
if(received.type == "login"){
ws.send(message); // send message to itself
/* *********************************************************** */
/* *** Here I trying to check if message comes from sender *** */
sendNotes(JSON.stringify({
user: received.name,
type: "notes"
}), ws, id);
/* *********************************************************** */
}else if(received.type == "message"){
sendAll(message); // broadcast messages to everyone including sender
}
});
ws.on('close', function() {
console.log('user ' + CLIENTS[ws] + ' left chat');
delete CLIENTS[ws];
});
});
function sendNotes(message, ws, id) {
console.log('sendNotes : ', id);
if (CLIENTS[id] !== ws) {
console.log('IF : ', message);
for (var i = 0; i < CLIENTS.length; i++) {
CLIENTS[i].send(message);
}
}else{
console.log('ELSE : ', message);
}
}
function sendAll(message) {
for (var i=0; i < CLIENTS.length; i++) {
CLIENTS[i].send(message); // broadcast messages to everyone including sender
}
}
Client:
loginButton.addEventListener("click", function(){
name = usernameInput.value;
if(name.length > 0){
socket.send(JSON.stringify({
type: "login",
name: name
}));
}
});
function sendData() {
var data = dataChannelSend.value;
var userName = document.getElementById('greetingUser').innerHTML;
socket.send(JSON.stringify({
username : userName, // fetch user name from browser, after login
type : "message",
message : data
}));
}
socket.onmessage = function(message) {
var envelope = JSON.parse(message.data);
switch(envelope.type) {
case "login":
onLogin(envelope);
break;
case "message":
showMessage(envelope);
break;
}
};
I would highly appreciate If you could give me any hint. Thanks
Here is a very simple way of sending to everyone connected except the sender.
Create a broadcast function on your webSocketServer instance that will
take two params.
...
var webSocketServer = new WebSocketServer.Server({ port: 8081 });
...
/*
* method: broadcast
* #data: the data you wanna send
* #sender: which client/ws/socket is sending
*/
webSocketServer.broadcast = function(data, sender) {
webSocketServer.clients.forEach(function(client) {
if (client !== sender) {
client.send(data)
}
})
}
...
// On your message callback.
ws.on('message', function(message) {
...
// Note that we're passing the (ws) here
webSocketServer.broadcast(message, ws);
})
That's it, the broadcast method will send to each connected client
except the one who is sending.
Ok, so we are now storing the CLIENTS in a way that allows us to uniquely identify each client that is connecting, and store arbitrary information about them for later retrieval.
The code below will send the "notes" message to all clients, and THEN add the newly connecting client to the "all clients" list.
SERVER.JS:
var http = require('http'),
Static = require('node-static'),
WebSocketServer = new require('ws'),
// list of users
/*
We are now storing client data like this:
CLIENTS = {
uniqueRandomClientID: {
socket: {}, // The socket that this client is connected on
clientDetails: { // Any details you might wish to store about this client
username: "",
etc: "etc"
}
}
};
So now to get at the socket for a client, it'll be: CLIENTS[uniqueRandomClientID].socket.
Or to show a client's username, it'll be: CLIENTS[uniqueRandomClientID].clientDetails.username.
You might want to write a 'getClientByUsername' function that iterates the CLIENTS array and returns the client with that username.
*/
CLIENTS = {},
// web server is using 8081 port
webSocketServer = new WebSocketServer.Server({ port: 8081 });
// check if connection is established
webSocketServer.on('connection', function(ws) {
console.log('connection is established');
// Now using a randomly generated ID to reference a client. Probably should be better than Math.random :D
var wsID = Math.floor(Math.random() * 1000);
ws.on('message', function(message) {
console.log('received: %s', message);
var received = JSON.parse(message);
if(received.type == "login"){
// If a client with this login name doesnt exist already, its a new client
if(!CLIENTS[wsID]) {
doBroadcast(
{
"newuser": received.name,
type: "notes"
}
);
// Now add this new client to the list
CLIENTS[wsID] = {
socket: ws,
clientDetails: {
username: received.name
}
};
}
} else if(received.type == "message") {
doBroadcast(message); // broadcast messages to everyone including sender
}
});
ws.on('close', function(_event) {
if(CLIENTS[wsID]) {
console.log('user ' + CLIENTS[wsID].clientDetails.username + ' left chat');
delete CLIENTS[wsID];
}
});
/*
* Added this to 'catch' errors rather than just red dump to console. I've never actually done anything with this myself (I *like* red text in my console), but I know this handler should be here :P
*/
ws.on('error', function(_error) {
console.log("error!");
console.log(_error);
});
/*
* Send an object to a client
*
* #param WebSocketClient _to - The client you want to send to (generally an index in the CLIENTS array, i.e CLIENTS["bobsusername123"]
* #param Object _message - A stringifyable JSON object. Complex ones can screw things up, but your basic key/value pairs are usually fine to send.
*/
function doSend(_to, _message) {
_to.send(JSON.stringify(_message));
};
// Added broadcast function to replace sendAll
// Notice how it JSON stringifies the data before sending
/*
* Broadcast a message to all clients
*
* #param Object _message - A stringifyable JSON object. Complex ones can screw things up, but your basic key/value pairs are usually fine to send.
*/
function doBroadcast(_message) {
for(var client in CLIENTS) {
if(!CLIENTS.hasOwnProperty(client)) continue;
doSend(CLIENTS[client].socket, _message);
}
};
});
var fileServer = new Static.Server('.');
http.createServer(function (req, res) {
fileServer.server(req, res);
}).listen(8080, function(){
console.log("Server is listening 8080 port.");
});
console.log("Server is running on 8080 and 8081 ports");
MY CLIENT.JS (for your reference):
var loginButton = document.getElementById("loginbutton"),
usernameInput = document.getElementById("usernameInput");
var SocketClient = function(_uri, _callbacks) {
this.uri = _uri;
this.callbacks = _callbacks;
};
SocketClient.prototype = {
send: function(_message) {
this.socket.send(_message);
},
connect: function() {
try {
this.socket = new WebSocket("ws://" + this.uri);
} catch(e) { return false; }
for(var callback in this.callbacks) {
if(!this.callbacks.hasOwnProperty(callback)) continue;
this.socket["on" + callback] = this.callbacks[callback];
}
return true;
}
};
var socketClient = new SocketClient(
"127.0.0.1:8081",
{
open: function() {
console.log("connected.");
},
message: function(_message) {
console.log("received data:");
console.log(_message);
},
close: function() {
console.log("closed.");
},
error: function(_error) {
console.log("error: ");
console.log(_error);
}
}
);
socketClient.connect();
loginButton.addEventListener("click", function(){
name = usernameInput.value;
if(name.length > 0){
socketClient.send(JSON.stringify({
type: "login",
name: name
}));
}
});
AND THE CLIENT.HTML TO GO WITH IT:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<input type="text" id="usernameInput"/>
<button type="button" id="loginbutton">Login</button>
<script src="client.js"></script>
</body>
</html>
Ive tested this with NWJS v0.12.3 running the server and Firefox on the client.
This should work
const WebSocket = require('ws');
// Websocket variables
const wss = new WebSocket.Server({
port: 3000
});
console.log('Websocket active on port 3000...');
// New WebSocket Connection
wss.on('connection', function connection(ws) {
console.log('new connection')
// On Message Received
ws.on('message', function incoming(message) {
console.log(message)
// Send To Everyone Except Sender
wss.clients.forEach(function(client) {
if (client !== ws) client.send(message);
});
});
});

Express JS 'this' undefined after routing with app.get(..)

I have a basic Node JS server which is designed to be used as an API, I've created a log and database module and I've started adding other modules to deal with different request types.
I'm using Express.js and node-mysql
When I visit /v1/group I get the following error -
TypeError: Cannot read property 'database' of undefined
at Group.getAll (C:\code\javascript\node\api\api\v1\groups.js:12:23)
at callbacks (C:\code\javascript\node\api\node_modules\express\lib\router\index.js:161:37) ...
So I guess after recieving a request and calling group.getAll() that this is undefined but I don't understand why, is there a way to set this or have I structured my application all wrong?
sever.js
"use strict";
var Express = require('express');
var Log = require('./database/log');
var Database = require('./database/database');
var dbConfig = require('./dbconfig.json');
var Group = require('./api/v1/groups');
//Init express
var app = new Express();
//Init log and database
var log = new Log();
var database = new Database(dbConfig, log);
var initCallback = function() {
//Init routes
var group = new Group(database, log);
//Group routes
app.get('/v1/group', group.getAll);
app.get('/v1/group/:id', group.getByID);
app.listen(3000);
log.logMessage("INFO", "Listening on port 3000");
};
//Test database connection
database.getConnection(function(err, connection) {
if (err) {
log.logMessage("FATAL", "Error connecting to database, check database is running and the dbconfig.json file is present and correct.");
process.exit(1);
}
connection.end();
initCallback();
});
database.js
"use strict";
var mysql = require('mysql');
var Database = function(dbConfig, log) {
this.connected = false;
this.log = log;
this.log.logMessage("INFO", "Connecting to database with: Host - " + dbConfig.dbhost + ", Database port - " + dbConfig.dbport + ", Database name - " + dbConfig.dbname + ", User " + dbConfig.dbuser + ", Password length - " + dbConfig.dbpass.length);
this.pool = mysql.createPool({
host : dbConfig.dbhost,
user : dbConfig.dbuser,
port: dbConfig.dbport,
password : dbConfig.dbpass,
database: dbConfig.dbname
});
};
Database.prototype.getConnection = function() {
var args = arguments;
return this.pool.getConnection.apply(this.pool, arguments);
};
module.exports = Database;
groups.js
"use strict";
var Group = function(database, log) {
this.database = database;
this.log = log;
};
Group.prototype.getAll = function(req, res) {
console.log(this); // --> undefined
var query = 'SELECT * FROM invgroups WHERE published = 1';
this.database.getConnection(function(err, connection) { // --> error line
if (err) { res.send(500, "Database error"); }
connection.query(query, function(err, results) {
if (err) { res.send(500, "Database error"); }
res.send(results);
});
connection.end();
});
};
Group.prototype.getByID = function(req, res) {
console.log(this);
res.send({name: "Group Item 1"});
};
module.exports = Group;
You need to properly bind the function.
app.get('/v1/group', group.getAll);
only passes the getAll function as a handler, but the function itself has no concept of this. this is decided based on the context that is bound, or based on how the function is called. This blog post is useful for understanding how function context works.
app.get('/v1/group', group.getAll.bind(group));

Categories