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