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- ...
随机推荐
- 0基础入门学习Python(第4章)
第四章,了不起的分支和循环 4.1 分支和循环 Python主要依靠缩进来区分代码块 4.2 快速上手 成绩按照分数来划分等级,90分以上为A,80~90 为B,60~80 为C,60以下为D p4_ ...
- Tomcat启动分析(二)-自己编译Tomcat
为了方便分析Tomcat源码,利用大家习惯的方式来进行Debug调试,那么如何将Tomcat源码导入到Eclipse呢,这就是本文的重点 1 准备 1.1 获取Tomcat源码 获取tomcat源码有 ...
- [PHP] PHP调用IMAP协议读取邮件类库
socket.php 为连接socket的类库 imap.php 基于socket的imap协议封装 test.php 进行测试 require_once 'socket.php'; require_ ...
- spark Streaming与kafka的集成消费
Spark 2.3.3 Kafka 2.11-1.0.2 Java jdk1.8.0_191 Hbase 1.2.11 from pyspark impo ...
- AWVS破解安装
参考大佬@pirogue的安装步骤及awvs安装包,@pandahks的安装依赖,在本地虚拟机安装awvs,艰辛历程记录如下. 虚拟机操作系统:CentOS Linux release 7.7.190 ...
- 爬虫scrapy模块
首先下载scrapy模块 这里有惊喜 https://www.cnblogs.com/bobo-zhang/p/10068997.html 创建一个scrapy文件 首先在终端找到一个文件夹 输入 s ...
- 密标与pdf有什么关系
密标与pdf有什么关系 密标与pdf有什么关系 密标与pdf有什么关系
- 面向对象程序设计(JAVA) 第11周学习指导及要求
2019面向对象程序设计(Java)第11周学习指导及要求 (2019.11.8-2018.11.11) 学习目标 理解泛型概念: 掌握泛型类的定义与使用: 掌握泛型方法的声明与使用: 掌握泛型接 ...
- Python进阶-XVI 继承 单继承 多继承
一.初识继承 1.引入继承 class A(object): pass # 父类,基类,超类 class B: pass # 父类,基类,超类 class A_son(A, B): pass # 子类 ...
- Vue 使用数组和对象控制Class
直接上代码: <!doctype html> <html lang="en"> <head> <meta charset="UT ...