SpringBoot+vue整合websocket
0.引言
这里我先说下,网上对于websocket的解释有一堆不懂自己查,我这就不做原理解释,只上代码。
1.SpringBoot引入websocket
maven 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
WebSocketConfig 配置文件
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
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config){
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry){
registry.addEndpoint("/chat").setAllowedOrigins("*").withSockJS();
}
}
配置了之后基本上不用做其他的配置了
setAllowedOrigins()为跨域函数
然后是Controller
import org.just.computer.mathproject.Bean.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import java.security.Principal;
import java.util.Date;
@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Message greeting(String content, Principal pl) throws Exception{
Message message = new Message();
message.setContent(content.substring(1,content.length()-1));
message.setData(new Date().toString());
message.setName(pl.getName());
return message;
}
}
这里的Principal 为SpringSecurity相关知识,目的是通过session获得用户名。
到此为止,SpringBoot的配置已经没了
2、Vue通过stompClient使用webSocket
package.json
"dependencies": {
"@tinymce/tinymce-vue": "^3.0.1",
"axios": "^0.19.0",
"echarts": "^4.2.1",
"element-ui": "^2.11.1",
"net": "^1.0.2",
"nprogress": "^0.2.0",
"sockjs-client": "^1.4.0",
"stompjs": "^2.3.3",
"tinymce": "^4.8.5",
"tinymce-vue": "^1.0.0",
"vue": "^2.5.2",
"vue-axios": "^2.1.4",
"vue-echarts": "^4.0.3",
"vue-router": "^3.0.1",
"vue-stomp": "0.0.5"
}
一定要填加的有vue-stomp sockjs-client stompjs这三个
想用的地方直接引入。
import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'
vue中完整代码如下
<template>
<div>
<input type="text" v-model="text">
<button @click="sendMessage">发送消息</button>
<div class="bubble">
</div>
<div>
<div v-for="(data,key) in datas" :key="key">
{{data.content}}
</div>
</div>
</div>
</template>
<script>
import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'
export default {
name: 'ChatRoom',
data () {
return {
text: '',
datas: [],
stompClient: null
}
},
mounted () {
if ('WebSocket' in window) {
this.initWebSocket()
} else {
alert('当前浏览器 Not support websocket')
}
},
methods: {
sendMessage () {
this.stompClient.send('/app/hello', JSON.stringify(this.text), {})
},
initWebSocket () {
this.connection()
},
connection () {
const socket = new SockJS(this.$baseUrl + '/chat')
this.stompClient = Stomp.over(socket)
this.stompClient.connect({}, (frame) => {
this.stompClient.subscribe('/topic/greetings', (greeting) => {
console.log(JSON.parse(greeting.body))
this.datas.push(JSON.parse(greeting.body))
})
})
}
}
}
</script>
<style scoped>
</style>
注意在这行代码this.stompClient.send('/app/hello', JSON.stringify(this.text), {}) {}的位置,有的版本可能是相反的。
运行结果如下所示

SpringBoot+vue整合websocket的更多相关文章
- SpringBoot 同时整合thymeleaf html、vue html和jsp
问题描述 SpringBoot如何同时访问html和jsp SpringBoot访问html页面可以,访问jsp页面报错 SpringBoot如何同时整合thymeleaf html.vue html ...
- springboot 学习之路 8 (整合websocket(1))
目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...
- Springboot整合Websocket遇到的坑
Springboot整合Websocket遇到的坑 一.使用Springboot内嵌的tomcat启动websocket 1.添加ServerEndpointExporter配置bean @Confi ...
- SpringBoot 整合 WebSocket
SpringBoot 整合 WebSocket(topic广播) 1.什么是WebSocket WebSocket为游览器和服务器提供了双工异步通信的功能,即游览器可以向服务器发送消息,服务器也可以向 ...
- Websocket教程SpringBoot+Maven整合(详情)
1.大话websocket及课程介绍 简介: websocket介绍.使用场景分享.学习课程需要什么基础 笔记: websocket介绍: WebSocket协议是基于TCP的一种新的网络协议.它实现 ...
- springboot整合websocket原生版
目录 HTTP缺点 HTTP websocket区别 websocket原理 使用场景 springboot整合websocket 环境准备 客户端连接 加入战队 微信公众号 主题 HTTP请求用于我 ...
- SpringBoot+Vue+WebSocket 实现在线聊天
一.前言 本文将基于 SpringBoot + Vue + WebSocket 实现一个简单的在线聊天功能 页面如下: 在线体验地址:http://www.zhengqingya.com:8101 二 ...
- WebSocket的简单认识&SpringBoot整合websocket
1. 什么是WebSocket?菜鸟对websocket的解释如下 WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议. WebSocket 使得客户端和服务 ...
- SpringBoot + Vue + ElementUI 实现后台管理系统模板 -- 后端篇(一): 搭建基本环境、整合 Swagger、MyBatisPlus、JSR303 以及国际化操作
相关 (1) 相关博文地址: SpringBoot + Vue + ElementUI 实现后台管理系统模板 -- 前端篇(一):搭建基本环境:https://www.cnblogs.com/l-y- ...
随机推荐
- HTML学习 day03
表单 表单 表单:表单域:包含了处理表单数据所用的程序的URL以及数据提交到服务器的方法. 表单控件:(对象.元素):包含了文本框.密码框.隐藏.多行文本框(文本域).复选框.单选框.下拉 ...
- Qt之圆角阴影边框
Qt的主窗体要做出类似WIN7那种圆角阴影边框,这一直是美工的需求. 这里是有一些门道的,尤其是,这里藏着一个很大的秘密. 这个秘密是一个QT的至少横跨3个版本,存在了2年多的BUG... https ...
- Java 静态工厂模式的使用
多相关文章请参考:http://www.enjoytoday.cn/categorys/java 静态工厂模式给人的第一印象就是:static+abstract.这两个词汇已经说明了一切,一个是周期长 ...
- 如何在Appium中使用AI定位
当我们在写自动化测试脚本的时候,传统情况下一定要知道元素的属性,如id.name.class等.那么通过AI的方式定位元素可能就不需要知道元素的属性,评价人对元素的判断来定位,比如,看到一个搜索框,直 ...
- Python—网络抓包与解包(pcap、dpkt)
pcap安装 [root@localhost ~]# pip install pypcap 抓包与解包 # -*- coding:utf-8 -*- import pcap, dpkt import ...
- Mysql—配置文件my.ini或my.cnf的详解
[mysqld] log_bin = mysql-bin binlog_format = mixed expire_logs_days = # 超过7天的binlog删除 slow_query_log ...
- [Linux] deepin系统添加PHP仓库源出错Error: could not find a distribution template for Deepin/stable
aptsources.distro.NoDistroTemplateException: Error: could not find a distribution template for Deepi ...
- CodeForces - 1256D (贪心+思维)
题意 给定一个长度为n的二进制串(即由n个'0'和'1'构成的字符串),你最多可以进行k次交换相邻两个字符的操作,求字典序最小的串. 思路 大致就是找0的位置,然后贪心的放到最前面,这样字典序会最小: ...
- 2019 Multi-University Training Contest 1 String(序列自动机+贪心)
题意 链接:https://vjudge.net/problem/HDU-6586 给你一个字符串和k,还有每个字符出现次数的限制,求一个长度为k的字典序最小的满足限制的子序列. 思路 先构造出序列自 ...
- spark streaming checkpointing windows
spark streaming的相关概念: spark的核心是创建一个RDD对象,然后对RDD对象进行计算操作等 streaming可以理解为是 一个连续不断的数据流 ,然后将每个固定时间段里的数据构 ...