client.cache.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. if(client){
  29. this._clientsBySocket.delete(client.socket);
  30. this._clientsByTypeAndUserId.delete(client.userId+":"+client.clientType);
  31. }
  32. }
  33. removeByUserSocket(socket) {
  34. var client = this.findBySocket(socket);
  35. if (client) {
  36. this._clientsByUserId.delete(client.userId);
  37. this._clientsBySocket.delete(socket);
  38. this._clientsByTypeAndUserId.delete(client.userId+":"+client.clientType)
  39. }
  40. }
  41. findById(userId) {
  42. return this._clientsByUserId.get(userId);
  43. }
  44. findByIdAndType(userId,type){
  45. return this._clientsByTypeAndUserId.get(userId+":"+type);
  46. }
  47. findBySocket(socket) {
  48. return this._clientsBySocket.get(socket);
  49. }
  50. static clientCache() {
  51. if (clientCache === null) {
  52. clientCache = new ClientCache();
  53. }
  54. return clientCache;
  55. }
  56. }
  57. module.exports = ClientCache;