/** * 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 DoctorClient = require('./../models/socket.io/doctor.client'); let Sessions = require('../models/sessions/sessions'); let Users = require('../models/user/users'); let sessions = new Sessions(); let users = new Users(); class SocketHandler { constructor(socketServer) { this._socketServer = socketServer; } /** * 启用事件监听。 */ 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 { if(clientCache.removeByUserId(data.userId)){ log.info("User " + data.userId + " already login"); return; } log.info('User ' + data.userId + ' login'); if(!data.clientType||data.clientType=="patient"){ let patientClient = new PatientClient(socket, socketServer); patientClient.userId = data.userId; patientClient.password = data.password; patientClient.clientType = data.clientType||"patient"; clientCache.addClient(patientClient); users.login(data.userId, 10, '', ''); socket.emit('ack', {}); }else{ let doctorClient = new DoctorClient(socket, socketServer); doctorClient.userId = data.userId; doctorClient.password = data.password; doctorClient.clientType = data.clientType; doctorClient.sessionId = data.sessionId; clientCache.addClient(doctorClient); socket.emit('ack', {}); } } }); // 接收客户端消息 socket.on('message', function (data) { log.info('Got message from ' + clientCache.findBySocket(socket).userId); let sessionId = data.session_id; let message = data.message; message.timestamp = new Date(); /*sessions.createSession(sessionId, "Let's talk!", 1, ['504a0bcddb1e4e37a0306b39c51900b5', 'cd92414c-5b06-11e6-8344-fa163e8aee56'], function (err, res) { sessions.saveMessageBySession(sessionId, message); });*/ sessions.saveMessageBySession(sessionId, message); }); // 客户端退出 socket.on('logout', function (data) { let client = clientCache.findBySocket(socket); if (client) { log.info('User logout: ' + client.userId); clientCache.removeByUserId(client.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;