1.WebSocket,STOMP,SockJS含义

WebSocket:WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。

SockJS:SockJS 是 WebSocket 技术的一种模拟。为了应对许多浏览器不支持WebSocket协议的问题,设计了备选SockJs。开启并使SockJS后,它会优先选用Websocket协议作为传输协议,如果浏览器不支持Websocket协议,则会在其他方案中,选择一个较好的协议进行通讯。

STOMP:用于定义websocket的消息体格式.

2.springboot代码

定义websocket传输消息的内容格式。

浏览器向服务端发送消息:

package com.dyq.demo.DTO;

public class SocketRequestMessage {
private String requestMessage; public String getRequestMessage() {
return requestMessage;
}
}

服务端向浏览器发送消息:

package com.dyq.demo.DTO;

public class SocketResponseMessage {
private String responseMessage; public SocketResponseMessage(String responseMessage){
this.responseMessage = responseMessage;
} public String getResponseMessage() {
return responseMessage;
}
}

WebSocket配置文件:

package com.dyq.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.*; @Configuration
@EnableWebSocketMessageBroker//启用STOMP协议来传输基于代理(message broker)的消息
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
//注册一个stomp的节点,使用SockJS协议
registry.addEndpoint("/customendpoint").withSockJS();
} @Override
public void configureMessageBroker(MessageBrokerRegistry config) {
//config.setApplicationDestinationPrefixes("/app");
//使用内置的消息代理进行订阅和广播;路由消息的目标头以“/topic”或“/queue”开头。
config.enableSimpleBroker("/topic", "/queue");
}
}

控制器代码:

package com.dyq.demo.controller;

import com.dyq.demo.DTO.SocketRequestMessage;
import com.dyq.demo.DTO.SocketResponseMessage;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller; @Controller
public class WebSocketController {
@MessageMapping("/socket")//浏览器向服务器发送请求时,通过MessageMapping映射/socket地址
@SendTo("/topic/getResponse")//当服务器有消息时,会对订阅了@SendTo中路径的浏览器发送消息
public SocketResponseMessage say(SocketRequestMessage message) throws InterruptedException {
Thread.sleep(3000);
return new SocketResponseMessage("接收到RequestMessage:"+message.getRequestMessage()+"!");
}
}

前端页面代码websocket.html:
前端需要三个js文件,大家可以到http://www.bootcdn.cn/去搜索下载
目前最新版:
sockjs.min.js:https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js
stomp.min.js:https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js
jquery.min.js:https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>websocket</title>
</head>
<body>
<noscript>Your browser does not support JavaScript!</noscript>
<div>
<div>
<button id="connect" onclick="connect()">连接</button>
<button id="disconnect" onclick="disconnect()">断开连接</button><br/>
<p id="connectStatus">未连接</p>
<br/><br/>
</div>
<div id="conversation">
<label>输入发送信息</label>
<input type="text" id="requestMessage">
<button id="sendMessage" onclick="sendMessage()">发送</button>
<p id="responseMessage"></p>
</div>
</div>
<script th:src="@{js/sockjs.min.js}"></script>
<script th:src="@{js/stomp.min.js}"></script>
<script th:src="@{js/jquery.min.js}"></script>
<script type="text/javascript">
var stompClient = null;
$(function () {
setConnected(false);
});
function setConnected(connected) {
if(connected){
$("#connect").attr("disabled",true);
$("#disconnect").attr("disabled",false);
$("#conversation").show();
$("#connectStatus").html("已连接");
}else{
$("#connect").attr("disabled",false);
$("#disconnect").attr("disabled",true);
$("#conversation").hide();
$("#connectStatus").html("未连接");
}
$("#responseMessage").html();
}
function connect() {
var socket = new SockJS("/customendpoint");//连接SockJs的endpoint-/customendpoint
stompClient = Stomp.over(socket)//使用STOMP子协议的WebSocket客户端
stompClient.connect({},function (frame) {
setConnected(true);
console.log("Connected:"+frame);
stompClient.subscribe("/topic/getResponse",function (response) {
showResponseMessage(JSON.parse(response.body).responseMessage);
});
});
}
function disconnect() {
if(stompClient!=null){
stompClient.disconnect();
setConnected(false);
console.log("Disconnected")
}
}
function showResponseMessage(message) {
$("#responseMessage").html(message);
}
function sendMessage() {
var requseMessage = $("#requestMessage").val();
console.log("requseMessage:"+requseMessage);
stompClient.send("/socket",{},JSON.stringify({"requestMessage":requseMessage}));
}
</script>
</body>
</html>

需要在Mvc配置文件:

package com.dyq.demo.config;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*; @Configuration
public class MVCConfig implements WebMvcConfigurer { public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("/index");
registry.addViewController("/index").setViewName("/index");
registry.addViewController("/websocket").setViewName("/websocket");
}
}

运行,开多个浏览器窗口,连接上,如果一个浏览器发送消息到服务器,其他窗口能接受到信息。
然后运行效果:

springboot2 -广播式WebSocket的更多相关文章

  1. springboot + websocket + spring-messaging实现服务器向浏览器广播式

    目录结构 pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http:// ...

  2. websocket广播式实例

    1.引入相关依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>sp ...

  3. Spring3 springMVC添加注解式WebSocket

    Spring3添加注解式WebSocket 推荐升级成spring4以后,spring4已经集成WebSocket. 由于种种原因,项目开发处于快结束的阶段了,升级成spring4不想那么麻烦,但是又 ...

  4. SpringBoot2.x集成WebSocket

    WebSocket 不做过多得介绍,这里有篇比较全面得文章      Spring Boot系列十六 WebSocket简介和spring boot集成简单消息代理 我这里是精简版,只挑出核心代码记录 ...

  5. SpringBoot2.0集成WebSocket,实现后台向前端推送信息

    感谢作者,支持原创: https://blog.csdn.net/moshowgame/article/details/80275084 什么是WebSocket? WebSocket协议是基于TCP ...

  6. SpringBoot2.0整合WebSocket,实现后端数据实时推送!

    之前公司的某个系统为了实现推送技术,所用的技术都是Ajax轮询,这种方式浏览器需要不断的向服务器发出请求,显然这样会浪费很多的带宽等资源,所以研究了下WebSocket,本文将详细介绍下. 一.什么是 ...

  7. springboot2.0集成webSocket

    WebSocket和http的区别? http协议是用在应用层的协议,他是基于tcp协议的,http协议建立链接也必须要有三次握手才能发送信息. http链接分为短链接,长链接,短链接是每次请求都要三 ...

  8. Springboot:SpringBoot2.0整合WebSocket,实现后端数据实时推送!

    一.什么是WebSocket? B/S结构的软件项目中有时客户端需要实时的获得服务器消息,但默认HTTP协议只支持请求响应模式,这样做可以简化Web服务器,减少服务器的负担,加快响应速度,因为服务器不 ...

  9. 在Spring Boot框架下使用WebSocket实现消息推送

    Spring Boot的学习持续进行中.前面两篇博客我们介绍了如何使用Spring Boot容器搭建Web项目(使用Spring Boot开发Web项目)以及怎样为我们的Project添加HTTPS的 ...

随机推荐

  1. jmeter后置处理器之正則表達式提取器

    新浪围脖>@o蜗牛快跑o    使用这个组件时,注意使用带分组的正則表達式 使用正则分组方便提取干净数据.以免再次处理数据字符串 正則表達式在线工具推荐:点击打开链接 正則表達式语法參考:点击打 ...

  2. 关于erlang中的timer:tc/3

    timer:tc/3对于统计函数运行时间是个很不错的函数, 截图timer:tc/1,tc/2,tc/3的API: 拿斐波那契数列入手做个讲解: -module(fib). -export([fib/ ...

  3. Hadoop集群_HDFS初探之旅

    1.HDFS简介 HDFS(Hadoop Distributed File System)是Hadoop项目的核心子项目,是分布式计算中数据存储管理的基础,是基于流数据模式访问和处理超大文件的需求而开 ...

  4. iphone开发的技巧

    一,改动状态栏: 1.增加[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];但此方法仅仅是不显示状态条,状态 ...

  5. duplicate symbols for architeture arm64 linker command failed with code 1(use-c to see invocation)

    duplicate symbols for architeture arm64  linker command failed with code 1(use-c to see invocation) ...

  6. registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

    本文转载至 http://bbs.csdn.net/topics/390889517 IOS8 PUSH解决方法 昨天晚上整理PUSH的东西,准备些一个教程,全部弄好之后,发现没有达到预期的效果,本以 ...

  7. 【BZOJ4950】lydsy七月月赛 C 二分图最大匹配

    [BZOJ4950]lydsy七月月赛 C 题面 题解:比较直接的想法就是:每行,每列的最大值都留下,剩下的格子都变成1.但是如果一个格子既是行的最大值又是列的最大值,那么我们只需要把它留下即可.这就 ...

  8. Hibernate基础知识介绍

    一.什么是Hibernate? Hibernate,翻译过来是冬眠的意思,其实对于对象来说就是持久化.持久化(Persistence),即把数据(如内存中的对象)保存到可永久保存的存储设备中(如磁盘) ...

  9. windows下使用ofstream默认输出内存数据到文件中时,会自动将0A换成0A0D

    0A即\n,而0D是\r,windows下换行是\n\r,因此会自动转换. 但是,这样会带来很大的问题,导致由内存写入文件中的数据和内存中不一样,还不知道是什么原因造成的. 特别是将从网络接收来的pn ...

  10. Java NIO 粘包 拆包 (实战) - 史上最全解读

    疯狂创客圈 Java 聊天程序[ 亿级流量]实战系列之13 [博客园 总入口 ] 本文的源码工程:Netty 粘包/半包原理与拆包实战 源码 本实例是<Netty 粘包/半包原理与拆包实战> ...