socket.handler.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /**
  2. * author: Sand
  3. * since: 2016/11/17
  4. */
  5. "use strict";
  6. let log = require("../util/log.js");
  7. let clientCache = require('../models/socket.io/client.cache').clientCache();
  8. let PatientClient = require('./../models/socket.io/patient.client');
  9. let Doctor = require('../models/doctor');
  10. let doctor = new Doctor();
  11. let Group = require('../models/group');
  12. let group = new Group();
  13. class SocketHandler {
  14. constructor(socketServer) {
  15. this._socketServer = socketServer;
  16. }
  17. /**
  18. * 启用事件监听。
  19. *
  20. * @param socket
  21. */
  22. start() {
  23. let socketServer = this._socketServer;
  24. socketServer.sockets.on('connection', function (socket) {
  25. // 客户端注册
  26. socket.on('login', function (data) {
  27. if (!data.userId) {
  28. socketServer.sockets.emit('error', {message: 'Missing fields(s): userId.'});
  29. } else {
  30. log.info('User login: ' + data.userId);
  31. let patientClient = new PatientClient(socket, socketServer);
  32. patientClient.userId = data.userId;
  33. patientClient.password = data.password;
  34. clientCache.addClient(patientClient);
  35. socketServer.sockets.emit('ack', {});
  36. }
  37. });
  38. // 接收客户端消息
  39. socket.on('message', function (data) {
  40. log.info('Got message from ' + clientCache.findBySocket(socket).userId);
  41. let targetType = data.targetType;
  42. let message = data.message;
  43. if (targetType == 1) {
  44. doctor.sendMessage(message);
  45. } else {
  46. group.sendMessage(message);
  47. }
  48. });
  49. // 客户端退出
  50. socket.on('logout', function (data) {
  51. let client = clientCache.findBySocket(socket);
  52. if (client) {
  53. log.info('User logout: ' + client.userId);
  54. clientCache.removeByUserId(client.userId);
  55. }
  56. });
  57. // 客户端断开
  58. socket.on('disconnect', function () {
  59. let patientClient = clientCache.findBySocket(socket);
  60. if (patientClient) {
  61. log.info("User disconnect: ", patientClient.userId);
  62. clientCache.removeByUserSocket(socket);
  63. }
  64. });
  65. socket.emit('welcome', {message: 'Welcome to connect IM server, please login.'});
  66. });
  67. }
  68. }
  69. module.exports = SocketHandler;