Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

read/write a value in session #2

Closed
grigio opened this issue Sep 19, 2012 · 7 comments
Closed

read/write a value in session #2

grigio opened this issue Sep 19, 2012 · 7 comments

Comments

@grigio
Copy link

grigio commented Sep 19, 2012

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":"/"}}"}}

@wcamarao
Copy link
Owner

not sure I got it - can you paste your code to give more context?

@grigio
Copy link
Author

grigio commented Sep 20, 2012

Basically it's your code in coffeescript and I'd like to increment counter in session every time the client send the ping event (example).

I've also look at express session example, but I'm not sure if it works in the same way with socket.io https://github.com/visionmedia/express/blob/master/examples/session/redis.js

RedisStore = require('connect-redis')(express)
sessionStore = new RedisStore
....
app.use(express.session({ store: sessionStore }))
...
sessionSockets.on "connection", (err, socket, session) ->
  # here session seems undefined, with redis or memorystore
  # sessionStore is a Redisstore and the session is present in redis
  # should I use session or Redisstore inside here?
  socket.on "ping", (data) ->
    msgcounter = sessionStore.get('counter')
    msgcounter = 1 if !msgcounter
    sessionStore.set('counter', msgcounter++)

@wcamarao
Copy link
Owner

yea you should use session and not sessionStore for that case. if session is null, err should be present and tell what's the problem. seems like you're missing some config. can you paste your complete code? which version of express and socket.io are you using?

@grigio
Copy link
Author

grigio commented Sep 21, 2012

➜  node-testing  npm ls socket.io express
npm WARN package.json application-name@0.0.1 No README.md file found!
application-name@0.0.1/Users/grigio/Code/testing/node-testing
├── express@3.0.0rc4 
└── socket.io@0.9.10 

➜  node-testing  n                
    0.6.21 
  ο 0.8.4

And this is the full test code I'm using:

#
# Init
#
express    = require 'express'
http       = require 'http'
redis      = require 'redis'
connect    = require('connect')
#io         = require 'socket.io'
RedisStore = require('connect-redis')(express)

SessionSockets = require('session.socket.io')

app = module.exports = express()
app.set('port', 3000)
server = app.listen app.get('port')
io = require('socket.io').listen server

cookieParser = express.cookieParser('your secret sauce2')
sessionStore = new RedisStore


sessionSockets = new SessionSockets(io, sessionStore, cookieParser)

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

# redis sockets
store = redis.createClient()
pub = redis.createClient()
sub = redis.createClient()

app.set('port', 3000)
app.use(express.logger('dev'))
app.use(app.router)

#
# Server events
#
sessionSockets.on "connection", (err, socket, session) ->


  console.log '@err: '+ err # <- this is alwais undefined

  socket.on "ping", (data) ->
    console.log '@sess: '+JSON.stringify session # <- this is alwais undefined

    msgcounter = session.get('counter')
    msgcounter = 1 if !msgcounter
    session.set('counter', msgcounter++)

    console.log "@"+"{user:#{socket.id}, txt: #{data.txt}}" #debug
    socket.broadcast.emit "pong", {user:socket.id, txt: data.txt}
    store.rpush 'last_messages', "{user:#{socket.id}, txt: #{data.txt}}"


#
# Routes
#
app.get '/', (req, res) ->
  res.send """
            <h1>Express 3.0 + Socket.IO</h1>
            <input id="text" value/>
            <input id="button" type="button" value="Send"/>
            <hr>
            <div id="msgbox"></div>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
            <script src="/socket.io/socket.io.js"></script>
            <script>
              var socket = io.connect('http://#{server.address().address}:#{server.address().port}');
              socket.on("pong",function(data){
                $("#msgbox").append(data.user+">"+data.txt+"<br>");
              });
              socket.on('new_user', function(data) {
                $("#msgbox").append("Un nuovo utente!! <br>");
              });

              $("#button").click(function(){
                  $("#msgbox").append("ME: "+$("#text").val()+"<br>");
                  socket.emit("ping",{txt: $("#text").val() });
              });
            </script>
           """

# app.get '/test', (req, res) ->
#   res.render 'test',
#     title: JSON.stringify socket

server.on 'listening', () ->
  console.log('Server started on port %s at %s', server.address().port, server.address().address)

@wcamarao
Copy link
Owner

ok I can reproduce it with memory store by faking a wrong session key; seems like redis store uses a different session key from connect/express default. what doesn't make sense is that you ran into the same with memory store, right? can you paste your output of socket.handshake in the server so we can track your session key? then you will need to pass it to sessionSocket as the last optional parameter (see readme).

@grigio
Copy link
Author

grigio commented Sep 22, 2012

Yieeeh!!!! Thanks for helping me in the debug.
I think it was something related to the cross domain cookie policy, because the server was on 0.0.0.0:3000 but the request came from localhost:3000

Now it almost work but it seems the MemoryStore is used even if I specified redis

# like below
# ..
  socket.on "ping", (data) ->

    if session.counter
      ++session.counter
    else
      session.counter=1

    console.log '@sess2: '+JSON.stringify session

OUTPUT

@handshake: {"headers":{"host":"0.0.0.0:3000","connection":"keep-alive","cache-control":"max-age=0","user-agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.64 Safari/537.4","accept":"/","referer":"http://0.0.0.0:3000/","accept-encoding":"gzip,deflate,sdch","accept-language":"it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4","accept-charset":"UTF-8,*;q=0.5","cookie":"connect.sid=s%3Ao0wxRV%2BykXOIxT3FNwsIG9OX.CpuI3xm%2BR3ZeFQKkOMRoP38K12yPMAQVoMXiEv%2BThds"},"address":{"address":"127.0.0.1","port":55613},"time":"Sat Sep 22 2012 11:11:21 GMT+0200 (CEST)","query":{"t":"1348305081311"},"url":"/socket.io/1/?t=1348305081311","xdomain":false,"secret":"your secret sauce2","cookies":{},"signedCookies":{"connect.sid":"o0wxRV+ykXOIxT3FNwsIG9OX"}}
@sess2: {"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/","counter":2}}

The connect.sid session is in redis but "counter" is in memorystore I think

redis 127.0.0.1:6379> get sess:o0wxRV+ykXOIxT3FNwsIG9OX
"{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"}}"

@wcamarao
Copy link
Owner

hey glad you got it. thanks for your feedback, I published 0.1.1 on npm ensuring you will get either an error or the session; it will generate a lookup err if your key is wrong, but that's not your problem per your output. now you should get a better help on redis store repo, so closing this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants