相关文章推荐
严肃的烈酒  ·  SHA-1_百度百科·  2 月前    · 
魁梧的小蝌蚪  ·  中南大学 李津臣·  4 月前    · 
小眼睛的香菜  ·  VCPKG ...·  1 年前    · 
Spring Boot(七)Spring Boot的WebSocket

Spring Boot(七)Spring Boot的WebSocket

你好,专注于:Spring Boot ,微服务 和 前端APP开发,闲暇之余一起聊聊职场规划,个人成长,还能带你一起探索 副业赚钱渠道,在提升技术的同时我们一起交流 敏捷流程 提高工作效率,从技术到管理一步步提升自我!

标签:一个执着的职场程序员!

本文是Spring Boot系列的第七篇,了解前面的文章有助于更好的理解本文:

1.Spring Boot(一)初识Spring Boot框架
2.Spring Boot(二)Spring Boot基本配置
3.Spring Boot(三)Spring Boot自动配置的原理
4.Spring Boot(四)Spring Boot web项目开发
5.Spring Boot(五)Spring Boot web开发项目(2)配置
6.Spring Boot(六)Spring Boot web开发 SSL配置

前言

(一). 什么是WebSocket

(二). WebSocket实战

上篇文章为大家讲述了 Spring Boot的SSL配置,http转https的原理;本篇文章接着上篇内容继续为大家介绍SpringBoot中 WebSocket的功能。

(一). 什么是WebSocket

WebSocket为浏览器和服务器之间提供了双工异步通信功能,即可以利用浏览器给服务器发送消息,服务器也可以向浏览器发送消息。

WebSocket是一个通过socket来实现双工异步通信能力的,但是直接使用WebSocket协议开发程序比较繁琐,我们使用他们的自协议 STOMP,它是一个更高级的协议,STOMP协议使用一个基于帧的格式来定义消息,于http的request和response类似。

这边文字对于Websocket的原理和使用场景说的很详细,小伙伴可以 看一下
zhihu.com/question/2021

(二). WebSocket实战

1.新建项目

注意看在创建的时候 我们添加了两个依赖: Thymeleaf和WebSocket依赖

2. 配置websocket
需要在配置类上使用@EnableWebSocketMessageBroker 注解开启 Websocket的支持,并实现 WebSocketMessageBrokerConfigurer类

代码如下:

package org.cxzc.myyoung.springbootwebsocket;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        stompEndpointRegistry.addEndpoint("/endpoint").withSockJS();
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
}

代码解释:

1.@EnableWebSocketMessageBroker注解 表示开启使用STOMP协议来传输基于代理的消息,Broker就是代理。

2.registerStompEndpoints方法表示注册STOMP协议的节点,并映射指定的URL。

3.stompEndpointRegistry.addEndpoint("/endpoint").withSockJS();用来注册STOMP协议节点,并指定使用SockJS协议。

4.configureMessageBroker方法用来配置消息代理,由于我们是广播式,这里的消息代理是/topic

3. 添加浏览器向服务器发送消息的类
浏览器方发送来的消息用这个类来接收

package org.cxzc.myyoung.springbootwebsocket;
public class RequestMessage {
    private String name;
    public String getName() {
        return name;
}

4. 添加服务器返回给浏览器消息的类

package org.cxzc.myyoung.springbootwebsocket;
public class ResponseMessage {
    private String responseMessage;
    public ResponseMessage(String responseMessage) {
        this.responseMessage = responseMessage;
    public String getResponseMessage() {
        return responseMessage;
}

5. 创建控制器类

package org.cxzc.myyoung.springbootwebsocket;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class WsController {
    @MessageMapping("/welcome")
    @SendTo("/topic/getResponse")
    public ResponseMessage say(RequestMessage message) {
        System.out.println(message.getName());
        return new ResponseMessage("welcome," + message.getName() + " !");
}

代码解释:
1. 当浏览器向服务器发请求的时候,通过@MessageMapping 映射/welcome这个地址,类似于@RequestMapping

2. @SendTo 注解表示当服务器有消息需要推送的时候,会对订阅了@SendTo中路径的浏览器发送消息。

6. 添加演示界面

首先添加页面需要几个脚本,stomp.min.js , sockjs.min.js , jquery,该脚本可以砸源码中get,将上述脚本放在 src/main/resources/templates/js 下

新建页面:代码如下:

<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <meta charset="UTF-8"/>
    <title>广播式WebSocket</title>
    <script th:src="@{js/sockjs.min.js}"></script>
    <script th:src="@{js/stomp.js}"></script>
    <script th:src="@{js/jquery-3.1.1.js}"></script>
</head>
<body onload="disconnect()">
<noscript><h2 style="color: #e80b0a;">Sorry,浏览器不支持WebSocket</h2></noscript>
        <button id="connect" onclick="connect();">连接</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
    <div id="conversationDiv">
        <label>输入你要发送的信息</label><input type="text" id="name"/>
        <button id="sendName" onclick="sendName();">发送</button>
        <p id="response"></p>
<script type="text/javascript">
    var stompClient = null;
    function setConnected(connected) {
        document.getElementById("connect").disabled = connected;
        document.getElementById("disconnect").disabled = !connected;
        document.getElementById("conversationDiv").style.visibility = connected ? 'visible' : 'hidden';
        $("#response").html();
    function connect() {
        var socket = new SockJS('/endpointCXZC');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function (frame) {
            setConnected(true);
            console.log('Connected:' + frame);
            stompClient.subscribe('/topic/getResponse', function (response) {
                showResponse(JSON.parse(response.body).responseMessage);
    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        setConnected(false);
        console.log('Disconnected');
    function sendName() {
        var name = $('#name').val();
        console.log('name:' + name);
        stompClient.send("/welcome", {}, JSON.stringify({'name': name}));
    function showResponse(message) {
        $("#response").html(message);
</script>
</body>
</html>

1. connect方法是当我点击连接按钮的时候执行的,var socket = new SockJS('/endpointCXZC');表示连接的SockJS的endpoint名称为/endpointCXZC
2. stompClient = Stomp.over(socket);表示使用STOMP来创建WebSocket客户端。然后调用stompClient中的connect方法来连接服务端。然后再通过调用stompClient中的subscribe方法来订阅/topic/getResponse发送来的消息,也就是我们在Controller中的say方法上添加的@SendTo注解的参数。
3. stompClient中的send方法表示发送一条消息到服务端

7.配置 viewController

目的是为ws.html提供便捷的路径映射。

package org.cxzc.myyoung.springbootwebsocket;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration