属于c2c网站的有哪几个,酒水招商网站大全,wordpress调用随机文章,苏州绿叶网站建设SpringBoot_websocket实战 前言1.websocket入门1.1 websocket最小化配置1.1.1 后端配置1.1.2 前端配置 1.2 websocket使用sockjs1.2.1 后端配置1.2.2 前端配置 1.3 websocket使用stomp协议1.3.1 后端配置1.3.2 前端配置 2.websocket进阶2.1 websocket与stomp有什么区别2.2 webs… SpringBoot_websocket实战 前言1.websocket入门1.1 websocket最小化配置1.1.1 后端配置1.1.2 前端配置 1.2 websocket使用sockjs1.2.1 后端配置1.2.2 前端配置 1.3 websocket使用stomp协议1.3.1 后端配置1.3.2 前端配置 2.websocket进阶2.1 websocket与stomp有什么区别2.2 websocket与stomp怎么选 3.websocket实战3.1 案例1:websocket 实现web-ssh3.2 案例2:websocket 实现控制台日志在线展示 前言
本文记录说明springboot websocket示例及实战你将学习到 三种websocket开发方式
/websocket 接口演示原生websocket前后端收发websocket消息/websocket-sockjs 演示使用sockjs 前后端收发websocket消息/weboscket-stomp 演示使用stomp协议使用websocket
以及通过实战演示在不同业务场景的技术选择
web-ssh 使用sockjs点对点数据传输日志项目 使用stomp广播数据
使用环境:
springboot: 2.3.2.RELEASEjdk: java11
1.websocket入门
Spring Boot WebSocket是Spring框架的一部分用于实现WebSocket通信协议的支持。WebSocket是一种双向通信协议允许服务器与客户端之间进行实时、低延迟的数据交换适用于实时聊天、实时通知、在线协作和实时数据展示等场景。Spring Boot WebSocket提供了使用WebSocket的简化和高效的方法让开发者能够轻松地实现WebSocket通信。
以下是Spring Boot WebSocket的主要特点和概念
WebSocket协议支持: Spring Boot WebSocket支持WebSocket通信协议允许双向的、实时的通信。WebSocket允许服务器主动向客户端推送数据而不需要客户端发起请求。STOMP协议支持: 除了原始WebSocketSpring Boot WebSocket还支持STOMPSimple Text Oriented Messaging Protocol协议。STOMP是一个基于文本的协议它提供了更高级的消息传递功能例如消息订阅、目标广播和认证等。消息处理器: Spring Boot WebSocket允许你定义消息处理器用于处理WebSocket消息。你可以编写处理器来处理接收到的消息并决定如何响应。消息代理: Spring Boot WebSocket支持消息代理你可以配置一个消息代理服务器如RabbitMQ或ActiveMQ用于处理WebSocket消息的分发和广播。这使得构建分布式和扩展的WebSocket应用程序更容易。消息广播: Spring Boot WebSocket允许你将消息广播到多个订阅者。这对于实现群聊、广播通知和实时数据展示等功能非常有用。安全性: Spring Boot WebSocket提供了与Spring Security集成的方式可以轻松实现WebSocket连接的安全性和认证。SockJS支持: Spring Boot WebSocket还支持SockJS这是一个JavaScript库用于处理浏览器不支持WebSocket的情况下的降级处理使得WebSocket通信在各种浏览器上都能正常工作
1.1 websocket最小化配置
步骤说明
后端通过EnableWebSocket注解开启websocket功能 定义websocket的访问端点 作用: 定义对外暴露websocket接口定义websocket的处理器 作用: 解决websocket建立后消息怎么处理 前端通过new WebSocket(“ws://localhost:9090/websocket”); 打开websocket连接并监听消息
1.1.1 后端配置
maven 依赖 dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependency!--websocket--dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-websocket/artifactId/dependencyWebSocketConfiguration 实现WebSocketConfigurer注册websocket接口及处理器
Configuration
EnableWebSocket
public class WebSocketConfiguration implements WebSocketConfigurer {Autowiredprivate EchoWebSocketHandler echoWebSocketHandler;Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {// 配置原生WebSocket处理器registry.addHandler(echoWebSocketHandler, /websocket).setAllowedOrigins(*); //允许跨域}Beanpublic EchoWebSocketHandler echoWebSocketHandler() {return new EchoWebSocketHandler();}
}EchoWebSocketHandler 实现WebSocketHandler接口, 接受消息后简单打印转发消息
public class EchoWebSocketHandler implements WebSocketHandler {private static final Logger LOGGER LoggerFactory.getLogger(EchoWebSocketHandler.class);Overridepublic void afterConnectionEstablished(WebSocketSession session) throws Exception {// 连接建立时的处理逻辑LOGGER.info([websocket-echo] session:{} ConnectionEstablished, session.getId());}Overridepublic void handleMessage(WebSocketSession session, WebSocketMessage? message) throws IOException {String payload (String) message.getPayload();LOGGER.info([websocket-echo] session:{} receive:{}, session.getId(), payload);session.sendMessage(new TextMessage(payload));}Overridepublic void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {// 处理传输错误}// 连接关闭时的处理逻辑Overridepublic void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {LOGGER.info([websocket-echo] WebSocketSession[{}] close all ssh connection, session.getId());}Overridepublic boolean supportsPartialMessages() {return false;}
}1.1.2 前端配置
TODO 说明下WebSocket 对象作用
!DOCTYPE html
html
headtitle原始WebSocket示例/title
/head
body
h1测试默认websocket 接发消息/h1
div idmessages/div
input typetext idmessage placeholder输入消息
button onclicksendMessage()发送/buttonscriptvar socket new WebSocket(ws://localhost:9090/websocket);socket.onopen function(event) {console.log(WebSocket连接已打开);};socket.onmessage function(event) {var messages document.getElementById(messages);messages.innerHTML p event.data /p;};function sendMessage() {var messageInput document.getElementById(message);var message messageInput.value;socket.send(message);messageInput.value ;}
/script
/body
/html
1.2 websocket使用sockjs
为了区别原生WebSocket处理器,以示区别,再注册一个接口/websocket-sockjs. 并且开启.withSockJS()
1.2.1 后端配置
Configuration
EnableWebSocket
Import({WebSocketStompConfiguration.class})
public class WebSocketConfiguration implements WebSocketConfigurer {Autowiredprivate EchoWebSocketHandler echoWebSocketHandler;Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {// 配置原生WebSocket处理器器registry.addHandler(echoWebSocketHandler, /websocket).setAllowedOrigins(*);//WebSocket connection to ws://localhost:9090/websocket failed: Error during WebSocket handshake: Unexpected response code: 200//.withSockJS();//.withSockJS()的作用是声明我们想要使用 SockJS 功能如果WebSocket不可用的话会使用 SockJS。(前端需要使用sockjs库)registry.addHandler(echoWebSocketHandler, /websocket-sockjs).setAllowedOrigins(*).withSockJS();}Beanpublic EchoWebSocketHandler echoWebSocketHandler() {return new EchoWebSocketHandler();}
}1.2.2 前端配置
使用sockjs需要引入前端sockjs的库: https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js
!DOCTYPE html
html
headtitle原始WebSocket示例/titlescript srchttps://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js/script
/head
body
h1测试websocket sockjs接发消息/h1
div idmessages/div
input typetext idmessage placeholder输入消息
button onclicksendMessage()发送/buttonscript// var socket new WebSocket(ws://localhost:9090/websocket);//原始写法var socket new SockJS(http://localhost:9090/websocket-sockjs);// 依赖sockjs库socket.onopen function(event) {console.log(WebSocket连接已打开);};// 监听websockt消息回调socket.onmessage function(event) {var messages document.getElementById(messages);messages.innerHTML p event.data /p;};// 定义连接关闭时的回调函数socket.onclose function () {console.log(WebSocket 连接已关闭);};// 定义连接错误时的回调函数socket.onerror function (e) {console.error(WebSocket 连接出错, e);};function sendMessage() {var messageInput document.getElementById(message);var message messageInput.value;socket.send(message);messageInput.value ;}
/script
/body
/html
1.3 websocket使用stomp协议
步骤说明
启用stomp协议, 通过EnableWebSocketMessageBroker 并注册stomp的端点 定义stomp端点 WebSocketStompConfiguration配置stomp消息路由 TestWebSocketStompController
1.3.1 后端配置
EnableWebSocketMessageBroker //在 WebSocket 上启用 STOMP
public class WebSocketStompConfiguration {BeanConditionalOnMissingBeanpublic WebSocketMessageBrokerConfigurer brokerConfigurer() {return new WebSocketMessageBrokerConfigurer() {/*** stomp 协议一种格式比较简单且被广泛支持的通信协议spring4提供了以stomp协议为基础的websocket通信实现。* spring 的websocket实现实际上是一个简易版的消息队列而且是主题-订阅模式的* param registry*/Overridepublic void registerStompEndpoints(StompEndpointRegistry registry) {// /stomp-websocket客户端需要注册这个端点进行链接// .withSockJS()的作用是声明我们想要使用 SockJS 功能如果WebSocket不可用的话会使用 SockJS。registry.addEndpoint(/websocket-stomp).setAllowedOrigins(*).withSockJS();}};}}配置消息转发路由
Controller
public class TestWebSocketStompController {private static final Logger LOGGER LoggerFactory.getLogger(TestWebSocketStompController.class);AutowiredSimpMessagingTemplate messagingTemplate;GetMapping(/websocket/print/{msg})ResponseBodypublic String print(PathVariable String msg) {messagingTemplate.convertAndSend(/topic/print, msg);return msg;}MessageMapping(/app/{destination}) // 使用 {destination} 占位符来捕获动态的目的地SendTo(/topic/print) // 服务器广播消息的目的地public String handleMessage(DestinationVariable String destination, String message) {// 处理接收到的消息LOGGER.info(Dynamic destination:[{}] Received message:{}, destination, message);// 根据动态目的地执行不同的操作if (destination1.equals(destination)) {// 处理目的地1的操作} else if (destination2.equals(destination)) {// 处理目的地2的操作} else {// 直接转发到对应订阅地址messagingTemplate.convertAndSend(/topic/ destination, copy: message);}// 可以根据需要添加更多的条件// 返回响应消息return message;}
}最后通过Import导入WebSocketStompConfiguration配置
Configuration
EnableWebSocket
Import({WebSocketStompConfiguration.class})
public class WebSocketConfiguration implements WebSocketConfigurer {Autowiredprivate EchoWebSocketHandler echoWebSocketHandler;Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {// 配置原生WebSocket处理器registry.addHandler(echoWebSocketHandler, /websocket).setAllowedOrigins(*);//WebSocket connection to ws://localhost:9090/websocket failed: Error during WebSocket handshake: Unexpected response code: 200//.withSockJS();//.withSockJS()的作用是声明我们想要使用 SockJS 功能如果WebSocket不可用的话会使用 SockJS。(前端需要使用sockjs库)registry.addHandler(echoWebSocketHandler, /websocket-sockjs).setAllowedOrigins(*).withSockJS();}Beanpublic EchoWebSocketHandler echoWebSocketHandler() {return new EchoWebSocketHandler();}
}
1.3.2 前端配置
前端依赖sockjs及stomp.min.js的库
!DOCTYPE html
html
headtitleWebSocket Example/titlescript srchttps://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.5.2/sockjs.min.js/scriptscript srchttps://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js/script/head
body
h1测试websocket stomp协议接发消息/h1
h2发送示例/h2
input typetext idsendDestination placeholderEnter send destinationinput typetext idmessage placeholderEnter your message
button onclicksendMessage()Send Message/buttonhr
h2订阅示例/h2
input typetext idlistenDestination placeholderEnter listen destination
button onclicksubscribeToDestination()Subscribe/button
div idmessages/divscriptvar stompClient null;var listenDestination null;function connect() {var socket new SockJS(/websocket-stomp); // WebSocket端点stompClient Stomp.over(socket);stompClient.connect({}, function (frame) {console.log(stomp Connected: frame);});}function sendMessage() {var sendDestination document.getElementById(sendDestination).value; // 获取发送目的地var message document.getElementById(message).value;stompClient.send(/app/ sendDestination, {}, message); // 发送消息到指定的目的地}function subscribeToDestination() {listenDestination document.getElementById(listenDestination).value; // 获取监听目的地stompClient.subscribe(/topic/ listenDestination, function (message) {displayMessage(message.body);});}function displayMessage(message) {var messagesDiv document.getElementById(messages);var p document.createElement(p);p.appendChild(document.createTextNode(message));messagesDiv.appendChild(p);}connect();
/script
/body
/html
2.websocket进阶
2.1 websocket与stomp有什么区别
WebSocket WebSocket 是一种通信协议 WebSocket 是一种在Web浏览器和服务器之间提供双向通信的协议。它允许在客户端和服务器之间创建持久性的连接以便在连接建立后实时地发送和接收消息。原始的、低级的协议 WebSocket 是一种相对较低级的协议它允许在两端之间直接发送原始的消息帧frames。这意味着你可以通过WebSocket发送任意的二进制或文本数据。需要自行处理消息格式和路由逻辑 WebSocket 本身并没有规定消息的格式或路由逻辑。在WebSocket上发送的消息可以是任意格式的数据你需要自行定义消息的结构和处理逻辑。 STOMP STOMP 是一种消息协议 STOMP 是一种基于文本的简单消息协议它定义了客户端和消息代理broker之间如何进行交互的规范。STOMP 通常运行在WebSocket之上它提供了一种在客户端和服务器之间进行实时消息通信的方式。面向文本的消息格式 STOMP 消息是文本格式的它使用类似于HTTP报文的格式来定义消息的头部和体。这种面向文本的格式使得它易于阅读和调试。定义了消息的结构和路由逻辑 STOMP 规定了消息的格式和消息目的地的语义。它定义了消息头部的各种属性例如目的地、消息类型等并提供了一种简单的消息路由机制使得消息能够被发送到特定的目的地。
2.2 websocket与stomp怎么选
如果你期望WebSocket连接之间是隔离的不需要共享数据那么使用原始的WebSocket通信是一个合适的选择。原始WebSocket通信提供了一种简单而轻量级的方式每个连接都是独立的不会共享会话数据。
STOMP协议通常用于需要高级消息传递功能和消息广播的场景其中不同连接之间需要共享数据。如果你不需要这种复杂性原始WebSocket通信足以满足需求而且更容易理解和维护。
因此你可以根据你的应用程序需求选择使用原始WebSocket通信或STOMP协议。如果只需要简单的双向通信并希望保持连接之间的隔离原始WebSocket通信通常是一个更直接的选择
3.websocket实战
3.1 案例1:websocket 实现web-ssh
springboot实现webssh功能, 使用xterm(前端) websocket jsch技术实现。后端主要实现websocket消息与jsch命令收发即可。还在开发中, 篇幅关系实现过程就不写了。有需要点赞或留言开源后再通知。 3.2 案例2:websocket 实现控制台日志在线展示
web在线查看springboot后台日志源码参考:https://github.com/easycode8/easy-log 的easy-log-web模块, 代码量很少。