official url |
http://socket.io/download/
http://socket.io/get-started/
https://www.npmjs.com/package/socket.io
https://github.com/Automattic/socket.io
https://github.com/Automattic/engine.io
https://github.com/nswbmw/N-chat
|
basic use |
npm install socket.io
client:
|
server side - io.on socket.emit socket.on |
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.get('/jquery-1.11.1.js', function(req, res){
res.sendFile(__dirname + '/jquery-1.11.1.js');
});
app.get('/socket.io-1.2.0.js', function(req, res){
res.sendFile(__dirname + '/socket.io-1.2.0.js');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('chat message', function(msg){
io.emit('chat message', msg);
console.log("msg: " + msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
|
Client (index.html) |
|
namespace server side |
var io = require('socket.io')(80);
var chat = io
.of('/chat')
.on('connection', function (socket) {
socket.emit('a message', {
that: 'only'
, '/chat': 'will get'
});
chat.emit('a message', {
everyone: 'in'
, '/chat': 'will get'
});
});
var news = io
.of('/news')
.on('connection', function (socket) {
socket.emit('item', { news: 'item' });
});
|
namespace client side |
|
volatile messages |
var io = require('socket.io')(80);
io.on('connection', function (socket) {
var tweets = setInterval(function () {
getBieberTweet(function (tweet) {
socket.volatile.emit('bieber tweet', tweet);
});
}, 100);
socket.on('disconnect', function () {
clearInterval(tweets);
});
});
|
callback |
Server (app.js)
var io = require('socket.io')(80);
io.on('connection', function (socket) {
socket.on('ferret', function (name, fn) {
fn('woot');
});
});
Client (index.html)
|
Broadcasting |
var io = require('socket.io')(80);
io.on('connection', function (socket) {
socket.broadcast.emit('user connected');
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|