client.cache.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. this._clientsByTypeAndUserId = new Map();
  15. }
  16. get clients() {
  17. return this._clientsByUserId;
  18. }
  19. addClient(client) {
  20. this._clientsByUserId.set(client.userId, client);
  21. this._clientsBySocket.set(client.socket, client);
  22. this._clientsByTypeAndUserId.set(client.userId+":"+client.clientType,client);
  23. //log.info('Current clients: ', this.clients);
  24. }
  25. removeByUserId(userId) {
  26. var client = this.findById(userId);
  27. this._clientsByUserId.delete(userId);
  28. this._clientsBySocket.delete(client.socket);
  29. this._clientsByTypeAndUserId.delete(client.userId+":"+client.clientType)
  30. }
  31. removeByUserSocket(socket) {
  32. var client = this.findBySocket(socket);
  33. if (client) {
  34. this._clientsByUserId.delete(client.userId);
  35. this._clientsBySocket.delete(socket);
  36. this._clientsByTypeAndUserId.delete(client.userId+":"+client.clientType)
  37. }
  38. }
  39. findById(userId) {
  40. return this._clientsByUserId.get(userId);
  41. }
  42. findByIdAndType(userId,type){
  43. this._clientsByTypeAndUserId.get(userId+":"+type);
  44. }
  45. findBySocket(socket) {
  46. return this._clientsBySocket.get(socket);
  47. }
  48. static clientCache() {
  49. if (clientCache === null) {
  50. clientCache = new ClientCache();
  51. }
  52. return clientCache;
  53. }
  54. }
  55. module.exports = ClientCache;