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.

265 lines
7.5 KiB

4 years ago
  1. # socket.io-redis
  2. [![Build Status](https://travis-ci.org/socketio/socket.io-redis.svg?branch=master)](https://travis-ci.org/socketio/socket.io-redis)
  3. [![NPM version](https://badge.fury.io/js/socket.io-redis.svg)](http://badge.fury.io/js/socket.io-redis)
  4. ## How to use
  5. ```js
  6. const io = require('socket.io')(3000);
  7. const redisAdapter = require('socket.io-redis');
  8. io.adapter(redisAdapter({ host: 'localhost', port: 6379 }));
  9. ```
  10. By running socket.io with the `socket.io-redis` adapter you can run
  11. multiple socket.io instances in different processes or servers that can
  12. all broadcast and emit events to and from each other.
  13. So any of the following commands:
  14. ```js
  15. io.emit('hello', 'to all clients');
  16. io.to('room42').emit('hello', "to all clients in 'room42' room");
  17. io.on('connection', (socket) => {
  18. socket.broadcast.emit('hello', 'to all clients except sender');
  19. socket.to('room42').emit('hello', "to all clients in 'room42' room except sender");
  20. });
  21. ```
  22. will properly be broadcast to the clients through the Redis Pub/Sub mechanism.
  23. If you need to emit events to socket.io instances from a non-socket.io
  24. process, you should use [socket.io-emitter](https://github.com/socketio/socket.io-emitter).
  25. ## API
  26. ### adapter(uri[, opts])
  27. `uri` is a string like `localhost:6379` where your redis server
  28. is located. For a list of options see below.
  29. ### adapter(opts)
  30. The following options are allowed:
  31. - `key`: the name of the key to pub/sub events on as prefix (`socket.io`)
  32. - `host`: host to connect to redis on (`localhost`)
  33. - `port`: port to connect to redis on (`6379`)
  34. - `pubClient`: optional, the redis client to publish events on
  35. - `subClient`: optional, the redis client to subscribe to events on
  36. - `requestsTimeout`: optional, after this timeout the adapter will stop waiting from responses to request (`5000ms`)
  37. If you decide to supply `pubClient` and `subClient`, make sure you use
  38. [node_redis](https://github.com/mranney/node_redis) as a client or one
  39. with an equivalent API.
  40. ### RedisAdapter
  41. The redis adapter instances expose the following properties
  42. that a regular `Adapter` does not
  43. - `uid`
  44. - `prefix`
  45. - `pubClient`
  46. - `subClient`
  47. - `requestsTimeout`
  48. ### RedisAdapter#clients(rooms:Array, fn:Function)
  49. Returns the list of client IDs connected to `rooms` across all nodes. See [Namespace#clients(fn:Function)](https://github.com/socketio/socket.io#namespaceclientsfnfunction)
  50. ```js
  51. io.of('/').adapter.clients((err, clients) => {
  52. console.log(clients); // an array containing all connected socket ids
  53. });
  54. io.of('/').adapter.clients(['room1', 'room2'], (err, clients) => {
  55. console.log(clients); // an array containing socket ids in 'room1' and/or 'room2'
  56. });
  57. // you can also use
  58. io.in('room3').clients((err, clients) => {
  59. console.log(clients); // an array containing socket ids in 'room3'
  60. });
  61. ```
  62. ### RedisAdapter#clientRooms(id:String, fn:Function)
  63. Returns the list of rooms the client with the given ID has joined (even on another node).
  64. ```js
  65. io.of('/').adapter.clientRooms('<my-id>', (err, rooms) => {
  66. if (err) { /* unknown id */ }
  67. console.log(rooms); // an array containing every room a given id has joined.
  68. });
  69. ```
  70. ### RedisAdapter#allRooms(fn:Function)
  71. Returns the list of all rooms.
  72. ```js
  73. io.of('/').adapter.allRooms((err, rooms) => {
  74. console.log(rooms); // an array containing all rooms (accross every node)
  75. });
  76. ```
  77. ### RedisAdapter#remoteJoin(id:String, room:String, fn:Function)
  78. Makes the socket with the given id join the room. The callback will be called once the socket has joined the room, or with an `err` argument if the socket was not found.
  79. ```js
  80. io.of('/').adapter.remoteJoin('<my-id>', 'room1', (err) => {
  81. if (err) { /* unknown id */ }
  82. // success
  83. });
  84. ```
  85. ### RedisAdapter#remoteLeave(id:String, room:String, fn:Function)
  86. Makes the socket with the given id leave the room. The callback will be called once the socket has left the room, or with an `err` argument if the socket was not found.
  87. ```js
  88. io.of('/').adapter.remoteLeave('<my-id>', 'room1', (err) => {
  89. if (err) { /* unknown id */ }
  90. // success
  91. });
  92. ```
  93. ### RedisAdapter#remoteDisconnect(id:String, close:Boolean, fn:Function)
  94. Makes the socket with the given id to get disconnected. If `close` is set to true, it also closes the underlying socket. The callback will be called once the socket was disconnected, or with an `err` argument if the socket was not found.
  95. ```js
  96. io.of('/').adapter.remoteDisconnect('<my-id>', true, (err) => {
  97. if (err) { /* unknown id */ }
  98. // success
  99. });
  100. ```
  101. ### RedisAdapter#customRequest(data:Object, fn:Function)
  102. Sends a request to every nodes, that will respond through the `customHook` method.
  103. ```js
  104. // on every node
  105. io.of('/').adapter.customHook = (data, cb) => {
  106. cb('hello ' + data);
  107. }
  108. // then
  109. io.of('/').adapter.customRequest('john', function(err, replies){
  110. console.log(replies); // an array ['hello john', ...] with one element per node
  111. });
  112. ```
  113. ## Client error handling
  114. Access the `pubClient` and `subClient` properties of the
  115. Redis Adapter instance to subscribe to its `error` event:
  116. ```js
  117. const adapter = require('socket.io-redis')('localhost:6379');
  118. adapter.pubClient.on('error', function(){});
  119. adapter.subClient.on('error', function(){});
  120. ```
  121. The errors emitted from `pubClient` and `subClient` will
  122. also be forwarded to the adapter instance:
  123. ```js
  124. const io = require('socket.io')(3000);
  125. const redisAdapter = require('socket.io-redis');
  126. io.adapter(redisAdapter({ host: 'localhost', port: 6379 }));
  127. io.of('/').adapter.on('error', function(){});
  128. ```
  129. ## Custom client (eg: with authentication)
  130. If you need to create a redisAdapter to a redis instance
  131. that has a password, use pub/sub options instead of passing
  132. a connection string.
  133. ```js
  134. const redis = require('redis');
  135. const redisAdapter = require('socket.io-redis');
  136. const pub = redis.createClient(port, host, { auth_pass: "pwd" });
  137. const sub = redis.createClient(port, host, { auth_pass: "pwd" });
  138. io.adapter(redisAdapter({ pubClient: pub, subClient: sub }));
  139. ```
  140. ## With [ioredis](https://github.com/luin/ioredis) client
  141. ### Cluster example
  142. ```js
  143. const io = require('socket.io')(3000);
  144. const redisAdapter = require('socket.io-redis');
  145. const Redis = require('ioredis');
  146. const startupNodes = [
  147. {
  148. port: 6380,
  149. host: '127.0.0.1'
  150. },
  151. {
  152. port: 6381,
  153. host: '127.0.0.1'
  154. }
  155. ];
  156. io.adapter(redisAdapter({
  157. pubClient: new Redis.Cluster(startupNodes),
  158. subClient: new Redis.Cluster(startupNodes)
  159. }));
  160. ```
  161. ### Sentinel Example
  162. ```js
  163. const io = require('socket.io')(3000);
  164. const redisAdapter = require('socket.io-redis');
  165. const Redis = require('ioredis');
  166. const options = {
  167. sentinels: [
  168. { host: 'somehost1', port: 26379 },
  169. { host: 'somehost2', port: 26379 }
  170. ],
  171. name: 'master01'
  172. };
  173. io.adapter(redisAdapter({
  174. pubClient: new Redis(options),
  175. subClient: new Redis(options)
  176. }));
  177. ```
  178. ## Protocol
  179. The `socket.io-redis` adapter broadcasts and receives messages on particularly named Redis channels. For global broadcasts the channel name is:
  180. ```
  181. prefix + '#' + namespace + '#'
  182. ```
  183. In broadcasting to a single room the channel name is:
  184. ```
  185. prefix + '#' + namespace + '#' + room + '#'
  186. ```
  187. - `prefix`: The base channel name. Default value is `socket.io`. Changed by setting `opts.key` in `adapter(opts)` constructor
  188. - `namespace`: See https://github.com/socketio/socket.io#namespace.
  189. - `room` : Used if targeting a specific room.
  190. A number of other libraries adopt this protocol including:
  191. - [socket.io-emitter](https://github.com/socketio/socket.io-emitter)
  192. - [socket.io-python-emitter](https://github.com/GameXG/socket.io-python-emitter)
  193. - [socket.io-emitter-go](https://github.com/stackcats/socket.io-emitter-go)
  194. ## License
  195. MIT