背景

做的一个校园版的美团外卖项目,这里分享一下订单提醒功能,使用uniapp+WebSocket实现。

开始

一、导入pom

<!--socket--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>

二、后端实现

package com.ningxun.restcard.controller;import com.alibaba.fastjson.JSONObject;
import com.ningxun.restcard.auth.UserAuthenticationProvider;
import com.ningxun.restcard.entity.StudentUserEntity;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;//这个是客户端访问的接口
@ServerEndpoint("/imserver/app/{token}")
@Component
public class WebSocketServerApp {//日志static Logger log = LoggerFactory.getLogger(WebSocketServerApp.class);/*** 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/private static int onlineCount = 0;/*** concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*///新建一个ConcurrentHashMap webSocketMap 用于接收当前userId的WebSocket,方便IM之间对userId进行推送消息。private static ConcurrentHashMap<String, WebSocketServerApp> webSocketMap = new ConcurrentHashMap<>();/*** 与某个客户端的连接会话,需要通过它来给客户端发送数据*/private Session session;//    /**接收userId*/private String userId = "";public static Session temp;public static boolean flag = false;/*** 连接建立成功调用的方法*/@OnOpenpublic void onOpen(Session session, @PathParam("token") String token) {//解析JWTClaims claims = Jwts.parser().setSigningKey(UserAuthenticationProvider.STORE_PWD).parseClaimsJws(token).getBody();StudentUserEntity user = JSONObject.parseObject(JSONObject.toJSON(claims.get("user")).toString(), StudentUserEntity.class);if (claims != null) {claims.setId(user.getId() + "");//获取到session和userIdthis.session = session;this.userId = claims.getId();this.temp = session;flag = true;//如果userId存在,则移除,再添加一个相同的userId和新的Session(防止session过期)if (webSocketMap.containsKey(userId)) {webSocketMap.remove(userId);webSocketMap.put(userId, this);} else {webSocketMap.put(userId, this);//在线数加1addOnlineCount();}log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());try {sendMessage(this.userId + "连接成功");} catch (IOException e) {log.error("用户:" + userId + ",网络异常!!!!!!");}} else {log.error("用户:" + userId + ",没有权限!!!!!!");}}/*** 连接关闭调用的方法*/@OnClosepublic void onClose() {//如果存在userId则移除,然后人数-1if (webSocketMap.containsKey(userId)) {webSocketMap.remove(userId);//从set中删除subOnlineCount();flag = false;}log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());}/*** @param session* @param error*/@OnErrorpublic void onError(Session session, Throwable error) {log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());error.printStackTrace();}// 收到客户端消息后调用的方法@OnMessagepublic void onMessage(String message, Session session) {log.info(message);}/*** 实现服务器主动推送*/public void sendMessage(String message) throws IOException {this.session.getBasicRemote().sendText(message);}/*** 发送自定义消息*/public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {log.info("发送消息到:" + userId + ",报文:" + message);if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {webSocketMap.get(userId).sendMessage(message);} else {log.error("用户" + userId + ",不在线!");}}public static synchronized int getOnlineCount() {return onlineCount;}public static synchronized void addOnlineCount() {WebSocketServerApp.onlineCount++;}public static synchronized void subOnlineCount() {WebSocketServerApp.onlineCount--;}public void setSession(Session session) {this.session = session;}
}

三、前端实现

export default {components: {uniLoadMore},data() {return {timer: '', //心跳定时器heartbeatFailNum: 0, //心跳失败次数    socketTask: null,// 确保websocket是打开状态is_open_socket: false};},onLoad() {this.connectSocketInit();},// 关闭websocket【必须在实例销毁之前关闭,否则会是underfined错误】beforeDestroy() {this.closeSocket();clearInterval(this.timer);},methods: {// 进入这个页面的时候创建websocket连接【整个页面随时使用】connectSocketInit() {// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】this.socketTask = uni.connectSocket({// 【非常重要】必须确保你的服务器是成功的url: this.$student_api_url + "/imserver/app/" + uni.getStorageSync("token"),success(data) {console.log("websocket连接成功");},});// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】//连接成功时回调this.socketTask.onOpen((res) => {console.log("WebSocket连接正常打开中...!");this.is_open_socket = true;//收到信息的回调this.socketTask.onMessage((res) => {console.log("收到服务器内容:" + res.data);var state = res.data;//连接成功消息不处理,业务消息加提示铃声if (state.indexOf("连") != -1) {} else {const innerAudioContext = uni.createInnerAudioContext();innerAudioContext.autoplay = true;innerAudioContext.src ='http://ppt.1ppt.com/uploads/soft/2008/2-200R5152453.mp3';innerAudioContext.onPlay(() => {console.log('开始播放');});innerAudioContext.onError((res) => {console.log(res.errMsg);console.log(res.errCode);});}//未接单状态且页面选中待接单页。。。。。//这里业务代码,没看的必要});})// 这里仅是事件监听【如果socket关闭了会执行】this.socketTask.onClose(() => {console.log("已经被关闭了")})//开启心跳机制this.heartCheck();},// 关闭websocket【离开这个页面的时候执行关闭】closeSocket() {this.socketTask.close({success(res) {this.is_open_socket = false;console.log("关闭成功", res)},fail(err) {console.log("关闭失败", err)}})},//心跳检测30秒一次heartCheck() {clearInterval(this.timer);var that=this;this.timer = setInterval(function() {//发送信息uni.sendSocketMessage({data: 'ping',success: res => {console.log("心跳发送成功");that.heartbeatFailNum = 0;},fail: err => {// 未连接关闭在打开console.log("心跳发送失败");that.heartbeatFailNum + 1;if (that.heartbeatFailNum <= 10) {that.closeSocket();that.connectSocketInit();} else {console.log("连续十次心跳检测失败,不再发起重连请求")}}});}, 1000 * 30);},};

四、最后

参考了一个博主的博文,回过头就找不到了,要不可以分享个链接。最后上测试服的时候遇到了WebSocket连接不上的问题。这属于微信小程序的问题,需要对IP做备案。

微信小程序:uniapp+WebSocket实现订单提醒相关推荐

  1. java与微信小程序通讯_java与微信小程序实现websocket长连接

    本文实例为大家分享了java与微信小程序实现websocket长连接的具体代码,供大家参考,具体内容如下 背景: 需要在小程序实现地图固定坐标下实时查看消息 java环境 :tomcat7 jdk1. ...

  2. 微信小程序之WebSocket

     (扫码带走看 ^ ^) 本文版权归 OSChina jsongo0 所有,此处为技术收藏,如有再转请自觉标明原文出处,这是大家对原创作者劳动成果的自觉尊重! 原文地址:https://my.osch ...

  3. 微信小程序uni-app

    文章目录 一.微信小程序uni-app 二.下载微信开发者工具 三.小程序开发 一.微信小程序uni-app 小程序是一种不需要下载.安装即可使用的应用,它实现了应用触手可及的梦想,用户扫一扫或者搜一 ...

  4. 微信是与服务器长连接,java与微信小程序实现websocket长连接.pdf

    java与与微微信信小小程程序序实实现现websocket长长连连接接 本文实例为大家分享了j ava与微信小程序实现websocket长连接的具体代码,供大家参考,具体内容 下 背背景景:: 需要在 ...

  5. 【微信小程序控制硬件⑧ 】微信小程序以 websocket 连接阿里云IOT物联网平台mqtt服务器,封装起来使用就是这么简单!(附带Demo)

    [微信小程序控制硬件第1篇 ] 全网首发,借助 emq 消息服务器带你如何搭建微信小程序的mqtt服务器,轻松控制智能硬件! [微信小程序控制硬件第2篇 ] 开始微信小程序之旅,导入小程序Mqtt客户 ...

  6. 微信小程序uni-app前端应用框架和HBuilderX工具使用及Git管理项目

    微信小程序uni-app前端应用框架和HBuilderX工具使用及Git管理项目 官方地址:https://uniapp.dcloud.io/ 1.起步 1.1.简介 uni-app 是一个使用 Vu ...

  7. 微信小程序/uni-app 蓝牙打印开发教程和常见问题总结【文末附源码】

    微信小程序/uni-app 蓝牙打印开发教程和常见问题总结[文末附源码] 文章目录 微信小程序/uni-app 蓝牙打印开发教程和常见问题总结[文末附源码] 1️⃣ 写在前面 2️⃣ 蓝牙连接流程 3 ...

  8. 微信小程序的 websocket 以及 微信开发者工具测试 ws 协议没有数据的 离奇解决方案 记录

    微信小程序的 websocket 在本地web能够使用ws协议去链接websocket,但是小程序不能使用. 一.WSS 协议与 WS 协议 二.业务场景记录 : 使用 ws 协议的 websocek ...

  9. 微信小程序使用websocket

    微信小程序使用websocket 连接websocket let url = `******`//websocket地址 wx.connectSocket({url: url,success() {c ...

  10. 开发微信小程序(uniapp)

    @2021SC@SDUSC WebStorm开发微信小程序(uniapp) 创建项目 采用cli方式创建的项目 vue create -p dcloudio/uni-preset-vue my-pro ...

最新文章

  1. 【spring 5】AOP:spring中对于AOP的的实现
  2. java程序员的第二编程语言应该选什么?
  3. word如何设置上标形式_如何在word中设置特殊页码
  4. 透析 | 卷积神经网络CNN究竟是怎样一步一步工作的?
  5. python中concat的用法_python pandas concat用法及代码示例
  6. 【mmdetection】mmdetection数据处理pipline结果可视化
  7. HTML与CSS各种代码与用法,几种关于html和css的使用方法
  8. 算术表达式:前缀表达式、中缀表达式、后缀表达式相互转换(手算法)
  9. ad13批量安装元件库_常用的Altium Designer AD09 AD14 AD18元件库 原理图库(543个)+PCB封装库(509个)...
  10. Linux那些事儿之我是U盘(28)第一次亲密接触(四)
  11. 西湖论剑2020-BrokenSystems
  12. bootstrap 初学 1
  13. 调用html事件,HTML 事件
  14. Excel表格文本/数字/科学计数法的格式转换问题
  15. Final Cut Pro 学习笔记
  16. android画布裁剪圆角,Android 视图圆角化处理方案
  17. 高可用的接口安全规范
  18. [分享]程序员技术练级攻略
  19. 纸牌博弈问题 动态规划
  20. 树莓派4b和3b+功耗_ARM v8(树莓派4)搭建服务器和性能测试实战

热门文章

  1. php 二维数组去重合并,PHP 二维数组去重合并
  2. html5 setdata函数,微信小程序this.setData is not a function错误解决
  3. golang pprof工具
  4. 关于以w3school为首的那些网址,很迷
  5. RFID电子标签的七大特点
  6. 动效之文字滚动5个代码
  7. CNAS/CMA?什么是认证认可?
  8. 4K HDR技术探讨一HDR是什么
  9. 二元logistic模型案例_二元选择(logistic的s )模型.ppt
  10. ComWar3b 魔兽显血改键(版本更新为1.01a) Delphi7