Socket.IO
Overview Server API Client API
Rooms and Namespaces
Migrating from 0.9Using multiple nodes Logging and Debugging
FAQ
How to use
Installing
Using with Node http server
$ npm install socket.io
Home Demos Get started Docs Blog Slack 78
Server (app.js)
var app = require('http').createServer(handler)var io = require('socket.io')(app);var fs = require('fs');
Client (index.html)
var socket = io('http://localhost');
Using with Express 3/4
Using with the Express framework
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html', function (err, data) { if (err) {
res.writeHead(500);
return res.end('Error loading index.html'); }
res.writeHead(200); res.end(data); });}
io.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); });});
socket.on('news', function (data) { console.log(data);
socket.emit('my other event', { my: 'data' }); });
Server (app.js)
var app = require('express')();
var server = require('http').Server(app);var io = require('socket.io')(server);server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');});
io.on('connection', function (socket) { socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) { console.log(data); });});
Client (index.html)
var socket = io.connect('http://localhost'); socket.on('news', function (data) { console.log(data);
socket.emit('my other event', { my: 'data' }); });
Server (app.js)Client (index.html)
Sending and receiving events
Socket.IO allows you to emit and receive custom events. Besides connect
,
message
and
disconnect
, you can
emit custom events:Server
Restricting yourself to a namespace
If you have control over all the messages and events emitted for a particular application, using the default /namespace works. If you want to leverage 3rd-party code, or produce code to share with others, socket.io provides a way of namespacing a socket.This has the benefit of multiplexing
a single connection. Instead of socket.io using two
WebSocket
connections,
it’ll use one.
// note, io(
io.on('connection', function (socket) {
io.emit('this', { will: 'be received by everyone'});
socket.on('private message', function (from, msg) {
console.log('I received a private message by ', from, ' saying ', msg); });
socket.on('disconnect', function () { io.emit('user disconnected'); });});
var app = require('express').createServer();var io = require('socket.io')(app);app.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) { console.log(data); });});
var socket = io.connect('http://localhost'); socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' }); });
Sending volatile messages
Sometimes certain messages can be dropped. Let’s say you have an app that shows realtime tweets for the keyword bieber .
If a certain client is not ready to receive messages (because of network slowness or other issues, or because they’re connected through long polling and is in the middle of a request-response cycle), if they doesn’t receive ALL the tweets related to bieber your application won’t suffer.
In that case, you might want to send those messages as volatile messages.Server
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); });});
Server (app.js)
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' }); });
Client (index.html)
var chat = io.connect('http://localhost/chat') , news =
io.connect('http://localhost/news');
chat.on('connect', function () { chat.emit('hi!'); });
news.on('news', function () { news.emit('woot'); });
Sending and getting data (acknowledgements)
Sometimes, you might want to get a callback when the client confirmed the message reception.To do this, simply pass a function as the last parameter of
.send
or
.emit
. What’s more, when you use
.emit
,
the acknowledgement is done by you, which means you can also pass data along:
Broadcasting messages
To broadcast, simply add a broadcast flag to emit and send method calls. Broadcasting means sending a message to everyone else except for the socket that starts it.Server
Using it just as a cross-browser WebSocket
If you just want the WebSocket semantics, you can do that too. Simply leverage send
and listen on the
message
event:
var io = require('socket.io')(80);
io.on('connection', function (socket) { socket.broadcast.emit('user connected');});
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)
var socket = io(); // TIP: io() with no args does auto-discovery
socket.on('connect', function () { // TIP: you can avoid listening on `connect` and listen on events directly too!
socket.emit('ferret', 'tobi', function (data) {
console.log(data); // data will be 'woot' }); });
Server (app.js)
var io = require('socket.io')(80);
Client (index.html)
var socket = io('http://localhost/');
Home Demos Get started Docs Blog Slack78
Overview
Server API
Client API
Rooms and Namespaces
Migrating from 0.9
Using multiple nodes
Logging and Debugging
FAQ
Server API
Server
Exposed by require('socket.io').
Server()
Creates a new Server. Works with and without new:
var io = require('socket.io')();
// or
var Server = require('socket.io');
var io = new Server();
Server#onconnection(socket:engine#Socket):Server
Advanced use only. Creates a new socket.io client from the incoming engine.io (or compatible API) socket.
Server#of(nsp:String):Namespace
Initializes and retrieves the given Namespace by its pathname
identifier nsp.
If the namespace was already initialized it returns it right away. Server#emit
Emits an event to all connected clients. The following two are equivalent:
var io = require('socket.io')();
io.sockets.emit('an event sent to all connected clients');
io.emit('an event sent to all connected clients');
For other available methods, see Namespace below.
Server#use
See Namespace#use below.
Namespace
Represents a pool of sockets connected under a given scope identified by a pathname (eg: /chat).
By default the client always connects to /.
Events
connection / connect. Fired upon a connection.
Parameters:
Socket the incoming socket.
Namespace#name:String
The namespace identifier property.
Namespace#connected:Object
Hash of Socket objects that are connected to this namespace indexed by id.
Namespace#use(fn:Function):Namespace
Registers a middleware, which is a function that gets executed for every incoming Socket and receives as parameter the socket and a function to optionally defer execution to the next registered middleware.
var io = require('socket.io')();
https://www.360docs.net/doc/0d2674400.html,e(function(socket, next){
if (socket.request.headers.cookie) return next();
next(new Error('Authentication error'));
});
Errors passed to middleware callbacks are sent as special error packets to clients.
Socket
A Socket is the fundamental class for interacting with browser clients. A Socket belongs to a certain Namespace (by default /)
and uses an underlying Client to communicate.
Socket#rooms:Array
A list of strings identifying the rooms this socket is in.
Socket#client:Client
A reference to the underlying Client object.
Socket#conn:Socket
A reference to the underyling Client transport connection (engine.io
Home Demos Get started Docs Blog Slack78
Overview
Server API
Client API
Rooms and Namespaces
Migrating from 0.9
Using multiple nodes
Logging and Debugging
FAQ
Client API
IO(url:String, opts:Object):Socket
Exposed as the io global in window if using the standalone build (eg: /socket.io/socket.io.js or the CDN), or the result of calling require('socket.io-client').
When called, it creates a new Manager for the given URL, and attempts
to reuse an existing Manager for subsequent calls, unless the
multiplex option is passed with false. Passing this option is the equivalent of passing 'force new connection': true.
The rest of the options are passed to the Manager constructor (see below
for details).
A Socket instance is returned for the namespace specified by the pathname in the URL, defaulting to /. For example, if the url is http://localhost/users, a transport connection will be established to http://localhost and a Socket.IO connection will be established to
/users.
IO#protocol
Socket.io protocol revision number this client works with.
IO#Socket
Reference to the Socket constructor.
IO#Manager
Reference to the Manager constructor.
IO#Emitter
Reference to the Emitter constructor.
Manager(url:String, opts:Object)
A Manager represents a connection to a given Socket.IO server. One or more Socket instances are associated with the manager. The manager can be accessed through the io property of each Socket instance.
The opts are also passed to engine.io upon initialization of the underlying Socket.
Options:
– reconnection whether to reconnect automatically (true)
– reconnectionDelay how long to wait before attempting a new reconnection (1000)
– reconnectionDelayMax maximum amount of time to wait between reconnections (5000). Each attempt increases the reconnection by
the amount specified by reconnectionDelay.
– timeout connection timeout before a connect_error
and connect_timeout events are emitted (20000)
Events
connect. Fired upon a successful connection.
connect_error. Fired upon a connection error.
Parameters:
Object error object
connect_timeout. Fired upon a connection timeout.
reconnect. Fired upon a successful reconnection.
Parameters:
Number reconnection attempt number
reconnect_attempt. Fired upon an attempt to reconnect.
reconnecting. Fired upon an attempt to reconnect.
Parameters:
Number reconnection attempt number
reconnect_error. Fired upon a reconnection attempt error.
Parameters:
Object error object
reconnect_failed. Fired when couldn’t reconnect within reconnectionAttempts
The events above are also emitted on the individual sockets that
reconnect that depend on this Manager.
Manager#reconnection(v:Boolean):Manager
Sets the reconnection option, or returns it if no parameters
are passed.
Manager#reconnectionAttempts(v:Boolean):Manager
Sets the reconnectionAttempts option, or returns it if no parameters
are passed.
Manager#reconnectionDelay(v:Boolean):Manager
Sets the reconectionDelay option, or returns it if no parameters
are passed.
Manager#reconnectionDelayMax(v:Boolean):Manager
Sets the reconectionDelayMax option, or returns it if no parameters
are passed.