uniapp中websocket的使用方法

今天研究一下在uniapp中websocket的使用方法:

基本使用:
uni.closeSocket();
关闭现有的websocket服务

uni.connectSocket({
url:“”
});
创建一个新的websocket连接,其中的url是必须传的参数。

uni.onSocketOpen(function (res) {
})
连接成功后的回调函数

uni.onSocketMessage(function (res) {
console.log(‘收到服务器内容:’ + res.data);
})
监听WebSocket接受到服务器的消息事件。

以上为基本用法。

在项目中的实际应用:

onShow(){
	//首页显示
	uni.getStorage({
			key: 'UserListYH',
				//获取本地存储中的用户信息
			success: (res)=>{
				//获取成功的回调函数
				this.isLogin = true
				//登陆状态标记为true
				uni.request({
					//根据得到的用户id发送ajax请求,获取用户的消息
					url: this.$api+'/IM/isHaveMessage/' + res.data.id,
					success: (resquert) => {
					//请求成功的回调函数
						console.log(resquert,'resquert')
						if(resquert.data.data){
							this.showxxList = true
							this.$store.state.dataList = true
						}else{
							this.showxxList = false
						}
					}
				});
				//到这里为止还没有用到websocket
				if(!this.socketOpen){
					//判断是否打开了socket服务
					this.uniOpenSocket(res.data.id);
					//如果没有打开服务,就调用开启socket的函数,把用户的id作为参数传进去
				}
			},
			fail:(e)=>{
				//如果存储中获取不到用户信息,登陆状态变成未登录
				this.isLogin = false;
			}
		});
}
uniOpenSocket(id){
			uni.closeSocket();
			//关闭现在的socket
			let _this = this;
			uni.connectSocket({
				url:"ws://uep5ems.nat.ipyingshe.com/imServer/"+id
				//可以判断这个url地址是后端地址,ws:是websocket协议,而且可以发现用户id多次出现
			});
			uni.onSocketOpen(function (res) {
				//连接成功后的回调
				_this.socketOpen = true
				//socket标记为开启状态
				_this.onSocketMessage();
				// 调用了名为onSocketMessage的函数
				uni.getStorage({
				    key: 'userMsgList',
				    success: function (res) {
						console.log('初始化聊天列表成功!');
						console.log(res);
						if(res.data.length == 0){
							_this.chatList=[{
								userId:5,
								userName:"在线客服",
								imageUrl:"/static/img/im/face/face_2.jpg",
								time:"",
								nowMsg:"欢迎提问,很高兴为您服务!",
								numberOfMsg:0,
							}]
						}else{
							console.log(res.data,'*********');
							_this.chatList = res.data
						}
				    },
					fail() {
						_this.chatList=[{
							userId:5,
							userName:"在线客服",
							imageUrl:"/static/img/im/face/face_2.jpg",
							time:"",
							nowMsg:"欢迎提问,很高兴为您服务!",
							numberOfMsg:0,
						}]
					}
				});
			});
//socket连接成功后,调用的回调函数
onSocketMessage(){
			let _this = this;
			let timer = setInterval(()=>{
				//开启一个定时器
				uni.onSocketMessage((msg)=>{
					//接收到服务器的消息
					clearInterval(timer)
					//清空定时器
					if(!msg.data){
						//如果没有消息直接退出当前执行函数
						return
					}
					const msgUser = JSON.parse(msg.data);
					//如果有消息,把消息字符串解析成json对象
					console.log(msgUser)
					let haschatList = false;
					uni.getStorage({
					    key: 'userMsgList',
					    //从本地存储中获取用户的消息列表
					    success: function (res) {
					    	//获取成功的回调
							_this.chatList = res.data
							//获取的消息列表存入data
							console.log(_this.chatList,'chatList----------');
					    },
						fail: () => {
							console.log('getstorage失败了');
						}
					});



					_this.chatList.forEach((item,index) => {
						// 判断函数----判断当前用户是否在列表
						if(item.userId == msgUser.fromUserId){
							haschatList = true;
							_this.chatList[index].time = msgUser.sendTime
							_this.chatList[index].numberOfMsg++
							_this.chatList[index].nowMsg = msgUser.contentText
							_this.chatList[index].UserAndMeMsgList.push({
								userMsgID: msgUser.fromUserId,
								time: msgUser.sendTime,
								msg: msgUser.contentText
							})
							uni.setStorage({
							    key: 'userMsgList',
							    data: _this.chatList,
								success: function () {
									uni.$emit('haveNewMsg',
									{
										userMsgID: msgUser.fromUserId,
										time: msgUser.sendTime,
										msg: msgUser.contentText
									})
								}
							});
						}
					})
					if(haschatList && _this.chatList.length != 1){
						return
					}
					uni.request({
						url: _this.$api + '/userInfo/getUserInfo?userId='+msgUser.fromUserId,
						method:'POST',
						success: (res) => {
							console.log(res.data.data)
							let msgLsit = {
								userId: msgUser.fromUserId,
								imageUrl: res.data.data.avatar,
								userName: res.data.data.name,
								time: msgUser.sendTime,
								nowMsg: msgUser.contentText,
								numberOfMsg: 1,
								UserAndMeMsgList:[]
							}
							msgLsit.UserAndMeMsgList.push({
								userMsgID: msgUser.fromUserId,
								time: msgUser.sendTime,
								msg: msgUser.contentText
							})
							_this.chatList.unshift(msgLsit)
							uni.setStorage({
							    key: 'userMsgList',
							    data: _this.chatList,
								success: function () {
									uni.$emit('haveNewMsg')
								}
							});
						},
					});
				})
			},60)
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
uniapp使用WebSocket可以通过以下步骤进行操作: 1. 首先,在你的项目创建一个websocket.js文件,可以放在utils目录下。在这个文件,你可以定义一个WebSocket类,用于处理WebSocket的连接和消息传输。 2. 在websocket.js文件,你可以使用uni.connectSocket接口来创建一个WebSocket连接。这个接口返回一个SocketTask对象,你可以使用这个对象来发送和接收消息。 3. 在你的页面,引入websocket.js文件,并创建一个WebSocket实例。你可以将这个实例挂载到全局的Vue.prototype.$socket上,以便在其他页面也可以使用。 4. 在页面,你可以使用this.$socket.send方法来发送消息,传入一个字符串参数作为要发送的内容。 5. 同样地,你可以使用this.$socket.getMessage方法来接收消息。这个方法接受一个回调函数作为参数,当接收到消息时,回调函数会被调用,并传入接收到的消息作为参数。 需要注意的是,在测试环境WebSocket的URL可以写成ws://xxx:3100/connect/websocket,而在发布体验版或正式版,URL应该写成wss://xxx:3100/connect/websocket,以确保安全连接。 总结起来,使用uniappWebSocket可以通过创建WebSocket类、调用uni.connectSocket接口来创建连接、发送和接收消息来实现。具体的代码示例可以参考引用\[1\]的示例代码。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* [uni-app使用websocket(封装、心跳检测、实时信息)](https://blog.csdn.net/m0_60289222/article/details/130315532)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [uniapp APP 端 WebSocket 使用,实现一个简单 WebSocket 工具类](https://blog.csdn.net/sinat_35272898/article/details/122511603)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值