123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- /**
- * author: Sand
- * since: 2016/11/17
- */
- "use strict";
- let log = require("../util/log.js");
- let clientCache = require('../models/socket.io/client.cache').clientCache();
- let PatientClient = require('./../models/socket.io/patient.client');
- let Doctor = require('../models/doctor');
- let doctor = new Doctor();
- let Group = require('../models/group');
- let group = new Group();
- class SocketHandler{
- constructor(socketServer){
- this._socketServer = socketServer;
- }
- /**
- * 启用事件监听。
- *
- * @param socket
- */
- start(){
- let socketServer = this._socketServer;
- socketServer.sockets.on('connection', function (socket) {
- // 客户端注册
- socket.on('login', function (data) {
- if(!data.userId){
- socketServer.sockets.emit('error', {message: 'Missing fields(s): userId.'});
- } else{
- log.info('User login: ' + data.userId);
- let patientClient = new PatientClient(socket, socketServer);
- patientClient.userId = data.userId;
- patientClient.password = data.password;
- clientCache.addClient(patientClient);
- socketServer.sockets.emit('ack', {});
- }
- });
- // 接收客户端消息
- socket.on('message', function (data) {
- log.info('Got message from ' + clientCache.findBySocket(socket).userId);
- let targetType = data.targetType;
- let message = data.message;
- if(targetType == 1){
- doctor.sendMessage(message);
- } else {
- group.sendMessage(message);
- }
- });
- // 客户端退出
- socket.on('logout', function (data) {
- let userId = clientCache.findBySocket(socket).userId;
- log.info('User logout: ' + userId);
- clientCache.removeByUserId(userId);
- });
- // 客户端断开
- socket.on('disconnect', function () {
- let patientClient = clientCache.findBySocket(socket);
- if(patientClient){log.info("User disconnect: ", patientClient.userId);
- clientCache.removeByUserSocket(socket);
- }
- });
- socket.emit('welcome', {message: 'Welcome to connect IM server, please login.'});
- });
- }
- }
- module.exports = SocketHandler;
|