目录
写在前面
有些web项目需要大量的前后端websocket通信,如果在每个使用的地方都建立一个websocket连接就会使得代码变得冗长,且不方便维护。这时封装websocket就显得很有必要,但是由于websocket不只是维护一些简单的变量就可以实现的,还涉及到一些函数作为参数,相对比较复杂,因此本篇文章记录一个封装websocket和使用的方法供大家参考。
封装
废话不多说,直接上代码。
class WS {
ip: string;
port: string;
url: string;
ws: WebSocket;
closure: Function;
send: Function;
constructor(
ip: string,
port: string,
url: string,
onopen: ((ws: WS, ev: Event) => any) | null = null,
onmessage: ((ws: WS, ev: MessageEvent) => any) | null = null,
onerror: ((ws: WS, ev: Event) => any) | null = null,
onclose: ((ws: WS, ev: CloseEvent) => any) | null = null
) {
this.ip = ip;
this.port = port;
this.url = url;
this.ws = mew WebSocket("ws://" + ip + ":" + port + url);
this.closure = (): void => {
this.ws.close();
};
this.send = (msg: any): void => {
this.ws.send(msg);
};
const onopen_ = (ev: Event): any => {
if(onopen !== null) {
onopen(this, ev);
}
console.log(`websocket$(this.ip):${this.port}${this.url}连接开启!`);
};
const onmessage_ = (ev: MessageEvent): any => {
if(onmessage !== null) {
onmessage(this, ev);
}
console.log(`websocket$(this.ip):${this.port}${this.url}收到信息:${ev}!`);
};
const onerror_ = (ev: Event): any => {
if(onerror !== null) {
onerror(this, ev);
}
console.log(`websocket$(this.ip):${this.port}${this.url}连接error:${ev}!`);
};
const onclose_ = (ev: CloseEvent): any => {
if(onclose !== null) {
onclose(this, ev);
}
console.log(`websocket$(this.ip):${this.port}${this.url}连接关闭!`);
};
this.ws.onopen = onopen_;
this.ws.onmessage = onmessage_;
this.ws.onerror = onerror_;
this.ws.onclose = onclose_;
}
}
export { WS };
这里要注意的时用‘=>’方式写函数,可以保证this不会改变。
使用
使用其实很简单,直接创建对象并传参即可,四个函数参数都是可选的。
import { WS } from '@/utils/ws.ts'
let ws = new WS('192.168.1.100', '8080', '/ws/getData', onopen, onmessage);
function onopen(ws: WS, ev: Event): any {
let msg = { id: 100 };
ws.send(JSON.stringify(msg));
}
function onmessage(ws: WS, ev: MessageEvent): any {
ws.closure();
console.log(ev);
}