socket.io
Installation
npm install socket.io --save
How to use
The following example attaches socket.io to a plain Node.JS
HTTP server listening on port 3000.
var server = require('http').createServer();
var io = require('socket.io')(server);
io.on('connection', function(client){
client.on('event', function(data){});
client.on('disconnect', function(){});
});
server.listen(3000);
Standalone
var io = require('socket.io')();
io.on('connection', function(client){});
io.listen(3000);
In conjunction with Express
Starting with 3.0, express applications have become request handler
functions that you pass to http or http Server instances. You need
to pass the Server to socket.io, and not the express application
function.
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(){ /* … */ });
server.listen(3000);
In conjunction with Koa
Like Express.JS, Koa works by exposing an application as a request
handler function, but only by calling the callback method.
var app = require('koa')();
var server = require('http').createServer(app.callback());
var io = require('socket.io')(server);
io.on('connection', function(){ /* … */ });
server.listen(3000);
API
See API.
Debug / logging
Socket.IO is powered by debug.
In order to see all the debug output, run your app with the environment variable
DEBUG including the desired scope.
To see the output from all of Socket.IO's debugging scopes you can use:
DEBUG=socket.io* node myapp
Testing
npm test
This runs the gulp task test. By default the test will be run with the source code in lib directory.
Set the environmental variable TEST_VERSION to compat to test the transpiled es5-compat version of the code.
The gulp task test will always transpile the source code into es5 and export to dist first before running the test.