client.cache.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 userId = this.findBySocket(socket);
  30. this._clientsByUserId.delete(userId);
  31. this._clientsBySocket.delete(socket);
  32. }
  33. findById(userId){
  34. return this._clientsByUserId.get(userId);
  35. }
  36. findBySocket(socket){
  37. return this._clientsBySocket.get(socket);
  38. }
  39. static clientCache(){
  40. if(clientCache === null){
  41. clientCache = new ClientCache();
  42. }
  43. return clientCache;
  44. }
  45. }
  46. module.exports = ClientCache;