websocket广播式实例
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广播式实例的更多相关文章
- springboot + websocket + spring-messaging实现服务器向浏览器广播式
目录结构 pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http:// ...
- spring+websocket的整合实例--可使用
spring+websocket的整合实例----借鉴如下链接--此贴用于笔记 https://blog.csdn.net/qq_35515521/article/details/78610847
- 新入手服务器不会玩?抢占式实例服务器教程,从零搭建tomcat超简流程
新入手服务器不会玩?抢占式实例服务器教程,从零搭建tomcat超简流程 相信很多新人入手Linux服务器后,一脸无奈,这黑框框究竟能干啥?忽觉巨亏血亏不是? 这里面门道可不是你想象中的那么点,简则服务 ...
- springboot2 -广播式WebSocket
1.WebSocket,STOMP,SockJS含义 WebSocket:WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议. SockJS:SockJS 是 We ...
- C++学习笔记36 (模板的细节明确template specialization)和显式实例(template instantiation)
C++有时模板很可能无法处理某些类型的. 例如: #include <iostream> using namespace std; class man{ private: string n ...
- .NET 即时通信,WebSocket服务端实例
即时通信常用手段 1.第三方平台 谷歌.腾讯 环信等多如牛毛,其中谷歌即时通信是免费的,但免费就是免费的并不好用.其他的一些第三方一般收费的,使用要则限流(1s/限制x条消息)要么则限制用户数. 但稳 ...
- C#实现WebSocket协议客户端和服务器websocket sharp组件实例解析
看到这篇文章的题目,估计很多人都会问,这个组件是不是有些显的无聊了,说到web通信,很多人都会想到ASP.NET SignalR,或者Nodejs等等,实现web的网络实时通讯.有关于web实时通信的 ...
- html5 WebSocket的Js实例教程
详细解读一个简单+ ,附带完整的javascript websocket实例源码,以及实例代码效果演示页面,并对本实例的核心代码进行了深入解读. 从WebSocket通讯三个阶段(打开握手.数据传递. ...
- Nginx实战之反向代理WebSocket的配置实例
http://www.jb51.net/article/112183.htm 最近在工作中遇到一个需求,需要使用 nginx 反向代理websocket,经过查找一番资料,目前已经测试通过,所以这篇文 ...
随机推荐
- C语言中,如何输出一个菱形!
int zh,zl,h,l; //zh:行的总数 zl:列的总数 h:当前行 l:当前列 for( ...
- Vue v-if,v-else-if,v-else的使用
v-else-if 要紧跟 v-if v-else要紧跟v-else-if 或 v-if 代码: <!doctype html> <html lang="en"& ...
- ASP.NET开发实战——(六)ASP.NET MVC & 分层 代码篇
上一篇文章对如何规范使用ASP.NET进行了介绍,本章内容将根据上一篇得出的结论来修改博客应用的代码. 代码分层 综合考虑将博客应用代码分为以下几个层次: ○ 模型:代表应用程序中的数据模型,与数据库 ...
- 【2019.8.8 慈溪模拟赛 T1】开箱(chest)(暴力DP水过)
转化题意 这题目乍一看十分玄学,完全不可做. 但实际上,假设我们在原序列从小到大排序之后,选择开的宝箱编号是\(p_{1\sim Z}\),则最终答案就是: \[\sum_{i=1}^Za_{p_i} ...
- PyCharm工具配置和快捷键使用
PyCharm是一款高效开发Python程序的IDE,包含有自动联想.语法高亮.代码调试.管理多个版本Python解释器等功能.本文主要描述Python界面个性化定制方法(字体.颜色配置).常用配置和 ...
- How does Chrome Extension crx Downloader work? ——— From crxdown.com
How does Chrome Extension crx Downloader work? Home >> blog >> How does Chrome Extension ...
- FineUIPro v6.0.1 小版本更新!
这次修正了 v6.0.0版本的几个问题,建议所有用户升级到此版本: +修正调用F.addMainTab时可能出现JS错误的问题(34484135,1450561644). -仅在未调用F.ini ...
- 小小见解之python循环依赖
a.py from b import b print '---------this is module a.py----------' def a(): print "hello, a&qu ...
- java基础之----java常见异常及代码示例
概述 java中有两种错误类型,一个是Exception,一个是Error,都在java.lang包下,一般来说程序中的try...catch捕获的是Exception类型的异常,而Error类型的错 ...
- matplotlib基础
Matplotlib 基础 注:本文中的程序都默认引入了numpy库和matplotlib库,并且分别简写为np与plt:如果读者不知道怎么使用numpy库,可以移步到这一博客上进行简单的学习 一.简 ...