uniapp单页面使用websocket

45 阅读1分钟

背景

本文主要记录uniapp中但页面如何使用websoket,而不是封装工具类做法。
逻辑如下:
1.页面启动的时候进行websocket链接
2.连接建立后,监听消息接受
3.在自己的业务逻辑代码将消息投放到服务器端websocket.

代码

<template>
	<view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			
		}
	},

	mounted() {
		
	},
	onLoad() {
            //建立ws链接
            this.createWebsocket();
            this.onMessage();	
	},
	methods: {
		//建立ws链接
		createWebsocket(){
			let roomIdWithUserId = this.roomId + "-" + this.userInfo.id;
			this.socketTask = uni.connectSocket({
				url: "wss://doc.zengzhang.vip:443/jeecg-activiti-gateway/ws/push/"+roomIdWithUserId,
				success: (data) => {
					console.log("--connect--");
					this.isConnected = true;
				}
			})
		},
		//断开ws链接
		closeWebsocket(){
			this.socketTask.onClose(() => {
			  this.isConnected = false;
			  console.log('WebSocket closed');
			});
		},
		//往ws发送消息
		sendMessage(data){
			if (this.isConnected) {
				  
			      this.socketTask.send({
			        data: JSON.stringify(data),
			        fail: (error) => {
			          console.error('WebSocket send error:', error);
			        },
					success:()=>{
						console.log("--send success--");
					}
			      });
			} else {
			  console.error('WebSocket is not connected');
			}
		},
		//接受ws推送的消息
		onMessage(){
			this.socketTask.onMessage((message) => {
			  console.log('Received message:', message);
			});
		},
                
                //发送消息
                testSend(){
                     //往ws投放消息
	            let sendData = {"sourceUserId": this.userInfo.id, "targetUserId": this.targetUserId, "roomId": this.roomId, "amount": value}
	           this.sendMessage(sendData);
                }
		
	}
}
</script>

<style>

</style>