记录uniapp微信小程序上使用websocket实现聊天

本文介绍了在uniapp微信小程序中如何使用WebSocket实现聊天功能。在app.vue中,WebSocket在onLaunch中启动,但需在用户登录后进行。在onShow中监听用户登录,启动WebSocket。在index.vue聊天列表页面,监听newSocketMsg更新列表数据。chat.vue聊天页面则负责接收和发送消息,历史消息通过接口获取并存储,发送消息时先调用接口再通过WebSocket发送。
摘要由CSDN通过智能技术生成

app.vue页面

里面的message.type 是和后台商量的类型。

1. websocket是进小程序就要启动的,在onLaunch里面但是肯定是在用户登录之后才启动,不然要报错。

2. 在onShow里面监听了一个emit,在用户登录之后,要启动websocket。

<script>
	export default {
		data() {
			return {
				wsUrl: "wss://***.****.com/wss/",
				lockReconnect: false,  // 避免重复连接
				formId: null,
				toId: null,
				heartCheck : {
					timeout: 30000,
					timeoutObj: null,
					serverTimeoutObj: null,
					reset: () => {
						clearTimeout(this.heartCheck.timeoutObj);
						clearTimeout(this.heartCheck.serverTimeoutObj);
						return this.heartCheck;
					},
					start: () => {
						this.heartCheck.timeoutObj = setTimeout(() => {
							//这里发送一个心跳,后端收到后,返回一个心跳消息,
							//onmessage拿到返回的心跳就说明连接正常
							let heart = {
								type: "heart",
								fromId: this.formId
							}
							this.$store.state.wss.send({
								data: JSON.stringify(heart),
								success: () => {
									// console.log("发送一次心跳包", heart);
								}
							})
							this.heartCheck.serverTimeoutObj = setTimeout(() => {
								this.$store.state.wss.onOpen(_ => {
									this.$store.state.wss.close()
								})
							}, 70000) // 这里因为后台是60秒没反应就关闭,所以前端设置的是70秒关闭
							
						}, this.heartCheck.timeout)
					}
				}
			}
		},
		onLaunch: function() {
			console.log('App Launch')
			if(uni.getStorageSync('userInfo')) {
				this.createSocket(this.wsUrl)
				this.getMessageNum()
			}
		},
		onShow: function() {
			this.formId = uni.getStorageSync('userInfo').id
			uni.$on('openSocket', (data) => {
				this.formId = data.user_id
				this.createSocket(this.wsUrl)
				this.getMessageNum()
			})
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
			this.$store.state.wss.onOpen(_ => {
				this.$store.state.wss.close()
			})
		},
		onUnhandledRejection(event) {
			c
  • 3
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
uniapp微信小程序中连接websocket,你需要使用uni-app提供的uni-ws组件。具体操作步骤如下: 1. 在你的uni-app项目中,创建一个新的页面,并在该页面中引入uni-ws组件 2. 在页面的data中定义websocket连接对象,并设置websocket服务器的地址 3. 在页面的onLoad生命周期函数中,使用uni.connectSocket()方法连接websocket服务器,并将连接对象赋值给data中的websocket对象 4. 监听websocket连接事件,并在连接成功后发送消息给服务器 5. 监听websocket消息事件,并在接收到消息后更新页面数据或执行相应操作 以下是一个简单的示例代码: ``` <template> <view> <text>{{message}}</text> </view> </template> <script> export default { data() { return { websocket: null, message: "" } }, onLoad() { this.connectWebSocket(); }, methods: { connectWebSocket() { const url = "ws://localhost:8080"; // websocket服务器地址 this.websocket = uni.connectSocket({ url, success: () => { console.log("websocket连接成功"); } }); this.websocket.onOpen(() => { console.log("websocket连接已打开"); const msg = "Hello, WebSocket!"; this.websocket.send({ data: msg }); }); this.websocket.onMessage((res) => { console.log("websocket收到消息:", res); this.message = res.data; }); this.websocket.onError((err) => { console.error("websocket连接出现错误:", err); }); this.websocket.onClose(() => { console.log("websocket连接已关闭"); }); } } } </script> ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值