How to access session in express, outside of the req? - javascript

I know that I can use
function(req, res) {
req.session
}
using express. However I need to access the session outside of the response function. How would I go about doing that?
I'm using socket.io to pass information for adding posts and comments. So when I receive the socket.io message on the server-side, I need to verify the person posting the information by using the session. However since this is being done via socket.io there is no req/res.

I think I have a different answer.
code:
var MongoStore = require('connect-mongo')(session);
var mongoStore = new MongoStore({
db:settings.db, //these options values may different
port:settings.port,
host:settings.host
})
app.use(session({
store : mongoStore
//here may be more options,but store must be mongoStore above defined
}));
then you should define a session key at req,just like :
code:
req.session.userEmail;
finally,you can get it this way:
code:
var cookie = require("cookie"); //it may be defined at the top of the file
io.on("connection",function(connection){
var tS = cookie.parse(connection.handshake.headers.cookie)['connect.sid'];
var sessionID = tS.split(".")[0].split(":")[1];
mongoStore.get(sessionID,function(err,session){
console.log(session.userEmail);
});
}
I had test it yesterday, it worked well.

Using socket.io, I've done this in a simple way. I assume you have an object for your application let's say MrBojangle, for mine it's called Shished:
/**
* Shished singleton.
*
* #api public
*/
function Shished() {
};
Shished.prototype.getHandshakeValue = function( socket, key, handshake ) {
if( !handshake ) {
handshake = socket.manager.handshaken[ socket.id ];
}
return handshake.shished[ key ];
};
Shished.prototype.setHandshakeValue = function( socket, key, value, handshake ) {
if( !handshake ) {
handshake = socket.manager.handshaken[ socket.id ];
}
if( !handshake.shished ) {
handshake.shished = {};
}
handshake.shished[ key ] = value;
};
Then on your authorization method, I'm using MongoDB for session storage:
io.set('authorization', function(handshake, callback) {
self.setHandshakeValue( null, 'userId', null, handshake );
if (handshake.headers.cookie) {
var cookie = connect.utils.parseCookie(handshake.headers.cookie);
self.mongoStore()
.getStore()
.get(cookie['connect.sid'], function(err, session) {
if(!err && session && session.auth && session.auth.loggedIn ) {
self.setHandshakeValue( null,
'userId',
session.auth.userId,
handshake );
}
});
}
Then before saving a record in the model, you can do:
model._author = shished.getHandshakeValue( socket, 'userId' );

I believe checking socket.handshake should get you the session:
io.sockets.on('connection', function(socket) {
console.log(socket.handshake.sessionID);
});
When the client establishes a socket connection with your socket.io server, the client sends a WebSocket handshake request. What I'm doing above is grabbing the session ID from the handshake.

Assuming your socket.io code looks kinda like this:
io.on('connection',
function(client) {
console.log(client.request)
});
The request is client.request as shown in the example above.
Edit:
As a separate thing, maybe this would help:
https://github.com/aviddiviner/Socket.IO-sessions

Related

identifying users upon some action or disconnected

I'm new to node
I have a PHP/Laravel cms and I have a simple Nodejs game server which is basically a loop generating some numbers
I connect my PHP backend to Nodejs via Socketio and use Socketio-JWT to identify the user
my client side (php/laravel)
PHP
$userToken = JWTAuth::customClaims(['userid' => Auth::user()->id, 'name' => Auth::user()->name, 'avatar' => asset_url('image/avatar-default.png')])->fromUser(Auth::user() );
html/js
var socket = io.connect("http://localhost:666");
socket.on('connect', function () {
socket.emit('authenticate', {token: '{{$userToken}}'});
});
socket.on('authenticated', function () {
console.log('Authenticated');
});
socket.on('unauthorized', function (data) {
console.log('Unauthorized, error msg: ' + data.message);
});
my serverside
const _online_users = { };
io.sockets
.on('connection', socketioJwt.authorize({
secret: JWT_SECRET,
timeout: 15000
}))
.on('authenticated', function(socket) {
_online_users[socket.decoded_token.userid] = {
name : socket.decoded_token.name ,
avatar : socket.decoded_token.avatar ,
}
io.sockets.emit('update_online_users' , _online_users );
socket.on('disconnect', function() {
console.log(`----- ##disconnect -----`)
});
}) ;
as you can see I have an object called _online_users and I store authenticated users in this object and then I send it to the clients so they know who is online
io.sockets.emit('update_online_users' , _online_users );
here is the problem, when the user gets disconnected
socket.on('disconnect', function() {
console.log(`----- ##disconnect -----`)
});
I have to update my _online_users object and remove disconnected user .... how should I go about this? I was thinking maybe I can store the token itself in the _online_users
_online_users[socket.decoded_token.userid] = {
token : socket.token ,
name : socket.decoded_token.name ,
avatar : socket.decoded_token.avatar ,
}
and when the user gets disconnected I get the disconnected token from the socket and remove the user from an object by that token
of course, this is all theory! I'm not sure if that's the way to go .... first of all, I can't access the token itself from the socket !
or let's say one of the users sends another request to node server, how can I identify the user sending the request?
.on('authenticated', function(socket) {
socket.on('somaction', function() {
console.log(` who is this guy ? `)
});
})
is there anything unique insocket.decoded_token that I can use as id? if so I can store it in the online users send it back and forth when the user requests something
basically I'm lost and appreciate any pointers
You can use a middleware now in the newer versions of socket-io. So you can check if the user is logged in by the jwt token that is sent with the request. If decoded successfully you can assign the user info to the current socket and call next() and go to the event you are listening for. Here is the example provided in the socket-io docs slightly modified for your case.
io.use(function(socket, next) {
const handshakeData = socket.request;
// make sure the handshake data looks good as before
// if error do this:
// next(new Error('not authorized'));
// else decode jwt token here and append the user to the socket.request
// and call next
// pseudo code here
const {
authorization
} = handshakeData.header
let token;
if (authorization && authorization.split(" ")[0] === "Bearer") {
token = authorization.split(" ")[1]
}
let user = jwt.decode(token, secret);
socket.request.user = user;
next();
});
You are doing well!
Since you are adding socket event handlers in the 'authenticated' handler you still have access to socket.decoded_token.userid.
This should be enough:
const _online_users = {};
io.sockets
.on('connection', socketioJwt.authorize({
secret: JWT_SECRET,
timeout: 15000
}))
.on('authenticated', function(socket) {
_online_users[socket.decoded_token.userid] = {
name: socket.decoded_token.name,
avatar: socket.decoded_token.avatar,
};
io.sockets.emit('update_online_users', _online_users);
socket.on('disconnect', function() {
console.log(`----- ##disconnect -----`);
delete _online_users[socket.decoded_token.userid];
io.sockets.emit('update_online_users', _online_users);
});
});
or to be a little more concise:
const _online_users = {};
io.sockets
.on('connection', socketioJwt.authorize({
secret: JWT_SECRET,
timeout: 15000
}))
.on('authenticated', function(socket) {
const { avatar, name, userid } = socket.decoded_token;
_online_users[userid] = { name, avatar };
io.sockets.emit('update_online_users', _online_users);
socket.on('disconnect', function() {
delete _online_users[userid];
io.sockets.emit('update_online_users', _online_users);
});
socket.on('any other event...', function() {
// ... still have access to userid
});
});
Edit: About unauthenticated socket I don't know; doc says nothing. You could try something like:
io.socket.on('connection', socket => {
socket.emit('update_online_users', _online_users);
// I'm afraid this closes the socket if unauthorized, you could check by yourself
socketioJwt.authorize({
secret: JWT_SECRET,
timeout: 15000
})(socket);
}).on('authenticated', socket => {
//...
});
Hope this helps.

Emiting websocket message from routes

I'm trying to setup my server with websockets so that when I update something via my routes I can also emit a websocket message when something on that route is updated.
The idea is to save something to my Mongo db when someone hits the route /add-team-member for example then emit a message to everyone who is connected via websocket and is a part of whatever websocket room that corresponds with that team.
I've followed the documentation for socket.io to setup my app in the following way:
App.js
// there's a lot of code in here which sets what to use on my app but here's the important lines
const app = express();
const routes = require('./routes/index');
const sessionObj = {
secret: process.env.SECRET,
key: process.env.KEY,
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
secret : 'test',
cookie:{_expires : Number(process.env.COOKIETIME)}, // time im ms
}
app.use(session(sessionObj));
app.use(passport.initialize());
app.use(passport.session());
module.exports = {app,sessionObj};
start.js
const mongoose = require('mongoose');
const passportSocketIo = require("passport.socketio");
const cookieParser = require('cookie-parser');
// import environmental variables from our variables.env file
require('dotenv').config({ path: 'variables.env' });
// Connect to our Database and handle an bad connections
mongoose.connect(process.env.DATABASE);
// import mongo db models
require('./models/user');
require('./models/team');
// Start our app!
const app = require('./app');
app.app.set('port', process.env.PORT || 7777);
const server = app.app.listen(app.app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
const io = require('socket.io')(server);
io.set('authorization', passportSocketIo.authorize({
cookieParser: cookieParser,
key: app.sessionObj.key, // the name of the cookie where express/connect stores its session_id
secret: app.sessionObj.secret, // the session_secret to parse the cookie
store: app.sessionObj.store, // we NEED to use a sessionstore. no memorystore please
success: onAuthorizeSuccess, // *optional* callback on success - read more below
fail: onAuthorizeFail, // *optional* callback on fail/error - read more below
}));
function onAuthorizeSuccess(data, accept){}
function onAuthorizeFail(data, message, error, accept){}
io.on('connection', function(client) {
client.on('join', function(data) {
client.emit('messages',"server socket response!!");
});
client.on('getmessage', function(data) {
client.emit('messages',data);
});
});
My problem is that I have a lot of mongo DB save actions that are going on in my ./routes/index file and I would like to be able to emit message from my routes rather than from the end of start.js where socket.io is connected.
Is there any way that I could emit a websocket message from my ./routes/index file even though IO is setup further down the line in start.js?
for example something like this:
router.get('/add-team-member', (req, res) => {
// some io.emit action here
});
Maybe I need to move where i'm initializing the socket.io stuff but haven't been able to find any documentation on this or perhaps I can access socket.io from routes already somehow?
Thanks and appreciate the help, let me know if anything is unclear!
As mentioned above, io is in your global scope. If you do
router.get('/add-team-member', (req, res) => {
io.sockets.emit('AddTeamMember');
});
Then every client connected, if listening to that event AddTeamMember, will run it's associated .on function on their respective clients. This is probably the easiest solution, and unless you're expecting a huge wave of users without any plans of load balancing, this should be suitable for the time being.
Another alternative you can go:
socket.io lib has a rooms functionality where you can join and emit using the io object itself https://socket.io/docs/rooms-and-namespaces/ if you have a knack for this, it'd look something like this:
io.sockets.in('yourroom').broadcast('AddTeamMember');
This would essentially do the same thing as the top, only instead of broadcasting to every client, it'd only broadcast to those that are exclusive to that room. You'd have to basically figure out a way to get that users socket into the room //before// they made the get request, or in other words, make them exclusive. That way you can reduce the amount of load your server has to push out whenever that route request is made.
Lastly, if neither of the above options work for you, and you just absolutely have to send to that singular client when they initiate it, then it's going to get messy, because you have to have some sort of id to that person, and since you have no reference, you'd have to store all your sockets upon connection, and then make a comparison. I do not fully recommend something like this, because well, I haven't ever tested it, and don't know what type of repercussions could happen, but here is a jist of an idea I had:
app.set('trust proxy', true)
var SOCKETS = []
io.on('connection', function(client) {
SOCKETS.push(client);
client.on('join', function(data) {
client.emit('messages',"server socket response!!");
});
client.on('getmessage', function(data) {
client.emit('messages',data);
});
});
router.get('/add-team-member', (req, res) => {
for (let i=0; i< SOCKETS.length; i++){
if(SOCKETS[i].request.connection.remoteAddress == req.ip)
SOCKETS[i].emit('AddTeamMember');
}
});
Keep in mind, if you do go down this route, you're gonna need to maintain that array when users disconnect, and if you're doing session management, that's gonna get hairy really really quick.
Good luck, let us know your results.
Yes, it is possible, you just have to attach the instance of socket.io as long as you get a request on your server.
Looking to your file start.js you just have to replace your functions as:
// Start our app!
const app = require('./app');
app.app.set('port', process.env.PORT || 7777);
const io = require('socket.io')(app.app);
const server = app.app.listen(app.app.get('port'), () => {
server.on('request', function(request, response){
request.io = io;
}
console.log(`Express running → PORT ${server.address().port}`);
});
now when you receive an event that you want to emit some message to the clients you can use your io instance from the request object.
router.get('/add-team-member', (req, res) => {
req.io.sockets.emit('addteammember', {member: 6});
//as you are doing a broadcast you just need broadcast msg
....
res.status(200)
res.end()
});
Doing that i also were able to integrate with test framework like mocha, and test the events emited too...
I did some integrations like that, and in my experience the last thing to do was emit the msg to instances in the socket.
As a good practice the very begining of middleware functions i had were doing data validation, data sanitization and cleaning data.
Here is my working example:
var app = require('../app');
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.on('connection', function(client) {
client.emit('connected');
client.on('disconnect', function() {
console.log('disconnected', client.id);
});
});
server.on('request', function(request, response) {
request.io = io;
});
pg.initialize(app.config.DATABASEURL, function(err){
if(err){
throw err;
}
app.set('port', process.env.PORT || 3000);
var server1 = server.listen(app.get('port'), function(){
var host = 'localhost';
var port = server1.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
});
Your io is actually the socket object, you can emit events from this object to any specific user by -
io.to(userSocketId).emit('eventName', data);
Or you can broadcast by -
io.emit('eventName', data);
Just create require socket.io before using it :)
You can use emiter-adapter to emit data to client in other process/server. It use redis DB as backend for emitting messages.
I did something similar in the past, using namespaces.
Let's say your client connect to your server using "Frontend" as the namespace.
My solution was to create the instance of socket.io as a class in a separate file:
websockets/index.js
const socket = require('socket.io');
class websockets {
constructor(server) {
this.io = socket(server);
this.frontend = new Frontend(this.io);
this.io.use((socket, next) => {
// put here the logic to authorize your users..
// even better in a separate file :-)
next();
});
}
}
class Frontend {
constructor(io) {
this.nsp = io.of('/Frontend');
[ ... ]
}
}
module.exports = websockets;
Then in App.js
const app = require('express')();
const server = require('http').createServer(app);
const websockets = require('./websockets/index');
const WS = new websockets(server);
app.use('/', (req, res, next) => {
req.websocket = WS;
next();
}, require('./routes/index'));
[ ... ]
Finally, your routes can do:
routes/index.js
router.get('/add-team-member', (req, res) => {
req.websocket.frontend.nsp.emit('whatever', { ... });
[ ... ]
});

express-session won't set cookie connect.sid

EDIT 5
I have back and front end running on LAMP environment accesible with 192.168.80.213/backend adress.
I try to make a push notification server using nodejs, socket.io and express framework to link back and front end.
My nodejs server is listening on port 3000 while my backend and front end listenning on port 80 both using apache.
Here is my node client :
<script type="text/javascript" src="socket.io-1.4.5.js"></script>
<script type="text/javascript">
var socket = io('http://192.168.80.213:3000/');
</script>
Here is my node server :
const express = require('express')
, app = express()
, http = require('http').Server(app)
, socketIo = require('socket.io')(http)
, cookieParser = require('cookie-parser')
, cookie = require('cookie')
, connect = require('connect')
, expressSession = require('express-session')
, port = 3000
, helmet = require('helmet')
, name = 'connect.sid'
, sessionStore = new expressSession.MemoryStore({ reapInterval: 60000 * 10 })
, sessionSecret = 'VH6cJa7yZSmkRbmjZW#J3%CDn%dt'
, environment = process.env.NODE_ENV || 'development'
;
/** Configuration **/
app.enable('trust proxy');
app.disable('x-powered-by');
app.use(helmet());
app.use(cookieParser());
app.use(expressSession({
'name' : name,
'secret': sessionSecret,
'store' : sessionStore,
'resave': true,
'saveUninitialized': true
}));
app.get('/', function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello from node');
});
socketIo.use(function(socket, callback) {
// Read cookies from handshake headers
var cookies = cookie.parse(socket.handshake.headers.cookie);
// We're now able to retrieve session ID
var sessionID;
if (cookies[name]) {
console.log( "cookies['" + name + "'] = " + cookies[name] );
sessionID = cookieParser.signedCookie( cookies[name], sessionSecret );
console.log( "sessionID = " + sessionID );
}else{
console.log( "cookies['" + name + "'] = undefined" );
}
if (!sessionID) {
console.log('ERROR NO SESSION CONNECTION REFUSED !!');
callback('No session', false);
} else {
// Store session ID in handshake data, we'll use it later to associate
// session with open sockets
socket.handshake.sessionID = sessionID;
callback(null, true);
}
});
socketIo.on('connection', function (socket) { // New client
console.log( 'new connection..' );
console.log('user ' + socket.handshake.sessionID + ' authenticated and is now connected.');
});
/** Start server */
http.listen(port);
console.log( "listening on :" + port );
Go to 192.168.80.213:3000 and see 'Hello from node' and cookie['connect.sid'] is set according to screenshot below
And console output :
Now Clearing cache and i'm going to my back end app where is my nodeClient 192.168.80.213/backend.
connect.sid cookie doesn't exist
And console output :
Why express-session ain't set cookie.sid ? how can i fix that ? I'm new to node and express, i spend many times googling without succes, hope some node masters coul help me !!
regards
I dont know which version of socket.io you are using but after version 1.0 (> 1.0):
To register a middleware you should use socketIo.use (See documentation)
First parameter is incoming socket which have access to request through socket.request
express session by default save cookies with connect.sid name if you want to use io name you should set it explicitely (See name option)
When you want to parse a signed cookie you should provide it sessionSecret not sessionStore
and finally i think handshake support is deprecated and you should attach anything you want directly to socket (See authentication-differences).
With considering aboves you could use a middleware like following to Authenticate your sockets:
// every incoming socket should pass this middleware
socketIo.use(function(socket, next) {
var cookies = cookie.parse(socket.request.headers.cookie);
var sessionID = cookieParser.signedCookie(cookies['connect.sid'], sessionSecret);
sessionStore.get(sessionID, function(err, session) {
if ( session && session.isAuthenticated ) {
socket.userId = session.user.id;
return next();
} else {
return next(new Error('Not Authenticated'));
}
});
});
// when connected ...
socketIo.on('connection', function(socket) {
console.log('user ' + socket.userId + ' authenticated and is now connected.')
});
Here i consider you set isAuthenticated Boolean value and user on session when users logged in.
Also bear in mind that built in sessionStore, MemoryStore is not suit for production environment:
The default server-side session storage, MemoryStore, is purposely not
designed for a production environment. It will leak memory under most
conditions, does not scale past a single process, and is meant for
debugging and developing.
So you must consider using another session store like:
connect-mongo
or
connect-redis
I don't have experience using cookie or cookie-parser and am generally new to node, but I had a similar system to authenticate socket connections by accessing server side session variables if that helps at all.
Save the session details inside a variable
var sessionStorage = expressSession({
'secret': sessionSecret,
'store' : sessionStore,
'resave': true,
'saveUninitialized': true
});
let socketIo and app use the storage
socketIo.use(function (socket, next) {
sessionStorage(socket.request, socket.request.res, next);
});
app.use(sessionStorage);
and then inside on connect you can access those session variables using:
socket.request.res.session.[variable name]

Use loopback token for authentication of socket.io

I'm working with loopback 2.0 and socket.io 1.0.6.
I'd like to use loopback authentication method for authentication of socket.io.
I found the method to authenticate users in loopback/lib/middleware/token.js. https://github.com/strongloop/loopback/blob/master/lib/middleware/token.js
Then I write like below:
var loopback = require('loopback');
var ioapp = module.exports = socketio;
function socketio(server) {
var io = require('socket.io')(server);
// auth
io.use(function(socket, next) {
loopback.token()(socket.request, null, next);
});
// listeners
...
return io;
};
But actually I won't work and causes error like this.
/Users/.../project_root/node_modules/loopback/lib/models/access-token.js:201
id = req.param(params[i]);
^
TypeError: Object #<IncomingMessage> has no method 'param'
at tokenIdForRequest (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/loopback/lib/models/access-token.js:201:14)
at Function.AccessToken.findForRequest (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/loopback/lib/models/access-token.js:123:12)
at /Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/loopback/lib/middleware/token.js:53:16
at Array.0 (/Users/ksuzuki/Projects/appsocially/repo/chat-center/server/socket.js:15:28)
at run (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/socket.io/lib/namespace.js:114:11)
at Namespace.run (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/socket.io/lib/namespace.js:126:3)
at Namespace.add (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/socket.io/lib/namespace.js:155:8)
at Client.connect (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/socket.io/lib/client.js:67:20)
at Server.onconnection (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/socket.io/lib/index.js:309:10)
at Server.EventEmitter.emit (events.js:95:17)
I guess this is because I pass the wrong object type to loopback.token() method.
Well I believe Loopback token is built to be used with express request object. In the latest version(2.x) you could use it if you override AccessToken.findForRequest and implement it you yourself.
But there's another approach to this which is covered in the official documentation:
Basically it suggest using socketio-auth(Which "provides hooks to implement authentication in socket.io without using querystrings to send credentials, which is not a good security practice") and using AccessToken model directly.
I put the code here with a little bit of simplification:
On server-side:
app.io = require('socket.io')(app.start());
require('socketio-auth')(app.io, {
authenticate: function (socket, value, callback) {
var AccessToken = app.models.AccessToken;
//get credentials sent by the client
var token = AccessToken.count({
userId: value.userId,
id: value.id,
}, callback);
}
});
On client-side:
socket.on('connect', function() {
// You should have retrieved tokenId/userId by calling user.login and
// saving it in cookies or localStorage.
socket.emit('authentication', {id: tokenId, userId: userId });
});

Socket.io 1.x + Express (using http): How to send messages to specific client id?

I'm new to socket.io, and I'm doing a simple API with NodeJS (express 4). I'm developing an action that is similar to the old "poke" action at facebook. A user send a poke to other user, and this one gets a notification on real time (this is the reason why I am using socket.io).
This is the code:
app.js
var port = 3000;
var app = module.exports = express();
var server = require('http').Server(app);
...
server.listen(port);
require('./config/socket-io')(app, server, secret);
socket-io.js
module.exports = function(app, server, secret) {
var clients = {};
console.log("initiating sockets...");
var sio = require('socket.io').listen(server, {'log level': 2});
sio.on('connection', function (socket) {
console.log("...new connection: "+socket.client.id);
clients[socket.id] = socket;
socket.emit('identification', { data : socket.client.id });
socket.on('newShoutOut', function(data) {
var receptor = data.idTo;
var emiter = socket.client.id;
console.log("...new shout out from " +emiter+ " to "+receptor);
sio.sockets.sockets[receptor].emit({ data : data.data, from : emiter });
});
socket.on('disconnect', function() {
console.log("..."+socket.client.id + " disconnected");
});
});
};
Here you can differentiate three states:
Connection: The server detects all the clients connection to the host:port. After that, the server sends to each client his ID. This works fine.
Send message: One client sends a notification to other client. For now, the server receives the notification from one client, but the "receiver" doesn't receive anything.
Disconnection: Doesn't matter in this case.
My question is, what is the way to send a message to a client directly knowing the ID? What I am doing wrong? I tried so many options to send a message directly to a specific client ID but didn't work...
EDIT
Frontend
var socket = io('http://localhost:3000');
var id = "";
socket.on('connection', function (data) {
console.log("connected!");
console.log(data);
});
socket.on('identification', function(data) {
id = data.data;
$("#socket_info h1").html("ID: "+id);
});
socket.on('newShoutOut', function(data) {
console.log("newShoutOut received!");
});
Ok, so I assume the shoutout is coming from a user? You will need to create the event on the clientside, such as:
var button = $('#button');
button.on('click', function() {
var msg = 'message',
userID = '123'; //get the ID who they are messaging
socket.emit('sendShoutOut', {msg: msg, id: userID});
});
Then you will need to receive that response on the server, and reply to the user in that function:
socket.on('sendShoutOut', function( data ) {
socket.sockets.sockets[data.id].emit('sendPrivateMsg', { data : data.msg, from : emiter });
});
Lastly, the reciever must be notified, so you will need to handle the response on the client:
socket.on('sendPrivateMsg', function( data ) {
alert(data);
});
Hope this helps.

Categories

Resources