在这里想先做一个 webSocket 广播式的运用, 供大家对 webSocket 入门学习;
首先, 让大家在页面先看下效果:
图片. PNG
为什么说这是一个简单的 WebSocket 广播式的运用; 请看网页调试:
图片. PNG
理由:
1.101 状态码: 101 是 websocket 协议状态码, 101 表示协议切换成功;
2. 当你不断输入不同的名字进行发送时, 不会有新的连接出现, 之前有一个 101 的连接也一直没有断开;
所以说这是一个简单的 WebSocket 广播式运用!
声明:
现在以及之后的 springboot 开发都是在我原有的环境已布置好的项目上进行开发的;
可参考我之前的几篇文章:
Spring Boot(一): 入门篇
Spring Boot(二): 简单的初始配置
这里简单展示下项目工程的结构, 如下图:
图片. PNG
步骤:
一, 在项目 maven 配置中添加依赖:
- <!-- websocket -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-websocket</artifactId>
- </dependency>
二, 创建 WebSocketConfig 类, 代码如下
- package com.example.demo.config;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.messaging.simp.config.MessageBrokerRegistry;
- import org.springframework.Web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
- import org.springframework.Web.socket.config.annotation.EnableWebSocketMessageBroker;
- import org.springframework.Web.socket.config.annotation.StompEndpointRegistry;
- import org.springframework.Web.socket.config.annotation.StompWebSocketEndpointRegistration;
- /**
- * Created by AxeLai on 2019/04/29 0011.
- */
- @Configuration
- @EnableWebSocketMessageBroker//(1),@EnableWebSocketMessageBroker 注解用于开启使用 STOMP 协议来传输基于代理 (MessageBroker) 的消息, 这时候控制器 (controller) 开始支持 @MessageMapping, 就像是使用 @requestMapping 一样.
- public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
- @Override
- public void registerStompEndpoints(StompEndpointRegistry registry) {
- registry.addEndpoint("/stomp").withSockJS(); //(2), 注册一个 Stomp 的节点(endpoint), 并指定使用 SockJS 协议.
- //stomp 就是 websocket 的端点, 客户端需要注册这个端点进行链接, withSockJS 允许客户端利用 sockjs 进行浏览器兼容性处理
- }
- @Override
- public void configureMessageBroker(MessageBrokerRegistry registry) {
- registry.enableSimpleBroker("/topic");//(3), 配置消息代理(MessageBroker).
- // 设置服务器广播消息的基础路径
- // registry.setApplicationDestinationPrefixes("/app");// 设置客户端订阅消息的基础路径
- }
- }
三, 创建 WiselyMessage 类(浏览器向服务器传送消息, 用该类进行接收), 代码如下:
- package com.example.demo.model;
- /**
- * @author AxeLai
- * @date 2019-04-29 09:06
- * 浏览器向服务器传送消息, 用该类进行接收
- */
- public class WiselyMessage {
- private String name;
- public String getName(){
- return name;
- }
- }
四, 创建 WiselyResponse 类(服务器向浏览器传送消息, 用该类进行传送), 代码如下:
- package com.example.demo.model;
- /**
- * @author AxeLai
- * @date 2019-04-29 09:06
- * 服务器向浏览器传送消息, 用该类进行传送
- */
- public class WiselyResponse {
- private String responseMessage;
- public WiselyResponse(String responseMessage){
- this.responseMessage = responseMessage;
- }
- public String getResponseMessage(){
- return responseMessage;
- }
- }
五, 创建 WsController 类, 代码如下:
- package com.example.demo.controller;
- import com.example.demo.model.WiselyMessage;
- import com.example.demo.model.WiselyResponse;
- import org.springframework.messaging.handler.annotation.MessageMapping;
- import org.springframework.messaging.handler.annotation.SendTo;
- import org.springframework.stereotype.Controller;
- /**
- * @author AxeLai
- * @date 2019-04-29 09:08
- */
- @Controller
- public class WsController {
- @MessageMapping("/welcome")//1@MessageMapping 和 @RequestMapping 功能类似, 用于设置 URL 映射地址, 浏览器向服务器发起请求, 需要通过该地址.
- @SendTo("/topic/getResponse")//2 如果服务器接受到了消息, 就会对订阅了 @SendTo 括号中的地址传送消息
- public WiselyResponse say(WiselyMessage message) throws Exception {
- return new WiselyResponse("你好," + message.getName() + "!");
- }
- }
六, 创建 IndexPageConfig 配置类,(该类的作用是可以把 websocket1.html 设为首页, 只需要在地址栏里面输入 localhost:8080, 就会找到 websocket1.HTML), 代码如下:
- package com.example.demo.config;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.stereotype.Controller;
- import org.springframework.Web.bind.annotation.RequestMapping;
- import org.springframework.Web.servlet.config.annotation.ViewControllerRegistry;
- import org.springframework.Web.servlet.config.annotation.WebMvcConfigurerAdapter;
- import org.springframework.Web.servlet.view.RedirectView;
- /**
- * @author AxeLai
- * @date 2019-04-29 09:31
- */
- @Controller
- public class IndexPageConfig {
- @RequestMapping("/")
- public RedirectView ws() {
- return new RedirectView("/websocket1.html");
- }
- }
七, 网页 HTML 编写
首先先加入三个 JS: 如图:
图片. PNG
其实是要导入三个包, 其他两个我们直接从外网导入; 如下:
- <script src="js/jquery-2.1.1.min.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>
创建前端页面 websocket1.HTML, 代码如下:
- <!DOCTYPE HTML>
- <HTML>
- <head>
- <meta charset="UTF-8" />
- <title>
- Spring Boot+WebSocket + 广播式
- </title>
- </head>
- <body onload="disconnect()">
- <noscript>
- <h2 style="color: #ff0000">
- 貌似你的浏览器不支持 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 src="js/jquery-2.1.1.min.js">
- </script>
- <script src="//cdn.bootcss.com/angular.js/1.5.6/angular.min.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>
- <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('/stomp'); //1<!--(1)连接 SockJS 的 endpoint 是 "stomp", 与后台代码中注册的 endpoint 要一样.-->
- stompClient = Stomp.over(socket); //2<!--(2)创建 STOMP 协议的 webSocket 客户端.-->
- stompClient.connect({},
- function(frame) { //3<!--(3)连接 webSocket 的服务端.-->
- setConnected(true);
- console.log('开始进行连接 Connected:' + frame);
- stompClient.subscribe('/topic/getResponse',
- function(respnose) { //4<!--(4)通过 stompClient.subscribe()订阅服务器的目标是'/topic/getResponse'发送过来的地址, 与 @SendTo 中的地址对应.-->
- showResponse(JSON.parse(respnose.body).responseMessage);
- });
- });
- }
- function disconnect() {
- if (stompClient != null) {
- stompClient.disconnect();
- }
- setConnected(false);
- console.log("Disconnected");
- }
- function sendName() {
- var name = $('#name').val();
- stompClient.send("/welcome", {},
- JSON.stringify({
- 'name': name
- })); //5<!--(5)通过 stompClient.send()向地址为 "/welcome" 的服务器地址发起请求, 与 @MessageMapping 里的地址对应.-->
- }
- function showResponse(message) {
- var response = $("#response");
- response.HTML(message);
- }
- </script>
- </body>
- </HTML>
运行程序, 浏览器打开 http://localhost:8080/, 就可以进行测试了.......
来源: http://www.jianshu.com/p/6cebcf69abff