【Web系列二十一】Vue+Ts下实现Websocket封装

目录

写在前面

封装

使用


写在前面

        有些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);
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值