I read an excellent blog post called socket.io and Express. tying it all together. that describes the concepts behind putting socket.io in your Express framework. The explanation of what needs to be done is really excellent, but it’s only applicable for Express 2.

Here is an updated tutorial that explains how to do this for Express 3. Since Daniel already covered the “why”, I’ll plunge right ahead into the “how”.

Purpose

In Express, when a socket connects, we don’t know which session it belongs to by default, meaning we can’t do anything private with that connection. We want to be able to retrieve the session information when a socket connects.

Strategy

The steps we will take are:

  1. Enable sessions (duh).
  2. Save a pointer to the session store, to be used in sockets.
  3. Write an authorization function that only accepts sockets with sessions.
  4. Load the session data once a socket is authorized.

Simple enough, right? The key difficulty here is that Connect, the middleware behind Express, has its own internal way of parsing and verifying cookies. We’ll have to reach our fingers in and touch some private functions. Oh well.

Implementation

I’ve created a gist with inline comments that hopefully explain why things are written the way they are:

https://gist.github.com/2640463

  1. vladimir-t reblogged this from notjustburritos
  2. notjustburritos posted this