每个中间件都要判断context.req.action,而这个context.res就是浏览器端或客户端发送的数据。怎么消除这个频繁的if判断呢? 我们实现一个简单的消息处理路由。
路由定义消息路由中间件
messageRouteMiddleware.js
export default (routes) => { return async (context, next) => { if (routes[context.req.action]) { await routes[context.req.action](context,next); } else { console.log(context.req) next(); } } }定义路由
router.js
export default { roomChatMessage:function(context,next){ //可以在这里持久化消息,将消息发送给其它群聊客户端,以及其它业务逻辑 console.log(context.req); next(); }, privateChatMessage:function(context,next){ //可以在这里持久化消息,将消息发送给私聊客户端,以及其它业务逻辑 console.log(context.req); next(); } }使用:
easySocket.messageUse(messageRouteMiddleware(router)) 跨进程事件上一篇文章已经介绍了跨进程事件,这里直接说实现。
使用Node的原生事件模块
import compose from './compose'; const WebSocket = require('ws'); var EventEmitter = require('events').EventEmitter; export default class EasySocket extends EventEmitter { constructor() { ... this.remoteEmitMiddleware = []; ... this.remoteEmitFn = Promise.resolve(); } ... remoteEmitUse(fn, runtime) { this.remoteEmitMiddleware.push(fn); if (runtime) { this.remoteEmitFn = compose(this.remoteEmitMiddleware); } return this; } listen(config) { this.socket = new WebSocket.Server(config); ... this.remoteEmitFn = compose(this.remoteEmitMiddleware); ... } emit(event, args, isLocal = false) { let arr = [event, args]; if (isLocal) { super.emit.apply(this, arr); return this; } let evt = { event: event, args: args } let remoteEmitContext = { server: this, event: evt }; this.remoteEmitFn(remoteEmitContext).catch(error => { console.log(error) }) return this; } } 最后源码地址:easy-socket-node
基于easy-socket-node与easy-socket-browser一个完整例子:
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> </body> <script src="http://unpkg.com/easy-socket-browser@1.1.1/lib/easy-socket.min.js"></script> <script> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> </body> <script src="http://unpkg.com/easy-socket-browser@1.1.1/lib/easy-socket.min.js"></script> <script> var client = new EasySocket({ name: 'demo', autoReconnect: true, pingMsg: '{"type":"event","event":"ping","args":"ping"}'//模拟emit 消息体 }); client.openUse((context, next) => { console.log("open"); next(); }) .closeUse((context, next) => { console.log("close"); next(); }).errorUse((context, next) => { console.log("error", context.event); next(); }).messageUse((context, next) => { if (context.res.type === 'event') { context.client.emit(context.res.event, context.res.args, true); } next(); }) .reconnectUse((context, next) => { console.log('正在进行重连') next(); }) .remoteEmitUse((context, next) => { let client = context.client; let event = context.event; if (client.socket.readyState !== 1) { console.log("连接已断开"); } else { client.socket.send(JSON.stringify({ type: 'event', event: event.event, args: event.args })); next(); } }); client.connect('ws://localhost:3001'); var msg = 1; setInterval(() => { client.emit('chatMessage', msg++) }, 3000); client.on("serverMessage", (data) => { console.log("serverMessage:" + data) }); </script> </html> </script> </html>server.js
var EasySocket = require('easy-socket-node').default; var config = { port: 3001, perMessageDeflate: { zlibDeflateOptions: { // See zlib defaults. chunkSize: 1024, memLevel: 7, level: 3, }, zlibInflateOptions: { chunkSize: 10 * 1024 }, // Other options settable: clientNoContextTakeover: true, // Defaults to negotiated value. serverNoContextTakeover: true, // Defaults to negotiated value. //clientMaxWindowBits: 10, // Defaults to negotiated value. serverMaxWindowBits: 10, // Defaults to negotiated value. // Below options specified as default values. concurrencyLimit: 10, // Limits zlib concurrency for perf. threshold: 1024, // Size (in bytes) below which messages // should not be compressed. } } var remoteEmitMiddleware = (context, next) => { var server = context.server; var event = context.event; for (let client of server.clients.values()) { client.readyState == 1 && client.send(makeEventMessage(event)); } } function makeEventMessage(event) { return JSON.stringify({ type: 'event', event: event.event, args: event.args }) } var messageRouteMiddleware = (routes) => { return (context, next) => { if (context.req.type === 'event') { if (routes[context.req.event]) { routes[context.req.event](context, next); } else { context.server.emit(context.req.event, context.req.args);//将会直接触发remoteEmitMiddleware 中间件的调用 next(); } } else { next(); } } } var router = { chatMessage: (context, next) => { var req = context.req; context.server.emit('serverMessage', req.args); } } var server = new EasySocket(); server .connectionUse((context, next) => { context.server.clients.set(1, context.client) console.log('new connection') }) .closeUse((context, next) => { console.log('close') }) .messageUse(messageRouteMiddleware(router)) .remoteEmitUse(remoteEmitMiddleware) .listen(config) console.log('Now start WebSocket server on port ' + config.port + '...')运行过程,可以停止后端服务,然后再启动,测下心跳重连
实现的聊天室例子:
聊天室前端源码:lazy-mock-im
聊天室服务端源码:lazy-mock