JS websocket 实战——好友聊天
原文地址:websocket 实战——好友聊天
还不了解 websocket 的同鞋,请先学习阮一峰老师的 WebSocket 教程
websocket
-
websocket 在实际项目中有着很广的应用,如好友聊天,异步请求,react-hot-loader 的热更新等等
-
本文前端采用原生
WebSocket
,后端采用express-ws 库
实现聊天通信 -
聊天原理很简单,如下图:
简单版本
先撸个简单版本,能够实现用户与服务器之间的通信
- 前端:WsRequest 封装类
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')
- 服务端:WsRouter 封装类,使用单例模式
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;
}