You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

489 lines
14 KiB

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