wenf00 2019-11-08
原文地址:websocket 实战——好友聊天
还不了解 websocket 的同鞋,请先学习阮一峰老师的 WebSocket 教程
WebSocket
,后端采用 express-ws 库
实现聊天通信先撸个简单版本,能够实现用户与服务器之间的通信
class WsRequest { ws: WebSocket constructor(url: string) { this.ws = new WebSocket(url) this.initListeners() } initListeners() { this.ws.onopen = _event => console.log('client connect') this.ws.onmessage = event => console.log(`来自服务器的信息:${event.data}`) this.ws.onclose = _event => console.log('client disconnect') } send(content: string) { this.ws.send(content) } close() { this.ws.close() } } // 使用 const ws = new WsRequest('your_websocket_url') // 如: ws://localhost:4000/ws ws.send('hello from user')
import expressWs, { Application, Options } from 'express-ws'; import ws, { Data } from 'ws'; import { Server as hServer } from 'http'; import { Server as hsServer } from 'https'; class WsRouter { static instance: WsRouter; wsServer: expressWs.Instance; clientMap: Map<string, ws>; // 保存所有连接的用户 id constructor( private path: string, private app: Application, private server?: hServer | hsServer, private options?: Options ) { this.wsServer = expressWs(this.app, this.server, this.options); this.app.ws(this.path, this.wsMiddleWare); this.clientMap = new Map(); } static getInstance(path: string, app: Application, server?: hServer | hsServer, options: Options = {}) { if (!this.instance) { this.instance = new WsRouter(path, app, server, options); } return this.instance; } wsMiddleWare = (wServer: any, _req: any) => { this.clientMap.set(id, wServer); this.broadcast('hello from server'); // send data to users wServer.on('message', async (data: Data) => console.log(`来自用户的信息:${data.toString()}`)); wServer.on('close', (closeCode: number) => console.log(`a client has disconnected: ${closeCode}`)); } broadcast(data: Data) { // 全体广播 this.clientMap.forEach((client: any) => { if (client.readyState === ws.OPEN) { client.send(data); } }); } } export default WsRouter.getInstance; // 使用:bootstrap.ts const server = new InversifyExpressServer(container); // 注:本项目后端使用的是 [Inversify](https://github.com/inversify) 框架 // 具体传的 private server?: hServer | hsServer 参数值,请类比改变 server.setConfig((app: any) => WsRouter('/ws/:id', app)) server.build().listen(4000);
要实现好友通信,在前后端的 send
方法中,当然要指定 from
和 to
的用户
再者,后台要记录发送的消息,也必须要有好友表的主键 friendId,表示为这两个人之间的消息
// user.ts const userSchema = new Schema( { name: { type: String, required: true, unique: true } } ); export default model('User', userSchema); // friend.ts 两个用户之间的好友关系 import { Schema, model, Types } from 'mongoose'; const FriendSchema = new Schema( { user1: { type: Types.ObjectId, ref: 'User', required: true }, // user1Id < user2Id user2: { type: Types.ObjectId, ref: 'User', required: true } } ); export default model('Friend', FriendSchema); // message.ts const MessageSchema = new Schema( { friend: { type: Types.ObjectId, ref: 'Friend', required: true }, // 关联 Friend 表 from: String, to: String, content: String, type: { type: String, default: 'text' }, } ); export default model('Message', MessageSchema);
type msgType = 'text' | 'emoji' | 'file' interface IMessage { from: string to: string content: string type: msgType }
import { IMessage, msgType } from './interface' export default class WsRequest { ws: WebSocket constructor(url: string, private userId: string) { this.ws = new WebSocket(`${url}/${this.userId}`) this.initListeners() } initListeners() { this.ws.onopen = _event => console.log('client connect') this.ws.onmessage = event => { const msg: IMessage = JSON.parse(event.data) console.log(msg.content) } this.ws.onclose = _event => console.log('client disconnect') } // friendId 指 Friend Model 的 _id async send(friendId: string, content: string, receiverId: string, type: msgType = 'text') { const message: IMessage = { from: this.userId, to: receiverId, content, type } await this.ws.send(JSON.stringify({ friend: friendId, ...message })) } close() { this.ws.close() } } // 使用 const ws = new WsRequest('your_websocket_url', 'your_user_id') // example: ws://localhost:4000/ws await wsRequest.send('Friend_model_id', '你好啊,jeffery', 'jeffery_id')
import expressWs, { Application, Options } from 'express-ws'; import ws, { Data } from 'ws'; import { Server as hServer } from 'http'; import { Server as hsServer } from 'https'; import Message, { IMessage } from 'models/message'; import Friend from 'models/friend'; class WsRouter { static instance: WsRouter; wsServer: expressWs.Instance; clientMap: Map<string, ws>; // 保存所有连接的用户 id constructor( private path: string, private app: Application, private server?: hServer | hsServer, private options?: Options ) { this.wsServer = expressWs(this.app, this.server, this.options); this.app.ws(this.path, this.wsMiddleWare); this.clientMap = new Map(); } static getInstance(path: string, app: Application, server?: hServer | hsServer, options: Options = {}) { if (!this.instance) { this.instance = new WsRouter(path, app, server, options); } return this.instance; } wsMiddleWare = (wServer: any, req: any) => { const { id } = req.params; // 解析用户 id wServer.id = id; this.clientMap.set(id, wServer); wServer.on('message', async (data: Data) => { const message: IMessage = JSON.parse(data.toString()); const { _id } = await new Message(message).save(); // 更新数据库 this.sendMsgToClientById(message); }); wServer.on('close', (closeCode: number) => console.log(`a client has disconnected, closeCode: ${closeCode}`)); }; sendMsgToClientById(message: IMessage) { const client: any = this.clientMap.get(message.to); if (client) { client!.send(JSON.stringify(message)); } } broadcast(data: Data) { this.clientMap.forEach((client: any) => { if (client.readyState === ws.OPEN) { client.send(data); } }); } } export default WsRouter.getInstance; // 使用:bootstrap.ts const server = new InversifyExpressServer(container); // 注:本项目后端使用的是 [Inversify](https://github.com/inversify) 框架 // 具体传的 private server?: hServer | hsServer 参数值,请类比改变 server.setConfig((app: any) => WsRouter('/ws/:id', app)) server.build().listen(4000);
参考:
// 服务端 wsMiddleWare = (wServer: any, req: any) => { const { id } = req.params; wServer.id = id; wServer.isAlive = true; this.clientMap.set(id, wServer); wServer.on('message', async (data: Data) => {...}); wServer.on('pong', () => (wServer.isAlive = true)); } initHeartbeat(during: number = 10000) { return setInterval(() => { this.clientMap.forEach((client: any) => { if (!client.isAlive) { this.clientMap.delete(client.id); return client.terminate(); } client.isAlive = false; client.ping(() => {...}); }); }, during); }
wss://qaapi.omyleon.com/ws
,具体使用要附上用户 id,如:wss://qaapi.omyleon.com/ws/asdf...
,参见 升级版本的 websocketwss://qaapi.omyleon.com/ws/5d1327c65793f14020a979ca
Open
,下方 Status
显示 Opened
表示连接成功friendId
,否则不能对应到相应的好友关系上{ "friend": "5d1328295793f14020a979d5", "from": "5d1327c65793f14020a979ca", "to": "5d1328065793f14020a979cf", "content": "你好呀,testuser,这是通过 simple websocket client 发送的消息", "type": "text" }
wss://qaapi.omyleon.com/ws/5d1328065793f14020a979cf { "friend": "5d1328295793f14020a979d5", "from": "5d1328065793f14020a979cf", "to": "5d1327c65793f14020a979ca", "content": "嗯嗯,收到了 jeffery,这也是通过 simple websocket client 发送的", "type": "text" }