3 Socket.IO is a Node.JS project that makes WebSockets and realtime possible in
4 all browsers. It also enhances WebSockets by providing built-in multiplexing,
5 horizontal scalability, automatic JSON encoding/decoding, and more.
15 First, require `socket.io`:
18 var io = require('socket.io');
21 Next, attach it to a HTTP/HTTPS server. If you're using the fantastic `express`
28 , server = require('http').createServer(app)
29 , io = io.listen(server);
33 io.sockets.on('connection', function (socket) {
34 socket.emit('news', { hello: 'world' });
35 socket.on('my other event', function (data) {
44 var app = express.createServer()
45 , io = io.listen(app);
49 io.sockets.on('connection', function (socket) {
50 socket.emit('news', { hello: 'world' });
51 socket.on('my other event', function (data) {
57 Finally, load it from the client side code:
60 <script src="/socket.io/socket.io.js"></script>
62 var socket = io.connect('http://localhost');
63 socket.on('news', function (data) {
65 socket.emit('my other event', { my: 'data' });
70 For more thorough examples, look at the `examples/` directory.
74 ### Sending and receiving events.
76 Socket.IO allows you to emit and receive custom events.
77 Besides `connect`, `message` and `disconnect`, you can emit custom events:
80 // note, io.listen(<port>) will create a http server for you
81 var io = require('socket.io').listen(80);
83 io.sockets.on('connection', function (socket) {
84 io.sockets.emit('this', { will: 'be received by everyone' });
86 socket.on('private message', function (from, msg) {
87 console.log('I received a private message by ', from, ' saying ', msg);
90 socket.on('disconnect', function () {
91 io.sockets.emit('user disconnected');
96 ### Storing data associated to a client
98 Sometimes it's necessary to store data associated with a client that's
99 necessary for the duration of the session.
104 var io = require('socket.io').listen(80);
106 io.sockets.on('connection', function (socket) {
107 socket.on('set nickname', function (name) {
108 socket.set('nickname', name, function () { socket.emit('ready'); });
111 socket.on('msg', function () {
112 socket.get('nickname', function (err, name) {
113 console.log('Chat message by ', name);
123 var socket = io.connect('http://localhost');
125 socket.on('connect', function () {
126 socket.emit('set nickname', prompt('What is your nickname?'));
127 socket.on('ready', function () {
128 console.log('Connected !');
129 socket.emit('msg', prompt('What is your message?'));
135 ### Restricting yourself to a namespace
137 If you have control over all the messages and events emitted for a particular
138 application, using the default `/` namespace works.
140 If you want to leverage 3rd-party code, or produce code to share with others,
141 socket.io provides a way of namespacing a `socket`.
143 This has the benefit of `multiplexing` a single connection. Instead of
144 socket.io using two `WebSocket` connections, it'll use one.
146 The following example defines a socket that listens on '/chat' and one for
152 var io = require('socket.io').listen(80);
156 .on('connection', function (socket) {
157 socket.emit('a message', { that: 'only', '/chat': 'will get' });
158 chat.emit('a message', { everyone: 'in', '/chat': 'will get' });
163 .on('connection', function (socket) {
164 socket.emit('item', { news: 'item' });
172 var chat = io.connect('http://localhost/chat')
173 , news = io.connect('http://localhost/news');
175 chat.on('connect', function () {
179 news.on('news', function () {
185 ### Sending volatile messages.
187 Sometimes certain messages can be dropped. Let's say you have an app that
188 shows realtime tweets for the keyword `bieber`.
190 If a certain client is not ready to receive messages (because of network slowness
191 or other issues, or because he's connected through long polling and is in the
192 middle of a request-response cycle), if he doesn't receive ALL the tweets related
193 to bieber your application won't suffer.
195 In that case, you might want to send those messages as volatile messages.
200 var io = require('socket.io').listen(80);
202 io.sockets.on('connection', function (socket) {
203 var tweets = setInterval(function () {
204 getBieberTweet(function (tweet) {
205 socket.volatile.emit('bieber tweet', tweet);
209 socket.on('disconnect', function () {
210 clearInterval(tweets);
217 In the client side, messages are received the same way whether they're volatile
220 ### Getting acknowledgements
222 Sometimes, you might want to get a callback when the client confirmed the message
225 To do this, simply pass a function as the last parameter of `.send` or `.emit`.
226 What's more, when you use `.emit`, the acknowledgement is done by you, which
227 means you can also pass data along:
232 var io = require('socket.io').listen(80);
234 io.sockets.on('connection', function (socket) {
235 socket.on('ferret', function (name, fn) {
245 var socket = io.connect(); // TIP: .connect with no args does auto-discovery
246 socket.on('connect', function () { // TIP: you can avoid listening on `connect` and listen on events directly too!
247 socket.emit('ferret', 'tobi', function (data) {
248 console.log(data); // data will be 'woot'
254 ### Broadcasting messages
256 To broadcast, simply add a `broadcast` flag to `emit` and `send` method calls.
257 Broadcasting means sending a message to everyone else except for the socket
263 var io = require('socket.io').listen(80);
265 io.sockets.on('connection', function (socket) {
266 socket.broadcast.emit('user connected');
267 socket.broadcast.json.send({ a: 'message' });
273 Sometimes you want to put certain sockets in the same room, so that it's easy
274 to broadcast to all of them together.
276 Think of this as built-in channels for sockets. Sockets `join` and `leave`
277 rooms in each socket.
282 var io = require('socket.io').listen(80);
284 io.sockets.on('connection', function (socket) {
285 socket.join('justin bieber fans');
286 socket.broadcast.to('justin bieber fans').emit('new fan');
287 io.sockets.in('rammstein fans').emit('new non-fan');
291 ### Using it just as a cross-browser WebSocket
293 If you just want the WebSocket semantics, you can do that too.
294 Simply leverage `send` and listen on the `message` event:
299 var io = require('socket.io').listen(80);
301 io.sockets.on('connection', function (socket) {
302 socket.on('message', function () { });
303 socket.on('disconnect', function () { });
311 var socket = io.connect('http://localhost/');
312 socket.on('connect', function () {
315 socket.on('message', function (msg) {
322 ### Changing configuration
324 Configuration in socket.io is TJ-style:
329 var io = require('socket.io').listen(80);
331 io.configure(function () {
332 io.set('transports', ['websocket', 'flashsocket', 'xhr-polling']);
335 io.configure('development', function () {
336 io.set('transports', ['websocket', 'xhr-polling']);
345 Copyright (c) 2011 Guillermo Rauch <guillermo@learnboost.com>
347 Permission is hereby granted, free of charge, to any person obtaining
348 a copy of this software and associated documentation files (the
349 'Software'), to deal in the Software without restriction, including
350 without limitation the rights to use, copy, modify, merge, publish,
351 distribute, sublicense, and/or sell copies of the Software, and to
352 permit persons to whom the Software is furnished to do so, subject to
353 the following conditions:
355 The above copyright notice and this permission notice shall be
356 included in all copies or substantial portions of the Software.
358 THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
359 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
360 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
361 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
362 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
363 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
364 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.