socket.handler.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 userId = clientCache.findBySocket(socket).userId;
  52. log.info('User logout: ' + userId);
  53. clientCache.removeByUserId(userId);
  54. });
  55. // 客户端断开
  56. socket.on('disconnect', function () {
  57. let patientClient = clientCache.findBySocket(socket);
  58. if(patientClient){log.info("User disconnect: ", patientClient.userId);
  59. clientCache.removeByUserSocket(socket);
  60. }
  61. });
  62. socket.emit('welcome', {message: 'Welcome to connect IM server, please login.'});
  63. });
  64. }
  65. }
  66. module.exports = SocketHandler;