PC端和APP实现WebSocket互通

pc端

 created() {
      
        this.openSoket();
       
    },
methods: {
  openSoket() {
            //console.log(typeof(WebSocket))
            if (typeof WebSocket === "undefined") {
                alert("您的浏览器不支持socket");
            } else {
                if (this.global.ws.readyState != 1) {
                    let phone = this.$store.getters.phone;
                 
                    //let path = `` WS地址;
                    // 实例化socket
                    this.ws = new WebSocket(path);
                    this.global.setWs(this.ws);
                    // 监听socket连接
                    this.ws.onopen = this.open;
                    // 监听socket错误信息
                    this.ws.onerror = this.error;
                    // 监听socket消息
                    this.ws.onmessage = this.getMessage;
                }
            }
        },
        // socket 链接提示
        open() {
            console.log("socket连接成功");
        },
        // socket 错误处理
        error(e) {
            console.log("连接错误00000000000000000000", e);

            // this.open()
        },
        getMessage(msg) { //获取消息
            if (msg != undefined) {
                //let json = JSON.parse(msg.data)
                if (msg.data.indexOf("{") !== -1) {
                    let json = JSON.parse(msg.data);
                    //console.log(json)
                    if (json.code == 9999) {
                        this.$notify({
                            title: `通知【${json.data.type}】`,
                            // 这里也可以把返回信息加入到message中显示
                            message: json.data.message,
                            type: "info",
                            offset: 50,
                            //position: 'bottom-right',
                            duration: 10 * 1000,
                            onClick: () => {
                                if (json.data.router_link !== "") {
                                    this.$router.push(
                                        "/" + json.data.router_link
                                    );
                                }
                            }
                        });
                    }
                }
            }
        },
   openPhone(row, phone) { //点击发送消息
            var params = {
                phone
            };
            console.log("params", params, row);
            console.log("this.global", this.global);
            this.global.ws.send(JSON.stringify(params));
  
        },
},

APP端

先在utlis文件夹新建文件websocket.js

// @/utils/websocket.js

//isJSON  方法
function isJSON(str) {
	if (typeof str == 'string') {
		try {
			var obj = JSON.parse(str);
			if (typeof obj == 'object' && obj) {
				return true;
			} else {
				return false;
			}

		} catch (e) {
			// console.log('error:'+str+'!!!'+e);
			return false;
		}
	}
	// console.log('It is not a string!')
}
class WebSocketClass {
	constructor(url) {
		this.lockReconnect = false; // 是否开始重连
		this.wsUrl = ""; // ws 地址
		this.globalCallback = null; // 回调方法
		this.userClose = false; // 是否主动关闭
		this.createWebSocket(url);
	}

	createWebSocket(url) {
		// #ifdef H5
		if (typeof(WebSocket) === 'undefined') {
			this.writeToScreen("您的浏览器不支持WebSocket,无法获取数据");
			return false
		}
		// #endif

		// #ifdef APP-PLUS
		if (typeof(uni.connectSocket) === 'undefined') {
			this.writeToScreen("您的浏览器不支持WebSocket,无法获取数据");
			return false
		}
		// #endif

		this.wsUrl = url;
		try {
			// 创建一个this.ws对象【发送、接收、关闭socket都由这个对象操作】

			// #ifdef H5
			this.ws = new WebSocket(this.wsUrl);
			this.initEventHandle();
			// #endif

			// #ifdef APP-PLUS
			this.ws = uni.connectSocket({
				url: this.wsUrl,
				success: (data) => {
					console.log("websocket连接成功", data);
					// this.ws.onmessage = (event) => {
					// 	if (isJSON(event.data)) {
					// 		const jsonobject = JSON.parse(event.data)

					// 		this.globalCallback(jsonobject)
					// 	} else {
					// 		this.globalCallback(event.data)
					// 	}
					// };

					this.initEventHandle();
				},
			});
			// #endif
		} catch (e) {
			this.reconnect(url);
		}
	}

	// 初始化
	initEventHandle() {
		/**
		 * 监听WebSocket连接打开成功
		 */

		// #ifdef H5
		this.ws.onopen = (event) => {
			console.log("WebSocket连接打开");
		};
		// #endif

		// #ifdef APP-PLUS
		this.ws.onOpen(res => {
			console.log('WebSocket连接打开');
		});
		// #endif


		/**
		 * 连接关闭后的回调函数
		 */

		// #ifdef H5
		this.ws.onclose = (event) => {
			if (!this.userClose) {
				this.reconnect(this.wsUrl); //重连
			}
		};
		// #endif

		// #ifdef APP-PLUS
		this.ws.onClose(() => {
			if (!this.userClose) {
				this.reconnect(this.wsUrl); //重连
			}
		});
		// #endif


		/**
		 * 报错时的回调函数
		 */

		// #ifdef H5
		this.ws.onerror = (event) => {
			if (!this.userClose) {
				this.reconnect(this.wsUrl); //重连
			}
		};
		// #endif

		// #ifdef APP-PLUS
		this.ws.onError(() => {
			if (!this.userClose) {
				this.reconnect(this.wsUrl); //重连
			}
		});
		// #endif


		/**
		 * 收到服务器数据后的回调函数
		 */

		// #ifdef H5
		this.ws.onmessage = (event) => {
			if (isJSON(event.data)) {
				const jsonobject = JSON.parse(event.data)

				this.globalCallback(jsonobject)
			} else {
				this.globalCallback(event.data)
			}
		};
		// #endif

		// #ifdef APP-PLUS
		this.ws.onMessage(event => {
			if (isJSON(event.data)) {
				const jsonobject = JSON.parse(event.data)

				this.globalCallback(jsonobject)
			} else {
				this.globalCallback(event.data)
			}
		});
		// #endif
	}

	// 关闭ws连接回调
	reconnect(url) {
		if (this.lockReconnect) return;
		this.ws.close();
		this.lockReconnect = true; // 关闭重连,没连接上会一直重连,设置延迟避免请求过多
		setTimeout(() => {
			this.createWebSocket(url);
			this.lockReconnect = false;
		}, 1000);
	}

	// 发送信息方法
	webSocketSendMsg(msg) {
		this.ws && this.ws.send({
			data: msg,
			success() {
				console.log("消息发送成功");
			},
			fail(err) {
				console.log("关闭失败", err)
			}
		});
	}

	// 获取ws返回的数据方法
	getWebSocketMsg(callback) {
		this.globalCallback = callback
	}

	// 关闭ws方法
	closeSocket() {
		if (this.ws) {
			this.userClose = true;
			this.ws.close({
				success(res) {
					console.log("关闭成功", res)
				},
				fail(err) {
					console.log("关闭失败", err)
				}
			});
		}
	}

	writeToScreen(massage) {
		console.log(massage);
	}
}
export default WebSocketClass;

在页面调用

		Socket() {
			this.ws && this.ws.closeSocket();

			//this.ws = new WS(`${process.env.VUE_APP_WS_API}/ws/xxx`)  // xxx 表示接口地址URL
			let phone = uni.getStorageSync('phone');
			let path = `地址`
			this.ws = new WS(path)
			// 发送数据
			// this.ws.webSocketSendMsg('发送信息')

			this.ws.getWebSocketMsg(data => {
				const dataJson = data;
				console.log('data', dataJson);
				if (typeof(dataJson) == "object") {
					//对消息的处理
				} else {
					console.log(dataJson);
				}
			});
		},

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值