client.cache.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * 客户端缓存池,记录各用户的socket与相应的client.
  3. *
  4. * author: Sand Wen
  5. * since: 2016.11.19
  6. */
  7. "use strict";
  8. var log = require('../../util/log');
  9. var clientCache = null;
  10. class ClientCache {
  11. constructor() {
  12. this._clientsBySocket = new Map();
  13. this._clientsByUserId = new Map();
  14. }
  15. get clients() {
  16. return this._clientsByUserId;
  17. }
  18. addClient(client) {
  19. this._clientsByUserId.set(client.userId, client);
  20. this._clientsBySocket.set(client.socket, client);
  21. //log.info('Current clients: ', this.clients);
  22. }
  23. removeByUserId(userId) {
  24. var socket = this.findById(userId);
  25. this._clientsByUserId.delete(userId);
  26. this._clientsBySocket.delete(socket);
  27. }
  28. removeByUserSocket(socket) {
  29. var client = this.findBySocket(socket);
  30. if (client) {
  31. this._clientsByUserId.delete(client.userId);
  32. this._clientsBySocket.delete(socket);
  33. }
  34. }
  35. findById(userId) {
  36. return this._clientsByUserId.get(userId);
  37. }
  38. findBySocket(socket) {
  39. return this._clientsBySocket.get(socket);
  40. }
  41. static clientCache() {
  42. if (clientCache === null) {
  43. clientCache = new ClientCache();
  44. }
  45. return clientCache;
  46. }
  47. }
  48. module.exports = ClientCache;