SpringBoot WebSocket 最简单的使用方法(实现网页动态打印后台消息)

一、 背景介绍

        最近研究 Jenkins,发现它的日志能动态输出到网页,十分不错,

        本文就基于 SpringBoot 简单实现下如何把后台消息源源不断地打印到网页上

        

二、  实现步骤

2.1    在你的 SpringBoot 项目中引入 websocket 依赖

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

2.2    编写 Configuration,配置 websocket 的 endpoint

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		registry.addEndpoint("/websocket").setAllowedOrigins("*").withSockJS();
	}

}
2.3    编写一个测试 Controller(实际非必需,这里是为了向网页客户端发送数据)
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class WebSocketController {

	@Autowired
	SimpMessagingTemplate messagingTemplate;
	

	@GetMapping("/websocket/print/{msg}")
	public String print(@PathVariable  String msg) {
		messagingTemplate.convertAndSend("/topic/print",msg);
		return msg;
	}

}

2.4    编写客户端网页程序

         // 这里连接 endpoint 地址,即 /websocket

         var socket = new SockJS('http://localhost:9000/websocket');  

         // 这里要与messagingTemplate.convertAndSend()地址一致,即 /topic/print

         stompClient.subscribe('/topic/print', function(event) {...});     

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>WebSocket Logger</title>
    <script src="https://cdn.bootcss.com/jquery/2.1.4/jquery.js"></script>
    <script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
    <script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
</head>
<body>
<button onclick="openSocket()">开启日志</button><button onclick="closeSocket()">关闭日志</button>
<div id="log-container" style="height: 450px; overflow-y: scroll; background: #333; color: #aaa; padding: 10px;">
    <div></div>
</div>
</body>
<script>
    var stompClient = null;
    $(document).ready(function() {openSocket();});
    function openSocket() {
        if(stompClient==null){
            var socket = new SockJS('http://localhost:9000/websocket');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
                stompClient.subscribe('/topic/print', function(event) {
                    $("#log-container div").append(event.body).append("<br/>");
                    $("#log-container").scrollTop($("#log-container div").height() - $("#log-container").height());
                },{});
            });
        }
    }
    function closeSocket() {
        if (stompClient != null) {
            stompClient.disconnect();
            stompClient=null;
        }
    }
</script>
</body>
</html>

2.5  实验截图


### 如何在 Spring Boot 中使用 WebSocket 实现投屏功能 #### 添加 WebSocket 依赖 为了使项目能够支持 WebSocket 功能,在 `pom.xml` 文件中需添加如下依赖[^2]: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` #### 创建启动类 创建项目的入口文件,通过 `@SpringBootApplication` 注解定义为主程序类。此部分代码结构简单明了[^3]: ```java package org.spring.boot.websocket; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ScreenCastingApplication { public static void main(String[] args) { SpringApplication.run(ScreenCastingApplication.class, args); } } ``` #### 配置 WebSocket 支持 配置 WebSocket 的支持对于建立客户端和服务端之间的双向通信至关重要。这通常涉及到编写一个配置类来注册必要的组件。 ```java @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws").withSockJS(); } } ``` 上述代码片段展示了如何启用简单的消息代理以及设置应用程序的目的地前缀,并为 WebSocket 终结点提供 SockJS 备选方案[^1]。 #### 编写控制器处理业务逻辑 接下来就是实现具体的业务逻辑处理器,这里假设要开发的是屏幕共享的功能,则可以设计成接收来自前端的画面帧数据并广播给其他订阅者: ```java @Controller public class ScreenCastController { private final SimpMessagingTemplate messagingTemplate; @Autowired public ScreenCastController(SimpMessagingTemplate messagingTemplate){ this.messagingTemplate = messagingTemplate; } @MessageMapping("/sendFrame") public void sendScreenFrame(Frame frame) throws Exception{ // 将接收到的数据转发至所有已订阅的客户端 messagingTemplate.convertAndSend("/topic/screen", frame.getData()); } } // Frame 类用来封装每一帧图像的信息 class Frame { private byte[] data; // Getter 和 Setter 方法... } ``` 这段代码实现了当有新的画面帧到达时,会将其推送给所有的监听者,从而达到同步显示的效果[^4]。 #### 前端页面集成 最后一步是在 HTML 页面或者其他前端框架里加入相应的 JavaScript 或 jQuery 来发起连接请求并与后台交互。以下是简化版的例子: ```html <script type="text/javascript"> var socket = new SockJS('/ws'); stompClient = Stomp.over(socket); stompClient.connect({}, function (frame) { stompClient.subscribe('/topic/screen', function (message) { var imgData = JSON.parse(message.body).data; document.getElementById('screen').src = "data:image/png;base64," + btoa(imgData); }); }); function sendMessage() { var canvasContext = document.getElementById('canvas').getContext('2d'); var image = canvasContext.getImageData(0, 0, canvas.width, canvas.height); stompClient.send("/app/sendFrame", {}, JSON.stringify({ 'data': image.data })); } </script> <!-- 显示远程屏幕 --> <img id="screen" /> <!-- 屏幕捕捉区域 --> <canvas id="canvas"></canvas> <button onclick="sendMessage()">分享当前画布内容</button> ``` 以上即完成了基本的基于 WebSocket 技术的 Spring Boot 应用中的投屏功能构建过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值