1、引入相关依赖

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>

2、写配置类

package springboot.config;

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;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/endpointZouHong").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
}
}

3、实体类

服务端接收类:

package springboot.bean;
public class ZouhongServerMessage {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

浏览器接收类:

package springboot.bean;
public class ZouhongBrowResponse {
private String responseMessage;
public ZouhongBrowResponse(String responseMessage) {
this.responseMessage = responseMessage;
}
public String getResponseMessage() {
return responseMessage;
}
public void setResponseMessage(String responseMessage) {
this.responseMessage = responseMessage;
} }

4、处理器

package springboot.controller;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import springboot.bean.ZouhongBrowResponse;
import springboot.bean.ZouhongServerMessage; @Controller
public class ZHController {
@MessageMapping("/welcome")
@SendTo("/topic/getResponse")
public ZouhongBrowResponse say(ZouhongServerMessage message) throws Exception{
Thread.sleep();
return new ZouhongBrowResponse("welcome,"+message.getName()+"!");
}
}

5、前端

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>SpringBoot+websocket+广播式</title>
</head>
<body>
<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 th:src="@{js/jquery.js}"></script>
<script th:src="@{js/stomp.min.js}"></script>
<script th:src="@{js/sockjs.min.js}"></script>
<script th:inline="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('/endpointZouHong');
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);
stompClient.send('/welcome',{},JSON.stringify({'name':name})); } function showResponse(message){
var response=$("#response");
response.html(message); }
</script>
</body>
</html>

6、效果图

websocket广播式实例的更多相关文章

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

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

  2. spring+websocket的整合实例--可使用

    spring+websocket的整合实例----借鉴如下链接--此贴用于笔记 https://blog.csdn.net/qq_35515521/article/details/78610847

  3. 新入手服务器不会玩?抢占式实例服务器教程,从零搭建tomcat超简流程

    新入手服务器不会玩?抢占式实例服务器教程,从零搭建tomcat超简流程 相信很多新人入手Linux服务器后,一脸无奈,这黑框框究竟能干啥?忽觉巨亏血亏不是? 这里面门道可不是你想象中的那么点,简则服务 ...

  4. springboot2 -广播式WebSocket

    1.WebSocket,STOMP,SockJS含义 WebSocket:WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议. SockJS:SockJS 是 We ...

  5. C++学习笔记36 (模板的细节明确template specialization)和显式实例(template instantiation)

    C++有时模板很可能无法处理某些类型的. 例如: #include <iostream> using namespace std; class man{ private: string n ...

  6. .NET 即时通信,WebSocket服务端实例

    即时通信常用手段 1.第三方平台 谷歌.腾讯 环信等多如牛毛,其中谷歌即时通信是免费的,但免费就是免费的并不好用.其他的一些第三方一般收费的,使用要则限流(1s/限制x条消息)要么则限制用户数. 但稳 ...

  7. C#实现WebSocket协议客户端和服务器websocket sharp组件实例解析

    看到这篇文章的题目,估计很多人都会问,这个组件是不是有些显的无聊了,说到web通信,很多人都会想到ASP.NET SignalR,或者Nodejs等等,实现web的网络实时通讯.有关于web实时通信的 ...

  8. html5 WebSocket的Js实例教程

    详细解读一个简单+ ,附带完整的javascript websocket实例源码,以及实例代码效果演示页面,并对本实例的核心代码进行了深入解读. 从WebSocket通讯三个阶段(打开握手.数据传递. ...

  9. Nginx实战之反向代理WebSocket的配置实例

    http://www.jb51.net/article/112183.htm 最近在工作中遇到一个需求,需要使用 nginx 反向代理websocket,经过查找一番资料,目前已经测试通过,所以这篇文 ...

随机推荐

  1. Ubuntu中如何使得程序在后台运行

    Ubuntu中如何使得程序在后台运行 一.前言 在Ubuntu中有的程序启动需要执行改程序./bin目录下的文件,并且启动之后这个shell就不能使用和关闭了,非常的麻烦,因此就有了相应的命令来解决这 ...

  2. 《Linux内核原理与分析》教学进程

    目录 2019-2020-1 <Linux内核原理与分析>教学进程 考核方案 第一周: 第二周: 第三周: 第四周: 第五周 第六周 第七周: 第八周 第九周 第十周 第十一周: 第十二周 ...

  3. 探索ASP.Net Core 3.0系列四:在ASP.NET Core 3.0的应用中启动时运行异步任务

    前言:在本文中,我将介绍ASP.NET Core 3.0 WebHost的微小更改如何使使用IHostedService在应用程序启动时更轻松地运行异步任务. 翻译 :Andrew Lock   ht ...

  4. 物联网架构成长之路(34)-物联网数据可视化grafana展示

    一.前言 前面介绍了利用后台业务服务器监听EMQ的Topic,作为EMQ的一个客户端方式来保存数据.然后将数据保存到时序数据库InfluxDB中.本小节就简单介绍一下如何安装和使用,及如何利用Graf ...

  5. 【解决错误】Non-reversible reg-exp portion: '(?i'

    在将Django升级到2.1后,运行 Django 自带后台后,或 使用 redirect 方法,就一直报错:Non-reversible reg-exp portion: '(?i'. 错误一 Dj ...

  6. 六、Spring之初步认识AOP

    Spring之初步认识AOP [1]AOP概览 什么是AOP?(来自百度) ​ 在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行 ...

  7. Mybatis中的association用法

    这篇文章我们将来学习一些 association 用法 表结构 DROP TABLE IF EXISTS `student`; CREATE TABLE `student` (  `id` int(1 ...

  8. CompletableFuture1

    public class CompletableFutureTest { public static void main(String[] args) throws Exception { test5 ...

  9. 【转】EF架构~为EF DbContext生成的实体添加注释(T5模板应用)

    嗨,没法说,EF4的TT模版加上注释后,升级到EF5的TT模版后,注释就不通用了,所以,还得再研究一下,然后把操作方法再分享出来,没辙的微软! T4模版可能有些凌乱,这在T5模版里有了不错的改进,但我 ...

  10. 【Python】运算符

    python是强类型语言,某些场合下需要进行类型转换.关系运算符的结果是true或false.这里介绍一下基本的运算符,和几个使用实例,了解并掌握python中range()函数和math类库的引入和 ...