Skip to content

Configuring Socket.IO

Tarik edited this page Nov 4, 2013 · 63 revisions

Configuring Socket.IO

Socket.IO can be configured in the same fashion as you would do with your Express application. It allows the usage of configure, set, enable and disable.

The following options can be configured.

Server

  • origins defaults to *:*
  • The origins that are allowed to connect to the Socket.IO server.

Security Note: If your socket.io server uses HTTP Cookies for authentication, the origins option should be restricted to only trusted hosts. Leaving the default value can lead to third party sites performing authenticated cross-domain requests to your socket.io endpoints and accessing unauthorized application data.

  • store defaults to MemoryStore
  • A store instance that is used to for client storage logic. See MemoryStore for working implementation. The MemoryStore only allows you to deploy socket.io on a single process. If you want to scale to multiple process and / or multiple servers you can use our RedisStore which uses the Redis NoSQL database as man in the middle.

Example:

var RedisStore = require('socket.io/lib/stores/redis')
, redis  = require('socket.io/node_modules/redis')
, pub    = redis.createClient()
, sub    = redis.createClient()
, client = redis.createClient();

io.set('store', new RedisStore({
redisPub : pub
, redisSub : sub
, redisClient : client
}));

If your Redis server uses a password, you must auth the client objects ahead of time, and you must pass in the redis module you used to create those clients as an option to the RedisStore constructor:

var RedisStore = require('socket.io/lib/stores/redis')
, redis  = require('socket.io/node_modules/redis')
, pub    = redis.createClient()
, sub    = redis.createClient()
, client = redis.createClient();

pub.auth(password, function (err) { if (err) throw err; });
sub.auth(password, function (err) { if (err) throw err; });
client.auth(password, function (err) { if (err) throw err; });

io.set('store', new RedisStore({
redis    : redis
, redisPub : pub
, redisSub : sub
, redisClient : client
}));

createClient(port, hostname, options)
  • logger defaults to Logger

  • A logger instance that is used to output log information. See Logger for working implementation.

  • static defaults to Static

  • A Static instance that is used to serve the socket.io client and its dependencies. See Static for working implementation.

  • heartbeats defaults to true

  • Should we use heartbeats to check the health of Socket.IO connections.

  • resource defaults to /socket.io

  • The begin point where Socket.IO starts looking for incoming connections. This should be the same between the client and the server.

  • transports defaults to websocket, htmlfile, xhr-polling, jsonp-polling

  • An array of allowed transport methods. The flashsocket transport is disabled by default, and can be enabled by setting the transports with the flashsocket option included.

  • flashsocket will not activate on Chrome or other browsers that fully support WebSockets, even if flashsocket is specified as the only transport. To test flashsocket, use IE 8 or IE 9, or other browsers that don't natively support WebSockets.

  • authorization defaults to false

  • Global authorization for Socket.IO access, this is called when the initial handshake is performed with the server. See Authorization and handshaking for detailed information.

  • log level defaults to 3

  • The amount of detail that the server should output to the logger.

  • 0 - error

  • 1 - warn

  • 2 - info

  • 3 - debug

  • log colors defaults to true

  • Whether to color the log type when output to the logger.

  • close timeout defaults to 60 seconds

  • The timeout for the client – when it closes the connection it still has X amounts of seconds to re-open the connection. This value is sent to the client after a successful handshake.

  • heartbeat timeout defaults to 60 seconds

  • The timeout for the client when it should send a new heartbeat to the server. This value is sent to the client after a successful handshake.

  • heartbeat interval defaults to 25 seconds

  • The timeout for the server, we should receive a heartbeat from the client within this interval. This should be less than the heartbeat timeout.

  • polling duration defaults to 20 seconds

  • The maximum duration of one HTTP poll, if it exceeds this limit it will be closed.

  • flash policy server defaults to true

  • Enable the flash policy server if the flashsocket transport is enabled.

  • flash policy port defaults to 10843

  • By default the Socket.IO client will check port 10843 on your server to see if flashsocket connections are allowed. The Adobe Flash Player normally uses 843 as default port, but we decided to default to a non root port.

  • destroy buffer size defaults to 10E7

  • Used by the HTTP transports. The Socket.IO server buffers HTTP request bodies up to this limit. This limit is not applied to websocket or flashsockets.

  • destroy upgrade defaults to true

  • Do we need to destroy non-socket.io upgrade requests.

  • browser client defaults to true

  • Does Socket.IO need to serve the static resources like socket.io.js and WebSocketMain.swf etc.

  • browser client cache defaults to true

  • Cache the Socket.IO file generation in the memory of the process to speed up the serving of the static files.

  • browser client minification defaults to false

  • Does Socket.IO need to send a minified build of socket.io.js.

  • browser client etag defaults to false

  • Does Socket.IO need to send an ETag header for the static requests.

  • browser client expires defaults to 315360000

  • Adds a Cache-Control: private, x-gzip-ok="", max-age=31536000 header to static requests, but only if the file is requested with a version number like /socket.io/socket.io.v0.9.9.js.

  • browser client gzip defaults to false

  • Does Socket.IO need to GZIP the static files. This process is only done once and the computed output is stored in memory. So we don't have to spawn a gzip process for each request.

  • browser client handler defaults to false

  • A function that should serve all static handling, including socket.io.js et al.

  • match origin protocol defaults to false

  • Meant to be used when running socket.io behind a proxy. Should be set to true when you want the location handshake to match the protocol of the origin. This fixes issues with terminating the SSL in front of Node and forcing location to think it's wss instead of ws.

var socket = require('socket.io').listen(80, {
  // options can go here
});

// or you can use the .set method

socket.set(key, value);

The browser client handler function

This function receives 2 arguments:

  1. HTTPRequest req The request object
  2. HTTPResponse res The response object

The client handler should take care of all the handling of requests, this includes caching and error handling.

Understanding the configure method

The Socket.IO configuration method mimics the same behavior that you might know from the Express web framework. It allows you to configure Socket.IO based on NODE_ENV environment flags such as production and development.

When configure() is called without an environment flag it will run in every environment. Inside the configure function you can use the set, enable and disable. The example below will enable the Flashsocket and etag for production and only allow WebSocket connection when developing.

var io = require('socket.io').listen(80);

io.configure('production', function(){
  io.enable('browser client etag');
  io.set('log level', 1);

  io.set('transports', [
    'websocket'
  , 'flashsocket'
  , 'htmlfile'
  , 'xhr-polling'
  , 'jsonp-polling'
  ]);
});

io.configure('development', function(){
  io.set('transports', ['websocket']);
});

How do you set the NODE_ENV flag

The following example will set the NODE_ENV flag to production.

NODE_ENV=production node app.js

Recommended production settings

Socket.IO is configured to make the development process easier, that's why certain settings like browser client etag are set to false by default. This will, for example, prevent caching on the socket.io.js file.

The following options are recommended to be set in production:

io.enable('browser client minification');  // send minified client
io.enable('browser client etag');          // apply etag caching logic based on version number
io.enable('browser client gzip');          // gzip the file
io.set('log level', 1);                    // reduce logging

// enable all transports (optional if you want flashsocket support, please note that some hosting
// providers do not allow you to create servers that listen on a port different than 80 or their
// default port)
io.set('transports', [
    'websocket'
  , 'flashsocket'
  , 'htmlfile'
  , 'xhr-polling'
  , 'jsonp-polling'
]);

Heroku has provided their own recommended set of options because they do not support WebSockets unlike other hosting services.

If you are using a hosting provider that doesn't allow you to start servers other than on port 80 or the provided port and you still want to support flashsockets you can set the flash policy port to -1 before you set the transports option.

var io = require('socket.io').listen(80, {
  'flash policy port': -1
});

io.set('transports', ['websocket', 'flashsocket']);

This will instruct the policyfile server to only serve inline policy file requests over your supplied HTTP server. This affect to the initial connection time because the flash player will still search for a dedicated policy file server before it falls back to requesting the policy file inline over the supplied connection.

Client

  • resource defaults to socket.io

    • Note the subtle difference between the server, this one is missing a /. These 2 should be in sync with the server to prevent mismatches.
  • connect timeout defaults to 10000 ms

  • How long should Socket.IO wait before it aborts the connection attempt with the server to try another fall-back. Please note that some transports require a longer timeout than others. Setting this really low could potentially harm them.

  • try multiple transports defaults to true

  • When Socket.IO reconnects and it keeps failing over and over again, should it try all available transports when it finally gives up.

  • reconnect defaults to true

  • Should Socket.IO automatically reconnect when it detects a dropped connection or timeout.

  • reconnection delay defaults to 500 ms

    • The initial timeout to start a reconnect, this is increased using an exponential back off algorithm each time a new reconnection attempt has been made.
  • reconnection limit defaults to Infinity

    • The maximum reconnection delay in milliseconds, or Infinity.
  • max reconnection attempts defaults to 10

    • How many times should Socket.IO attempt to reconnect with the server after a a dropped connection. After this we will emit the reconnect_failed event.
  • sync disconnect on unload defaults to false

  • Do we need to send a disconnect packet to server when the browser unloads.

  • auto connect defaults to true

  • When you call io.connect() should Socket.IO automatically establish a connection with the server.

  • flash policy port defaults to 10843

  • If you have Flashsocket enabled, this should match the same port as the server.

  • force new connection defaults to false

  • Force multiple io.connect() calls to the same server to use different connections.

var socket = io.connect('http://server.com', {
  // options here
});