socketioMEANseed/server/node_modules/socket.io/Readme.md
server/node_modules/socket.io/Readme.mdRaw
1
2# socket.io
3
4[](https://travis-ci.org/socketio/socket.io)
5[](https://david-dm.org/socketio/socket.io)
6[](https://david-dm.org/socketio/socket.io#info=devDependencies)
7[](https://www.npmjs.com/package/socket.io)
8
9[](http://slack.socket.io)
10
11## How to use
12
13The following example attaches socket.io to a plain Node.JS
14HTTP server listening on port `3000`.
15
16```js
17var server = require('http').createServer();
18var io = require('socket.io')(server);
19io.on('connection', function(client){
20 client.on('event', function(data){});
21 client.on('disconnect', function(){});
22});
23server.listen(3000);
24```
25
26### Standalone
27
28```js
29var io = require('socket.io')();
30io.on('connection', function(client){});
31io.listen(3000);
32```
33
34### In conjunction with Express
35
36Starting with **3.0**, express applications have become request handler
37functions that you pass to `http` or `http` `Server` instances. You need
38to pass the `Server` to `socket.io`, and not the express application
39function.
40
41```js
42var app = require('express')();
43var server = require('http').createServer(app);
44var io = require('socket.io')(server);
45io.on('connection', function(){ /* … */ });
46server.listen(3000);
47```
48
49### In conjunction with Koa
50
51Like Express.JS, Koa works by exposing an application as a request
52handler function, but only by calling the `callback` method.
53
54```js
55var app = require('koa')();
56var server = require('http').createServer(app.callback());
57var io = require('socket.io')(server);
58io.on('connection', function(){ /* … */ });
59server.listen(3000);
60```
61
62## API
63
64### Server
65
66 Exposed by `require('socket.io')`.
67
68### Server()
69
70 Creates a new `Server`. Works with and without `new`:
71
72 ```js
73 var io = require('socket.io')();
74 // or
75 var Server = require('socket.io');
76 var io = new Server();
77 ```
78
79### Server(opts:Object)
80
81 Optionally, the first or second argument (see below) of the `Server`
82 constructor can be an options object.
83
84 The following options are supported:
85
86 - `serveClient` sets the value for Server#serveClient()
87 - `path` sets the value for Server#path()
88
89 The same options passed to socket.io are always passed to
90 the `engine.io` `Server` that gets created. See engine.io
91 [options](https://github.com/socketio/engine.io#methods-1)
92 as reference.
93
94### Server(srv:http#Server, opts:Object)
95
96 Creates a new `Server` and attaches it to the given `srv`. Optionally
97 `opts` can be passed.
98
99### Server(port:Number, opts:Object)
100
101 Binds socket.io to a new `http.Server` that listens on `port`.
102
103### Server#serveClient(v:Boolean):Server
104
105 If `v` is `true` the attached server (see `Server#attach`) will serve
106 the client files. Defaults to `true`.
107
108 This method has no effect after `attach` is called.
109
110 ```js
111 // pass a server and the `serveClient` option
112 var io = require('socket.io')(http, { serveClient: false });
113
114 // or pass no server and then you can call the method
115 var io = require('socket.io')();
116 io.serveClient(false);
117 io.attach(http);
118 ```
119
120 If no arguments are supplied this method returns the current value.
121
122### Server#path(v:String):Server
123
124 Sets the path `v` under which `engine.io` and the static files will be
125 served. Defaults to `/socket.io`.
126
127 If no arguments are supplied this method returns the current value.
128
129### Server#adapter(v:Adapter):Server
130
131 Sets the adapter `v`. Defaults to an instance of the `Adapter` that
132 ships with socket.io which is memory based. See
133 [socket.io-adapter](https://github.com/socketio/socket.io-adapter).
134
135 If no arguments are supplied this method returns the current value.
136
137### Server#origins(v:String):Server
138
139 Sets the allowed origins `v`. Defaults to any origins being allowed.
140
141 If no arguments are supplied this method returns the current value.
142
143### Server#origins(v:Function):Server
144
145 Sets the allowed origins as dynamic function. Function takes two arguments `origin:String` and `callback(error, success)`, where `success` is a boolean value indicating whether origin is allowed or not.
146
147 __Potential drawbacks__:
148 * in some situations, when it is not possible to determine `origin` it may have value of `*`
149 * As this function will be executed for every request, it is advised to make this function work as fast as possible
150 * If `socket.io` is used together with `Express`, the CORS headers will be affected only for `socket.io` requests. For Express can use [cors](https://github.com/expressjs/cors).
151
152
153### Server#sockets:Namespace
154
155 The default (`/`) namespace.
156
157### Server#attach(srv:http#Server, opts:Object):Server
158
159 Attaches the `Server` to an engine.io instance on `srv` with the
160 supplied `opts` (optionally).
161
162### Server#attach(port:Number, opts:Object):Server
163
164 Attaches the `Server` to an engine.io instance that is bound to `port`
165 with the given `opts` (optionally).
166
167### Server#listen
168
169 Synonym of `Server#attach`.
170
171### Server#bind(srv:engine#Server):Server
172
173 Advanced use only. Binds the server to a specific engine.io `Server`
174 (or compatible API) instance.
175
176### Server#onconnection(socket:engine#Socket):Server
177
178 Advanced use only. Creates a new `socket.io` client from the incoming
179 engine.io (or compatible API) `socket`.
180
181### Server#of(nsp:String):Namespace
182
183 Initializes and retrieves the given `Namespace` by its pathname
184 identifier `nsp`.
185
186 If the namespace was already initialized it returns it immediately.
187
188### Server#emit
189
190 Emits an event to all connected clients. The following two are
191 equivalent:
192
193 ```js
194 var io = require('socket.io')();
195 io.sockets.emit('an event sent to all connected clients');
196 io.emit('an event sent to all connected clients');
197 ```
198
199 For other available methods, see `Namespace` below.
200
201### Server#close([fn:Function])
202
203 Closes socket.io server.
204
205 The optional `fn` is passed to the `server.close([callback])` method of the
206 core `net` module and is called on error or when all connections are closed.
207 The callback is expected to implement the common single argument `err`
208 signature (if any).
209
210 ```js
211 var Server = require('socket.io');
212 var PORT = 3030;
213 var server = require('http').Server();
214
215 var io = Server(PORT);
216
217 io.close(); // Close current server
218
219 server.listen(PORT); // PORT is free to use
220
221 io = Server(server);
222 ```
223
224### Server#use
225
226 See `Namespace#use` below.
227
228### Namespace
229
230 Represents a pool of sockets connected under a given scope identified
231 by a pathname (eg: `/chat`).
232
233 By default the client always connects to `/`.
234
235#### Events
236
237 - `connection` / `connect`. Fired upon a connection.
238
239 Parameters:
240 - `Socket` the incoming socket.
241
242### Namespace#name:String
243
244 The namespace identifier property.
245
246### Namespace#connected:Object<Socket>
247
248 Hash of `Socket` objects that are connected to this namespace indexed
249 by `id`.
250
251### Namespace#clients(fn:Function)
252
253 Gets a list of client IDs connected to this namespace (across all nodes if applicable).
254
255 An example to get all clients in a namespace:
256
257 ```js
258 var io = require('socket.io')();
259 io.of('/chat').clients(function(error, clients){
260 if (error) throw error;
261 console.log(clients); // => [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD]
262 });
263 ```
264
265 An example to get all clients in namespace's room:
266
267 ```js
268 var io = require('socket.io')();
269 io.of('/chat').in('general').clients(function(error, clients){
270 if (error) throw error;
271 console.log(clients); // => [Anw2LatarvGVVXEIAAAD]
272 });
273 ```
274
275 As with broadcasting, the default is all clients from the default namespace ('/'):
276
277 ```js
278 var io = require('socket.io')();
279 io.clients(function(error, clients){
280 if (error) throw error;
281 console.log(clients); // => [6em3d4TJP8Et9EMNAAAA, G5p55dHhGgUnLUctAAAB]
282 });
283 ```
284
285### Namespace#use(fn:Function):Namespace
286
287 Registers a middleware, which is a function that gets executed for
288 every incoming `Socket`, and receives as parameters the socket and a
289 function to optionally defer execution to the next registered
290 middleware.
291
292 ```js
293 var io = require('socket.io')();
294 io.use(function(socket, next){
295 if (socket.request.headers.cookie) return next();
296 next(new Error('Authentication error'));
297 });
298 ```
299
300 Errors passed to middleware callbacks are sent as special `error`
301 packets to clients.
302
303### Socket
304
305 A `Socket` is the fundamental class for interacting with browser
306 clients. A `Socket` belongs to a certain `Namespace` (by default `/`)
307 and uses an underlying `Client` to communicate.
308
309 It should be noted the `Socket` doesn't relate directly to the actual
310 underlying TCP/IP `socket` and it is only the name of the class.
311
312### Socket#use(fn:Function):Socket
313
314 Registers a middleware, which is a function that gets executed for
315 every incoming `Packet` and receives as parameter the packet and a
316 function to optionally defer execution to the next registered
317 middleware.
318
319 ```js
320 var io = require('socket.io')();
321 io.on('connection', function(socket){
322 socket.use(function(packet, next){
323 if (packet.doge === true) return next();
324 next(new Error('Not a doge error'));
325 });
326 ```
327
328 Errors passed to middleware callbacks are sent as special `error`
329 packets to clients.
330
331### Socket#rooms:Object
332
333 A hash of strings identifying the rooms this client is in, indexed by
334 room name.
335
336### Socket#client:Client
337
338 A reference to the underlying `Client` object.
339
340### Socket#conn:Socket
341
342 A reference to the underlying `Client` transport connection (engine.io
343 `Socket` object). This allows access to the IO transport layer, which
344 still (mostly) abstracts the actual TCP/IP socket.
345
346### Socket#request:Request
347
348 A getter proxy that returns the reference to the `request` that
349 originated the underlying engine.io `Client`. Useful for accessing
350 request headers such as `Cookie` or `User-Agent`.
351
352### Socket#id:String
353
354 A unique identifier for the session, that comes from the
355 underlying `Client`.
356
357### Socket#emit(name:String[, …]):Socket
358
359 Emits an event identified by the string `name` to the client.
360 Any other parameters can be included.
361
362 All datastructures are supported, including `Buffer`. JavaScript
363 functions can't be serialized/deserialized.
364
365 ```js
366 var io = require('socket.io')();
367 io.on('connection', function(client){
368 client.emit('an event', { some: 'data' });
369 });
370 ```
371
372### Socket#join(name:String[, fn:Function]):Socket
373
374 Adds the client to the `room`, and fires optionally a callback `fn`
375 with `err` signature (if any).
376
377 The client is automatically a member of a room identified with its
378 session id (see `Socket#id`).
379
380 The mechanics of joining rooms are handled by the `Adapter`
381 that has been configured (see `Server#adapter` above), defaulting to
382 [socket.io-adapter](https://github.com/socketio/socket.io-adapter).
383
384### Socket#leave(name:String[, fn:Function]):Socket
385
386 Removes the client from `room`, and fires optionally a callback `fn`
387 with `err` signature (if any).
388
389 **Rooms are left automatically upon disconnection**.
390
391 The mechanics of leaving rooms are handled by the `Adapter`
392 that has been configured (see `Server#adapter` above), defaulting to
393 [socket.io-adapter](https://github.com/socketio/socket.io-adapter).
394
395### Socket#to(room:String):Socket
396
397 Sets a modifier for a subsequent event emission that the event will
398 only be _broadcasted_ to clients that have joined the given `room`.
399
400 To emit to multiple rooms, you can call `to` several times.
401
402 ```js
403 var io = require('socket.io')();
404 io.on('connection', function(client){
405 client.to('others').emit('an event', { some: 'data' });
406 });
407 ```
408
409### Socket#in(room:String):Socket
410
411 Same as `Socket#to`
412
413### Socket#compress(v:Boolean):Socket
414
415 Sets a modifier for a subsequent event emission that the event data will
416 only be _compressed_ if the value is `true`. Defaults to `true` when you don't call the method.
417
418 ```js
419 var io = require('socket.io')();
420 io.on('connection', function(client){
421 client.compress(false).emit('an event', { some: 'data' });
422 });
423 ```
424
425### Socket#disconnect(close:Boolean):Socket
426
427 Disconnects this client. If value of close is `true`, closes the underlying connection.
428 Otherwise, it just disconnects the namespace.
429
430#### Events
431
432- `disconnect`
433 - Fired upon disconnection.
434 - **Arguments**
435 - `String`: the reason of the disconnection (either client or server-side)
436- `error`
437 - Fired when an error occurs.
438 - **Arguments**
439 - `Object`: error data
440- `disconnecting`
441 - Fired when the client is going to be disconnected (but hasn't left its `rooms` yet).
442 - **Arguments**
443 - `String`: the reason of the disconnection (either client or server-side)
444
445These are reserved events (along with `connect`, `newListener` and `removeListener`) which cannot be used as event names.
446
447
448### Client
449
450 The `Client` class represents an incoming transport (engine.io)
451 connection. A `Client` can be associated with many multiplexed `Socket`s
452 that belong to different `Namespace`s.
453
454### Client#conn
455
456 A reference to the underlying `engine.io` `Socket` connection.
457
458### Client#request
459
460 A getter proxy that returns the reference to the `request` that
461 originated the engine.io connection. Useful for accessing
462 request headers such as `Cookie` or `User-Agent`.
463
464## Debug / logging
465
466Socket.IO is powered by [debug](https://github.com/visionmedia/debug).
467In order to see all the debug output, run your app with the environment variable
468`DEBUG` including the desired scope.
469
470To see the output from all of Socket.IO's debugging scopes you can use:
471
472```
473DEBUG=socket.io* node myapp
474```
475
476## Testing
477
478```
479npm test
480```
481This runs the `gulp` task `test`. By default the test will be run with the source code in `lib` directory.
482
483Set the environmental variable `TEST_VERSION` to `compat` to test the transpiled es5-compat version of the code.
484
485The `gulp` task `test` will always transpile the source code into es5 and export to `dist` first before running the test.
486
487## License
488
489[MIT](LICENSE)