uni-app uniapp的websocket是否可以实现浏览器的websocket规范,这样可以使用许多实用的websocket库而非自实现

rjee0c15  于 3个月前  发布在  uni-app
关注(0)|答案(2)|浏览(42)

新功能描述
uniapp的websocket是否可以实现浏览器的websocket规范

参考链接:

现状及问题

一些常见的websocket库时无法使用,如graphql-ws

尝试方案

尝试了做适配器,但没成功,会显示子协议不支持

补充信息

https://juejin.cn/post/7225074892357337148#comment

jgzswidk

jgzswidk1#

可以封装(难易度:★★★☆☆),但我希望社区的开发者们能动起来,相关可以参考这个对localstorage的封装: https://github.com/zhetengbiji/mp-storage

gudnpqoy

gudnpqoy2#

可以封装(难度:★★★☆☆),但我希望社区的开发者能动起来,相关可以参考这个对localstorage的封装: https://github.com/zhetengbiji/mp-storage

如下是我实现的一部分,但能力有限,好像在使用其他库时还有点问题,,正处于调试中:

export class uniWebSocket {
	private socketTask: null | UniApp.SocketTask;
	public readyState: number = 0;
	constructor(url: string, protocol: string) {
		const socketTask = uni.connectSocket({
			url,
			protocols: [protocol],
			complete: () => {},
		});
		this.socketTask = socketTask;
		if (!this.socketTask) {
			throw new Error("server didn't accept Websocket");
		}
	}
	static CONNECTING = 0;
	static OPEN = 1;
	static CLOSING = 2;
	static CLOSED = 3;

	addEventListener(type: "open" | "error" | "close" | "message", callback: (event: any) => void) {
		if (this.socketTask === null) throw new Error("uniWebSocket not init");

		if (type === "open") {
			this.socketTask.onOpen((e: any) => {
				console.log("websocket连接打开");
				this.readyState = 1;
				callback(e);
			});
		} else if (type === "error") {
			this.socketTask.onError((e: any) => {
				console.log("websocket连接错误");
				this.readyState = 1;
				callback(e);
			});
		} else if (type === "close") {
			this.socketTask.onClose((e: any) => {
				console.log("websocket连接关闭");
				this.readyState = 2;
				callback(e);
				this.readyState = 3;
			});
		} else if (type === "message") {
			this.socketTask.onMessage((e: any) => {
				console.log("websocket消息接收: ", e);
				this.readyState = 1;
				callback(e);
			});
		}
	}

	public send(msg: string) {
		if (this.socketTask === null) throw new Error("uniWebSocket not init");
		this.socketTask.send({ data: msg });
	}
	public close(code: number, reason: string) {
		if (this.socketTask === null) throw new Error("uniWebSocket not init");
		this.socketTask.close({ code, reason });
	}
}

相关问题