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.

374 lines
10 KiB

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