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