阅读本文前,请您先点击上面的蓝色字体“程序职场”关注后再点击置顶公众号,这样您就可以收到最优质的文章了。每周都有分享。

 


大家好,我是“追梦蜗牛”,大家可以在公众号后台回复 “Java资料”获得技能提升的资料,绝对是干货。

 

本文是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的原理和使用场景说的很详细,小伙伴可以 看一下
https://www.zhihu.com/question/20215561

 

(二). WebSocket实战

1.新建项目

Spring Boot(七)Spring Boot的WebSocket_spring

Spring Boot(七)Spring Boot的WebSocket_mvc_02

Spring Boot(七)Spring Boot的WebSocket_html_03

 

注意看在创建的时候 我们添加了两个依赖: 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@EnableWebSocketMessageBrokerpublic 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;
@Controllerpublic 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"><head>    <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><div>    <div>        <button id="connect" onclick="connect();">连接</button>        <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>    </div>
<div id="conversationDiv"> <label>输入你要发送的信息</label><input type="text" id="name"/> <button id="sendName" onclick="sendName();">发送</button> <p id="response"></p> </div></div><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;
@Configurationpublic class WebMvcConfig extends WebMvcConfigurationSupport { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/ws").setViewName("/ws"); }}

我们映射到ws路径上了。

 

浏览器访问 ,打开多个浏览器,显示如下:

 

 

Spring Boot(七)Spring Boot的WebSocket_服务器_04

 

当我在一个浏览器输入信息发送后 其他浏览器能够收到消息。

 

 

ok,Spring Boot 使用WebSocket实现消息推送 到这里就完成了,如果小伙伴还有疑问,可以 公众号 加群,我们一起进步

 

参考:
1. 
《JavaEE开发的颠覆者 Spring Boot实战》

 

本案例下载地址:

https://github.com/ProceduralZC/itcxzc/tree/master/springbootwebsocket

 

Spring Boot(七)Spring Boot的WebSocket_mvc_05

 

 

- End -

 

 

Spring Boot(七)Spring Boot的WebSocket_mvc_06

长按二维码关注

期待您的加入

 

 

Spring Boot(七)Spring Boot的WebSocket_发送消息_07

 

 

近期推荐阅读:

职场我们如何寻找自己的定位?

IT项目开发流程

怎样才能算自由者?

频繁跳槽会有什么不好的影响?

 

资源整理:
包括不限于Java、Python、Linux、前端、人工智能、架构、大数据、电子书 ,移动端,小程序,项目等