Giter Club home page Giter Club logo

session.socket.io's Introduction

session.socket.io (SessionSockets) Build Status

This tiny module simplifies the usage of socket.io with http sessions from express or connect middlewares. It has no dependencies and can be initialized using any session store and cookie parser compatible with express or connect.

Compatibility:

  • Express 3
  • Express 4
  • Connect 2
  • Socket.io 0.9

If you're using socket.io 1.0 or newer, this is not required because socket.io 1.0 has built-in support for middlewares.

Quick Start

Import the module and initialize it providing the required parameters

var SessionSockets = require('session.socket.io'),
    sessionSockets = new SessionSockets(io, sessionStore, cookieParser);

Listen to socket connections and get the socket as provided by socket.io with either an error or the session

sessionSockets.on('connection', function (err, socket, session) {
  //your regular socket.io code goes here
  //and you can still use your io object
});

Running the example

$ cd example
$ npm install
$ node server.js

Visit http://localhost:3000

Running the spec

$ npm install
$ make spec

Saving values into the session

sessionSockets.on('connection', function (err, socket, session) {
  session.foo = 'bar';
  //at this point the value is not yet saved into the session
  session.save();
  //now you can read session.foo from your express routes or connect middlewares
});

Namespacing

sessionSockets.of('/chat').on('connection', function (err, socket, session) {
  //the socket here will address messages only to the /chat namespace
});

Get session for a client

io.sockets.clients().forEach(function (socket) {
  // so far we have access only to client sockets
  sessionSockets.getSession(socket, function (err, session) {
    // getSession gives you an error object or the session for a given socket
  });
});

Callback parameters and error handling

Note that now you receive 3 parameters in the connection callback: (err, socket, session).

  • The first parameter will be present if an error has occured, otherwise null. Errors may originate from the cookie parser when trying to parse the cookie, or from the session store when trying to lookup the session by key.
  • The second parameter will be the socket as provided by socket.io.
  • The third parameter will be the corresponding user session for that socket connection if an error has not ocurred, otherwise null.

Troubleshooting

The cookieParser doesn't need to be the same reference, you can create another instance somewhere else, but it should take the same 'secret', otherwise the cookie id won't be decoded, therefore the session data won't be retrieved.

The sessionStore must be the same instance.

You can always debug cookies and session data from any socket.handshake. The socket is the same as provided by socket.io.

Cookie lookup precedence

When looking up for the cookie in a socket.handshake, SessionSockets will take precedence on the following order:

  1. secureCookies
  2. signedCookies
  3. cookies

Custom session store key

You can specify a custom session store key

new SessionSockets(io, sessionStore, cookieParser, 'customSessionStoreKey');

It defaults to 'connect.sid' (which is default for both connect and express).

A step by step example

This is for express 3. If you're using express 4, follow the steps above under "Running the example" but in the example-express4 directory.

var http = require('http'),
    connect = require('connect'),
    express = require('express'),
    app = express();

Below are the two main references you will need to keep

var cookieParser = express.cookieParser('your secret sauce'),
    sessionStore = new connect.middleware.session.MemoryStore();

Both will be used by express and so far everything's familiar. Note that you need to provide sessionStore when using express.session(). Here you could use Redis or any other store as well.

app.configure(function () {
  //hiding other express configuration
  app.use(cookieParser);
  app.use(express.session({ secret: 'your secret sauce', store: sessionStore }));
});

Next, you create the server and bind socket.io to it (nothing new here)

var server = http.createServer(app),
    io = require('socket.io').listen(server);

Inject the original io module with the sessionStore and cookieParser

var SessionSockets = require('session.socket.io'),
    sessionSockets = new SessionSockets(io, sessionStore, cookieParser);

Now instead of io.sockets.on('connection', ...) you will use sessionSockets, giving you the session for that socket

sessionSockets.on('connection', function (err, socket, session) {
  //your regular socket.io code goes here
  //and you can still use your io object
});

License

The MIT License

Copyright (c) 2012 Wagner Camarao

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

session.socket.io's People

Contributors

artur-krueger avatar austp avatar euoia avatar hnry avatar inspectocat avatar joeao avatar trotter avatar wcamarao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

session.socket.io's Issues

How to write to session?

First:

sIO.on('connection', function (err, socket, session) {
    session.cookie.test = '1';
});

After:

app.get('/', function (req, res) {
  console.log(req.cookies.test);
  // undefined!!!
  res.send(200);
});

Thanks!

Compatibility with socket.io 1.0.6 ?

Hello,

Since socket.io released a 1.0.6 version, do session.socket.io is compatible with this new version ? I need to migrate to this version and my previous code which contain
socket.handshake.getSession method is saying me that socket.handshake has no getSession method.

Is there a workaround or maybe the compatibility with socket.io 1.0.6 is plan soon ?

Thank you

Npm

Hey, fancy putting this on npm?

Session with flashsocket

Hi Wagner,

Thank you very much for sharing this great little module!

I tried it with a JavaScript based socket client and it works like a charm but this is not the case for flashsocket. So, I was wandering if you could give me a tip about how I can get it working, if possible at all.

Thank you again,

Naso.

Undefined error

This is a bit of a weird bug, which may be caused by my code below. Basically what I am trying to do is prevent the user from opening the chat in multiple tabs after they have logged in, as I only want them to be in one room at a time.

I am trying to keep track if the user opens a new window, by checking if they are already in the online users array, and if they are disconnect their previous connection.

Now the problem comes when I open a tab. Everything works as intended, but if I now refresh the page then I get the error [TypeError: Cannot read property '' of undefined]. I am not sure if it's a problem with my approach or not, thank you.

var onlineUsers = new Array();

sessionSockets.on('connection', function(err, socket, session){
if(err) console.log(err);
console.log(onlineUsers);
if(session.username in onlineUsers){
console.log("DISCONNECTED: " + onlineUsers[session.username]);
socket.manager.onClientDisconnect(onlineUsers[session.username]);
}
onlineUsers[session.username] = socket.id;
console.log("CONNECTED: " + onlineUsers[session.username]);
console.log(onlineUsers);
io.sockets.emit('getlobbyuserlist', Object.keys(onlineUsers));
socket.on('sendlobbymessage', function(message){
io.sockets.emit('addlobbymessage', { username: session.username, message: message });
});
socket.on('disconnect', function(){
//Remove the user from the lobby user list when they close the window
//io.sockets.emit('removeuserfromlist', session.username);
//This is only used when the client is forced to disconnect - ie they have multiple tabs open
socket.emit("forcedisconnect");
});
});

Broken when using Express 4.0 because of changed middleware for cookies

When using session.socket.io with Express 4.0 i need to use this hotfix:

function findCookie(handshakeInput) {
    // added fix for express 4.x (parse the cookie sid to extract the correct part)
    var handshake = JSON.parse(JSON.stringify(handshakeInput)); // copy of object
    if(handshake.secureCookies && handshake.secureCookies[key]) handshake.secureCookies = handshake.secureCookies[key].match(/\:(.*)\./).pop();
    if(handshake.signedCookies && handshake.signedCookies[key]) handshake.signedCookies[key] = handshake.signedCookies[key].match(/\:(.*)\./).pop();
    if(handshake.cookies && handshake.cookies[key]) handshake.cookies[key] = handshake.cookies[key].match(/\:(.*)\./).pop();

    // original code
    return (handshake.secureCookies && handshake.secureCookies[key])
        || (handshake.signedCookies && handshake.signedCookies[key])
        || (handshake.cookies && handshake.cookies[key]);
}

I'm sure there's a much better way of solving thing in the long run. I just needed a quick fix for some prototyping :-)

Only a part of the session id is saved to the cookie it appears (hence the regex).

getCookie returned more than just session id; had to trim to make it work

I was having issues getting session.socket.io to work, though after a bit of debugging, I've finally traced and put a bandaid on the issue - though my patch is a bit dirty, and I'm unsure if I've missed something that may be the origin of this issue.

So getCookie was returning something along the following (from handshake.cookies):
s:[sessionId].[trailingCharacters]
Wherein [sessionId] was the valid session id.

The sessionStore.load method is looking only for the session id, and thus it failed to get the session because of this issue. By using simple string manipulation, I was able to get the actual session id out of the cookie value, thus making the entire module work.

So I changed this line:
sessionStore.load(findCookie(socket.handshake), function (storeErr, session) {

to this:
sessionStore.load(findCookie(socket.handshake).substring(2).split('.')[0], function (storeErr, session) {

Here's a gist of test code that I've used to reproduce this issue: https://gist.github.com/TimeBomb/d992c84401d6e02b1c77

It errors out without the change I've made. With the change I've made, upon loading for the second time, it shows that the session test var is 1, as expected.

FYI, I'm using the latest version (as of 04/08/2013) of all the modules required in the aforementioned test code.

easyrtc 1.0.7

hi,
when i use session.socket.io in easyrtc 0.9, works very well
but when use in easyrtc 1.0.7, gives error.

namespace.on(event, function (socket) {
                  ^
TypeError: Cannot call method 'on' of undefined
    at bind (/var/www/nodejs/easyrtc-master/node_modules/session.socket.io/session.socket.io.js:26:15)
    at on (/var/www/nodejs/easyrtc-master/node_modules/session.socket.io/session.socket.io.js:13:17)
    at Object.<anonymous> (/var/www/nodejs/easyrtc-master/server.js:103:16)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

Write to session store -- and persist it?

Hey,

Great little library you've got here.

I use it in conjunction with a MongoStore, which also powers my Express HTTP sessions. Only thing is, when I (from inside a socket.io callback) modify the session exposed by this library, it only seems to persist in memory; when I restart the server, the changes are not reflected (and thus weren't saved in MongoDB).

Am I wrong in expecting the changes to be perserved in MongoDB? Or is the session only exposed as read-only through socket.io.

very slow

original:

This module is slow.

In my testing, it seems more than 10 times slower compared to not using this module.
This is without variables such as network latencies etc.

I feel like this module can be faster, 10 times slower is too much.

edited:

This module is slow.

Using stubs, and not actually doing any real session loading, purely just testing the module it is more than 10 times slower compared to not using this module.

I feel like this module can be faster, 10 times slower is too much.

My results look something like this out of a run count of 10000000:

Without using this module

  • op/s: 10004360 | time: 0.99956419

With this module (but no real session loading, it's all stubbed) so this is purely testing the module's performance with no outside factors

  • op/s: 780283 | time: 12.815870532

Got deprecation warning with express 3.4.4

Just in case :

connect.multipart() will be removed in connect 3.0
visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives
connect.limit() will be removed in connect 3.0

Thanks for your work

Express 4 session null error

I am trying to use it with Express 4 and it is not working. I did just copy paste from Express 4 example code.

sessionSockets.on('connection', function (err, socket, session) {
var likes = [];
console.log("session=",session); ---->>>>> HERE session is null & impossible to use it
socket.emit('session', session);

How to solve this problem?

session.save() callback

Hello!

I just found out a minute ago that if you save the session and nearly at the same time you refresh the browser it doesn't save the changes. Right now after saving I send a message to the client and wait 2 seconds before reloading the page, just to make sure it saves properly, but it would be nice to have a callback to know when it's okay to refresh.

Thanks in advance!

Please add 4th param "key" to README.md

I just noticed, after a bunch of hair pulling over why I was getting ([Error: could not look up session by key: connect.sid]) that there is a 4th param that doesn't seem to be mentioned in the README.md to set the key. It would be helpful to have this included since lots of us change the key name for security reasons.

Question about using the socket.io authorization setup

you commented here about why you didn't want to use set('authorization') of socket.io.

senchalabs/connect#588 (comment)

"I see your point @kcaffrey, but I can't agree for a couple reasons: refusing a connection if the session is not found/valid and changing the socket object to add the session."

Could you clarify.

I'm not sure I understand why you wouldn't want to refuse a connection if a session id is invalid or missing.

Could not lookup session by key

I'm experiencing this issue with the latest socket.io 1.3.5 and express4.
I followed the express4 example, but i am using the connect-redis session store.

server.js

var _u = require('underscore')
  , http = require('http')
  , express = require('express')
  , url = require('url')
  , redis = require('redis')
  , mongoose = require('mongoose')
  , debug = require('debug')('signaling')
  , SocketIO = require('socket.io')
  , adapter = require('socket.io-redis')
  , Turn = require('./lib/turn')
  , Events = require('./lib/events')
  , Rooms = require('./lib/model/rooms')
  , Users = require('./lib/model/users')
  , Clients = require('./lib/model/clients')
  , SignalingError = require('./lib/error')
  , safesocket = require('./lib/safesocket')
  , config = require('./config');


var app = express();
var session = require('express-session');
var cookieParser = require('cookie-parser')(config.sessions.secret);
var RedisStore = require('connect-redis')(session);
var store = new RedisStore({
    client: require('redis-url').connect(process.env.REDIS_TURN_URL || 'redis://127.0.0.1:6379')
});

app.use(cookieParser);
app.use(session({
    secret: config.sessions.secret,
    store: store
}));

var server = http.Server(app);
var io = new SocketIO(server);

var SessionSockets = require('session.socket.io');
var sessionSockets = new SessionSockets(io, store, cookieParser);

io.path(config.io.path);
io.serveClient(config.io.serve_client);
io.listen(process.env.LISTEN_PORT || 3000);

sessionSockets.on('connection', function (err, socket, session) {

    console.log(err);
    debug('new client from ' + (socket.handshake.headers['x-forwarded-for'] || socket.client.conn.remoteAddress));
});

client.js

<html>

<head>
</head>

<body>
    <div id="stuns"></div>

    <script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
    <script>
        var socket = io('http://localhost:3000', {
            forceNew: true,
            path: '/websocket'
        });
        console.log(socket);
        socket.emit('stun', function (err, stuns) {
            console.log('here');
            if (err) console.log(err);
            console.log(stuns);
            document.getElementById('stuns').innerHTML = stuns.toString();
        });
    </script>
</body>

</html>

package.json

  "dependencies": {
    "connect-redis": "^2.2.0",
    "cookie-parser": "^1.3.4",
    "debug": "^2.1.2",
    "express": "^4.12.3",
    "express-session": "^1.10.4",
    "hiredis": "^0.2.0",
    "moment": "^2.9.0",
    "mongoose": "^3.8.25",
    "redis": "^0.12.1",
    "redis-url": "^1.1.0",
    "session.socket.io": "^0.2.0",
    "socket.io": "^1.3.5",
    "socket.io-redis": "^0.1.4",
    "underscore": "^1.8.2"
  },

Thanks

William

Why doesn't resolve return an error object?

Can you tell me why, in the event of an error, resolve returns an object with an error key instead of an Error object?

Where session.socket.io.js has:

if (!storeErr && !session) return { error: 'could not look up session by key: '+key };

I would expect to see:

if (!storeErr && !session) return new Error('could not look up session by key: '+key);

This way, one could rethrow the error and get a meaningful stack trace.

Session not updating

I have everything set up like example-express4

sessionSockets.on('connection', function (err, socket, session) {
    // 1: User not signed in
    console.log(session);

    // 2: Happens while the user is signed in
    socket.on('event', function(req){
        console.log(session)
    })
});

1: log as expected:

Session {
  cookie: {...} 
}

2: the signed in user event from the front-end logs the same results as 1, but expecting:

Session {
  cookie: {...},
  passport: {user: '1234'}
}

If I refresh the browser, while signed in, I then see what I would expect.

Is there a way to keep these sessions in sync?

read/write a value in session

Hi,
thanks for this package, I'm a bit confused how should I set the value (es. a reconnection counter) in the session? Should I use the "sessionStore" or the "session" from "connection", (err, socket, session) -> (this seems to be undefined inside the function)

console.log JSON.stringify sessionStore
{"sessions":{"gfFR572JqrZmCAWGwupdmFkD":"{"cookie": {"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"}}"}}

You can't directly work with session when you're using connect-mongo store

ok, i setup session.socket.io and my socket is working. But working with session i got javascript object instead of mongo record. So i can't perform this code (as shown):

sessionSockets.on('connection', function (err, socket, session) {
  session.foo = 'bar';
  //at this point the value is not yet saved into the session
  session.save();
  //now you can read session.foo from your express routes or connect middlewares
});

Becouse of you get unserialized record:

https://github.com/kcbanner/connect-mongo/blob/master/lib/connect-mongo.js

MongoStore.prototype.get = function(sid, callback) {
    var self = this;
    this._get_collection(function(collection) {    
      collection.findOne({_id: sid}, function(err, session) {
        try {
          if (err) {
            callback && callback(err, null);
          } else {      

            if (session) {
              if (!session.expires || new Date < session.expires) {
                callback(null, self._unserialize_session(session.session));
...

get data out of sessionStore

i create a session variable named session.active. when ever a user with a valid session comes i will set session.active = 1 and when he disconnects i will set session.active = 0.

at the admin site i will get all users (sessions) with the session.active = 1

i try to stringify and parse the json (storeSession) but i dont reach the active variable.

can you help me please?

rooms

I get TypeError: Cannot call method 'clients' of undefined
when trying to access namespace rooms, with sessionSockets.sockets.clients('room');
I glanced at the code see no room management functionality, is there a way to implement it?

When looping through sockets, how do I get the session data? (Solved)

I have everything set up so far that multiple users are connected to the server at a time. What I want is when one of them presses a button, a popup box will show up for every person telling them what their name is which is stored in their own session objects. So I am trying to break out your code so that I can get session data individually.

Here is what I have so far in my app.js

ssockets.on('connection', function(err, socket, session){
    socket.on('button' function(){
        io.sockets.clients().forEach(function(_socket){
            _socket.emit('name', {name: ssockets.getSession(_socket).name});
        });
    });
}

And this is what I have added to session.socket.io

this.getSession = function(socket){
    cookieParser(socket.handshake, {}, function (){
        sessionStore.load(findCookie(socket.handshake), function(storeErr, session){
            console.log(session);
            return session;
        });
    });
}

The problem I am getting is ssockets.getSession(_socket).name: cannot read a property from an undefined object. But when I console.log(session) it shows me that it has the session data. So I'm guessing that it's actually being ran after the call. Is the only way I can emit the data is if I add a callback to the function? What do you suggest?

Update

I ended up going with passing in a callback function. I forked the repository and made my changes here for anyone who is trying to do a similar thing: https://github.com/AustP/session.socket.io

redis latency

What's the best way of dealing with latency from redis when using;

io.sockets.clients().forEach(function (socket) {
// so far we have access only to client sockets
sessionSockets.getSession(socket, function (err, session) {
// getSession gives you an error object or the session for a given socket
});
});

I'm trying to get a list of clients online in a room and fetch their username, however the the session information retrieval appears to happen asynchronously to the rest of the code?

session.socket.io doesn't work

I using express 4 + passport with sessions.

I want to make private messages between users with socket.io

Before sending a message from the first user to a second user - I want to verify that the message is really from the first user. To exclude id spoofing in javascript files.

I try to using session.socket.io but it does not work and I can not understand why.

"console.log('connect!');" doesn't work. It seems that the function "sessionSockets.on('connection')"is not executed

Code:

require('./db');

var flash = require('connect-flash');
var mongoose = require('mongoose');
require('./config/passport');

var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');

var routes = require('./routes');
var users = require('./routes/user');

var session = require('express-session');
var MongoStore = require('connect-mongo')(session);

var sessionStore = new MongoStore({db:mongoose.connection.db});

var app = express();

app.use(cookieParser('keyboard cat'));
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
secret: 'keyboard cat',
cookie: {httpOnly: true, secure: true, maxAge: new Date(Date.now() + 3600000)},
store: sessionStore
}));
app.use(flash());

app.use(passport.initialize());
app.use(passport.session());
app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function() {
// debug('Express server listening on port ' + server.address().port);
});

var io = require('socket.io').listen(server);
var SessionSockets = require('session.socket.io-express4');
var sessionSockets = new SessionSockets(io, sessionStore, cookieParser);

sessionSockets.on('connection', function (err, socket, session) {
console.log('connect!');

socket.on('sendMessageToUser', function(data){
console.log(data);
console.log('User is ' + req);
});
//now you can read session.foo from your express routes or connect middlewares
});

Better solution

Respect to wcamarao for developing this tool, which closes an important gap.
Unfortunately it didn't work for me as I could not get around this:

node_modules/session.socket.io/session.socket.io.js:23
sessionLookupMethod.call(sessionStore, findCookie(socket.handshake), fun
                      ^
TypeError: Cannot call method 'call' of undefined

I lost an hour or two googling for similar problems ... until I found:
http://stackoverflow.com/a/29448630/1385546
which links to
https://github.com/xpepermint/socket.io-express-session

Please forgive my boldness, but I can't help that this approach using the new io middleware is far easier and cleaner. (Despite my not fully understanding :)

Problems with example code in README.md

When I copy the example code from README.md, session is always undefined in sessionSockets.on('connection'
err is 'Error: could not look up session by key: connect.sid'

This is the same problem as in issue #2:
#2

This line is what is causing issues:

app.use(express.session({ store: sessionStore }));

I need to change it to:

app.use(express.session({ secret: 'your secret sauce', store: sessionStore }));

To match the secret given to the cookie parser:

var cookieParser = express.cookieParser('your secret sauce')
, sessionStore = new connect.middleware.session.MemoryStore();

This solves the issue. If this is a general problem, perhaps the instructions in README.md ought to be updated?

your example fails in IE

THX for this great package (I have to say this first)

Issue

I got this handshake error when using IE (we only support >9, fails in all of them):
ERR Could not look up session by key: connect.sid

Sandbox Testing

So, we decided to run your example script, and oopz... it also fails in IE....
URL http://217.115.134.41:3187/

issue

NOTE This is very urgent, I hope you can provide a solution for this, our projects need to run in this cruel browser too...

UPDATE In some IE's it seems to work... Now we've got to find out why... 32bit vs 64bit??

(node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.

Node v0.10.5, Windows 7,

I am using the following code:

var store = new MongoStore({
     collectionPrefix: 'socket.io.',
     streamCollection: 'stream',
     storageCollection: 'storage',
     nodeId: null,  // id that uniquely identifies this node
     size: 1000000, // max size in bytes for capped collection
     num: null,     // max number of documents inside of capped collection
     // url: 'mongodb://localhost:27017/yourdb',
     host: 'localhost',
     port: 27017,
     db: 'socketio'
 });
 store.on('error', console.error);
 io.set('store', store);

The last line produces multiple warnings:
(node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.

Any ideas?

Adding the in(room) method

As described here, socket.io supports Rooms. This is really handy when you need to partition your users.
Unfortunately session.socket.io does not support it, because it doesn't implement the in() method call.

Any chance that you'll add it in the next release?

I made a quick hack to make it work:

this.in = function(room) {
    return io.sockets.in(room);
};

but I doubt it's the proper way, given your on() implementation.

Thanks for your great work.

sessionStore not refreshed?

my code:

socket.on('disconnect', function(){

session.active = '0';
session.save()
console.log(session.active);
console.log(sessionStore);
io.sockets.emit('sendSessions', sessionStore);

});

after disconnect i set session.active = 0

console.log(session.active); // logs 0

console.log(sessionStore); //logs 1

how can that be?

Struggling to write a session

I am trying to write a session value but I am getting "TypeError: Cannot set property 'foo' of undefined"

var express = require('express'),
    app = express(),
    http = require('http'),
    connect = require('connect'),
    mysql = require('mysql'),
    queue = [],
    db = mysql.createConnection({
          host     : 'xxxxx',
          user     : 'xxxx,
          password : 'xxxx',
          database : 'xxxx'
    }),
    cookieParser = express.cookieParser('testingthis'),
    sessionStore = new connect.middleware.session.MemoryStore();

app.configure(function () {
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(cookieParser);
    app.use(express.session({ store: sessionStore }));
});

var server = http.createServer(app),
    io = require('socket.io').listen(server),
    sessionSockets = require('session.socket.io'),
    sessionSockets = new sessionSockets(io, sessionStore, cookieParser);

server.listen(3000);
db.connect();

sessionSockets.on('connection', function (err, socket, session) {

    session.foo = 'bar'; // errors here: TypeError: Cannot set property 'foo' of undefined

    session.save();

    console.log(session.foo);

sessionStore.of method

How can we use the namespace feature with the provided sessionStore?
It only has on method defined? Can you advice on how to extend it?

could not look up session by key: connect.sid

I can't make it working.

The client connected but the session always is undefined with error:

could not look up session by key: connect.sid

Could you help please?

app.js

var http = require('http')
, connect = require('connect')
, express = require('express');

var app = express()
, cookieParser = express.cookieParser('key')
, sessionStore = new connect.middleware.session.MemoryStore();

app.configure(function () {
//hiding other express configuration
app.use(cookieParser);
app.use(express.session({ store: sessionStore }));
});

var server = http.createServer(app)
, io = require('socket.io').listen(server);

var SessionSockets = require('session.socket.io')
, sessionSockets = new SessionSockets(io, sessionStore, cookieParser);

server.listen(8080);

sessionSockets.on('connection', function (err, socket, session) {
console.log('connection ERR ', err);
console.log('connection session ', session);
});


client

<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js' ></script>
<script src='./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js'></script>
<script>
var iosocket = null;
$(function(){
iosocket = io.connect('http://localhost:8080');
iosocket.on('error', function (reason){
console.error('Unable to connect Socket.IO', reason);
});
iosocket.on('connect', function () {
$('#status').html('Connected');
});
iosocket.on('disconnect', function() {
$('#status').html('Disconnected');
iosocket.socket.connect();
});
});

</script>

</head>

<body>

<div id='status'></div>

</body>
</html>

Bug

[TypeError: Object # has no method 'getSession']

Since you're latest update to 0.1.5

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.