在写
websocket
的时候,很多页面都需要使用,每个页面重复写,太麻烦,于是先浅浅的封装一下。
起一个websocket后台
- 为了方便页面调试,我先简单的建一个
nodejs
的websocket
后台服务,定时给发送消息。
// 引入nodejs-websocket const ws = require("nodejs-websocket"); // 定义监听的host地址跟port端口 const host = "127.0.0.1", port = 8888; // 创建ws服务 ws.createServer((conn) => { // 定义测试数据 const data = ["消息1", "消息2", "消息3"]; setInterval(() => { // 随机推送message里的内容 conn.sendText(data[(Math.random() * 2).toFixed(0)]); console.log("推送成功!"); }, 2000); }).listen(port, host, () => { console.log(`服务打开成功:${host}:${port}`); });
运行文件,会打印地址127.0.0.1:8888
,在使用的时候就使用该地址。
使用函数封装
interface ScoketOptions { url: string token?: string[] message?: any } /** * 函数的形式封装 * @param option {url: string , token?: string[] , message?: any} * @returns */ export const useScoket = ( option: ScoketOptions = { url: "", token: [], message: "" } ) => { let ws: WebSocket // 创建链接 const connect = () => { close() ws = new WebSocket(option.url, option.token) error() open() } // 打开链接 const open = () => { ws.onopen = () => { console.log("WebSocket open") ws.send("hello") } } // 接收消息 const onMessage = (callback: (...data: any[]) => any): void => { if (ws) { ws.onmessage = (e: any) => { console.log("接收消息", e) try { const res = JSON.parse(e.data) callback(res) } catch (err) { callback(e) } } } } // 关闭通信 const close = () => { if (ws) { ws.close() ws.onclose = (e: any) => { console.log(e) } } } // 发送消息 const send = () => { if (ws) { ws.send(option.message) } } // 错误重连 const error = () => { if (ws) { ws.onerror = (err) => { connect() } } } connect() return { onMessage, close, send } }
使用class封装
interface ScoketOptions { url: string token?: string[] message?: any } /** * class的形式封装 * @param option {url: string , token?: string[] , message?: any} */ export class useScoket { private url: string = "" private token?: string[] = [] private message?: string = "" private ws: WebSocket | null = null constructor(option: ScoketOptions) { this.url = option.url this.token = option.token this.message = option.message this.connect() } // 创建链接 connect = () => { this.close() this.ws = new WebSocket(this.url, this.token) this.error() this.open() } // 打开链接 open = () => { this.ws!.onopen = () => { console.log("WebSocket open") this.ws!.send("hello") } } // 接收消息 onMessage = (callback: (...data: any[]) => any): void => { if (this.ws) { this.ws.onmessage = (e: any) => { console.log("接收消息", e) try { const res = JSON.parse(e.data) callback(res) } catch (err) { callback(e) } } } } // 关闭通信 close = () => { if (this.ws) { this.ws.close() this.ws.onclose = (e: any) => { console.log(e) } } } // 发送消息 send = () => { if (this.ws) { this.ws.send(this.message!) } } // 错误重连 error = () => { if (this.ws) { this.ws.onerror = (err) => { this.connect() } } } }
使用
函数方式
const ws = useScoket({ url: "ws://127.0.0.1:8888" }) ws.onMessage((data: any) => { console.log("message", data) })
class方式
const ws = new useScoket({ url: "ws://127.0.0.1:8888" }) ws.onMessage((data: any) => { console.log("message", data) })