当前位置: 首页 > news >正文

[苍穹外卖]-10WebSocket入门与实战

WebSocket

WebSocket是基于TCP的一种新的网络协议, 实现了浏览器与服务器的全双工通信, 即一次握手,建立持久连接,双向数据传输

区别

  1. HTTP是短连接, WebSocket是长连接
  2. HTTP单向通信, 基于请求响应模型
  3. WebSocket支持双向通信

相同

  1. HTTP和WebSocket底层都是TCP连接

应用场景: 视频弹幕/网页聊天/体育实况更新/股票基金报价实时更新

入门案例

使用webcocket.html页面作为客户端, 双击打开即用

<!DOCTYPE HTML>
<html>
<head><meta charset="UTF-8"><title>WebSocket Demo</title>
</head>
<body><input id="text" type="text" /><button onclick="send()">发送消息</button><button onclick="closeWebSocket()">关闭连接</button><div id="message"></div>
</body>
<script type="text/javascript">var websocket = null;var clientId = Math.random().toString(36).substr(2);//判断当前浏览器是否支持WebSocketif('WebSocket' in window){//连接WebSocket节点websocket = new WebSocket("ws://localhost:8080/ws/"+clientId);}else{alert('Not support websocket')}//连接发生错误的回调方法websocket.onerror = function(){setMessageInnerHTML("error");};//连接成功建立的回调方法websocket.onopen = function(){setMessageInnerHTML("连接成功");}//接收到消息的回调方法websocket.onmessage = function(event){setMessageInnerHTML(event.data);}//连接关闭的回调方法websocket.onclose = function(){setMessageInnerHTML("close");}//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。window.onbeforeunload = function(){websocket.close();}//将消息显示在网页上function setMessageInnerHTML(innerHTML){document.getElementById('message').innerHTML += innerHTML + '<br/>';}//发送消息function send(){var message = document.getElementById('text').value;websocket.send(message);}//关闭连接function closeWebSocket() {websocket.close();}
</script>
</html>
  1. 大部分浏览器都支持websocket, 通过new WebSocket就可以创建WebScoket对象

导入Maven坐标

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

创建WebSocket服务类, 用于处理客户端的通信, 类似于Controller

/** * WebSocket服务*/
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {//存放会话对象private static Map<String, Session> sessionMap = new HashMap();/*** 连接建立成功调用的方法*/@OnOpenpublic void onOpen(Session session, @PathParam("sid") String sid) {System.out.println("客户端:" + sid + "建立连接");sessionMap.put(sid, session);}/*** 收到客户端消息后调用的方法** @param message 客户端发送过来的消息*/@OnMessagepublic void onMessage(String message, @PathParam("sid") String sid) {System.out.println("收到来自客户端:" + sid + "的信息:" + message);}/*** 连接关闭调用的方法** @param sid*/@OnClosepublic void onClose(@PathParam("sid") String sid) {System.out.println("连接断开:" + sid);sessionMap.remove(sid);}/*** 群发** @param message*/public void sendToAllClient(String message) {Collection<Session> sessions = sessionMap.values();for (Session session : sessions) {try {//服务器向客户端发送消息session.getBasicRemote().sendText(message);} catch (Exception e) {e.printStackTrace();}}}}

配置类: 用于创建WebSocket的服务对象, 并交给IOC容器管理

/**
* WebSocket配置类,用于注册WebSocket的Bean*/
@Configuration // 声明配置类
public class WebSocketConfiguration {@Bean //程序运行时,创建WebSocket的服务对象,把对象交给IOC容器管理public ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}}

使用WebSocket服务, 完成浏览器/服务器的双向通信

@Component
public class WebSocketTask {@Autowiredprivate WebSocketServer webSocketServer;/*** 通过WebSocket每隔5秒向客户端发送消息*/@Scheduled(cron = "0/5 * * * * ?")public void sendMessageToClient() {webSocketServer.sendToAllClient("这是来自服务端的消息:" + DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalDateTime.now()));}
}

功能测试: 启动前端页面, 建立WebSocket连接, 服务端通过定时任务类定时给前端推送消息, 前端也可以给服务端发送消息

来单提醒

需求分析: 用户下单并且支付成功后, 需要在第一时间通知外卖商家, 通知的形式是 语音提醒 + 弹出提示框

思路分析

  1. 通过WebSocket实现管理端页面和服务端的长连接
  2. 当客户支付后, 调用WebSocket的相关API实现服务端向客户端推送消息
  3. 客户端浏览器解析服务端推送的消息, 判断是来单提醒还是客户催单, 进行相应的消息提示和语音播报
  4. 约定服务端发送给管理端页面的数据格式为JSON格式
  • type: 消息类型, 1是来单提醒, 2是客户催单
  • orderId: 订单id
  • content: 消息内容

代码开发: 基于WebSocket入门案例改造代码

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {@Autowiredprivate WebSocketServer webSocketServer;/*** 支付成功,修改订单状态** @param outTradeNo*/public void paySuccess(String outTradeNo) {// 根据订单号查询订单Orders ordersDB = orderMapper.getByNumber(outTradeNo);// 根据订单id更新订单的状态、支付方式、支付状态、结账时间Orders orders = Orders.builder().id(ordersDB.getId()).status(Orders.TO_BE_CONFIRMED).payStatus(Orders.PAID).checkoutTime(LocalDateTime.now()).build();orderMapper.update(orders);// 通过webscoket向客户端浏览器推送消息Map map = new HashMap();map.put("type", 1); // 1:来单提醒, 2:客户催单map.put("orderId", ordersDB.getId());map.put("content", "订单号:" + outTradeNo);String json = JSON.toJSONString(map);webSocketServer.sendToAllClient(json);}
}

功能测试: 客户端下单并支付成功后, 商家管理端进行语音播报并弹出提示框

交互说明: 客户端的websocket请求也是经过nginx服务器进行的代理转发

客户催单

需求分析: 用户在小程序中点击催单按钮后, 需要通知外卖商家, 通知形式是语音播报 + 弹出提示框

流程分析

  1. 通过WebSocket实现管理端页面和服务端的长连接
  2. 客户点击催单按钮后, 发起催单请求, 服务端收到请求后, 通过WebSocket, 推送消息给管理端页面
  3. 管理端页面拿到消息后, 进行相应的消息提示和语言播报
  4. 约定服务端发送给管理端页面的数据格式为JSON
  • type: 消息类型, 1: 来单提醒, 2: 客户催单
  • orderId: 订单id
  • content: 消息内容

接口设计

代码实现

@RestController("userOrderController")
@RequestMapping("/user/order")
@Slf4j
@Api(tags = "用户端订单相关接口")
public class OrderController {@Autowiredprivate OrderService orderService;/*** 客户催单*/@GetMapping("/reminder/{id}")@ApiOperation("客户催单")public Result reminder(@PathVariable Long id) {log.info("订单id:{}", id);orderService.reminder(id);return Result.success();}
}
public interface OrderService {/*** 客户催单* @param id*/void reminder(Long id);
}
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {@Autowiredprivate OrderMapper orderMapper;@Autowiredprivate WebSocketServer webSocketServer;/*** 客户催单** @param id*/public void reminder(Long id) {// 根据id查询订单Orders ordersDB = orderMapper.getById(id);// 校验订单是否存在if (ordersDB == null) {throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);}Map map = new HashMap();map.put("type", 2); // 1表示来单提醒, 2表示客户催单map.put("orderId", id);map.put("content", "订单号:" + ordersDB.getNumber());webSocketServer.sendToAllClient(JSON.toJSONString(map));}
}

功能测试: 用户点击催单按钮, 商家管理端播放语音提示, 并弹出消息框

http://www.lryc.cn/news/437504.html

相关文章:

  • 【JAVA】一篇聊透百万级数据导入导出场景问题、大数据处理策略及优化方案、EasyExcel 和 EasyPOI的玩法详解
  • 2024年华为9月4日秋招笔试真题题解
  • Next.js 14 App Router 预渲染 代码实践 静态页面渲染 SSG 服务端渲染代码 SSR
  • 阿里云人工智能ACP错题整理.txt
  • 为 WebSocket 配置 Nginx 反向代理来支持 Uvicorn 的最佳实践
  • Centos7通过Docker安装openGauss5.0.2并配置用户供Navicat连接使用
  • 生成树详细配置(STP、RSTP、MSTP)
  • 服务器环境搭建-5 Nexus搭建与使用介绍
  • 将 Parallels Desktop(PD虚拟机)安装在移动硬盘上,有影响吗?
  • PHP智能化云端培训考试系统小程序源码
  • 内幕!smardaten无代码平台全方位测评,这些细节你绝对想不到!
  • 计算机专业的真正的就业情况
  • Java对象列表属性映射工具类
  • .net core 通过Sqlsugar生成实体
  • ORCA-3D避障算法解析
  • CentOS 7停更官方yum源无法使用,更换阿里源
  • Introduction结构
  • 基于SpringBoot实现SpringMvc上传下载功能实现
  • vue 控制组件是否显示
  • 生产部门不给力?精益化生产管理咨询公司为您出谋划策
  • HTML+CSS - 网页布局之网格布局
  • 基于51单片机的16X16点阵显示屏proteus仿真
  • 【目标检测数据集】厨房常见的水果蔬菜调味料数据集4910张39类VOC+YOLO格式
  • 在Python中统计字符串中每个字符出现的次数
  • 关于 vue/cli 脚手架实现项目编译运行的源码解析
  • C++笔记---继承(上)
  • 气膜体育馆:为学校打造智能化运动空间—轻空间
  • JVM 调优篇5 jvm性能监控
  • 一. Unity实现虚拟摇杆及屏幕自适应功能
  • 【达梦数据库】mysql 和达梦 tinyint 与 bit 返回值类型差异