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的更多相关文章

  1. SpringBoot 同时整合thymeleaf html、vue html和jsp

    问题描述 SpringBoot如何同时访问html和jsp SpringBoot访问html页面可以,访问jsp页面报错 SpringBoot如何同时整合thymeleaf html.vue html ...

  2. springboot 学习之路 8 (整合websocket(1))

    目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...

  3. Springboot整合Websocket遇到的坑

    Springboot整合Websocket遇到的坑 一.使用Springboot内嵌的tomcat启动websocket 1.添加ServerEndpointExporter配置bean @Confi ...

  4. SpringBoot 整合 WebSocket

    SpringBoot 整合 WebSocket(topic广播) 1.什么是WebSocket WebSocket为游览器和服务器提供了双工异步通信的功能,即游览器可以向服务器发送消息,服务器也可以向 ...

  5. Websocket教程SpringBoot+Maven整合(详情)

    1.大话websocket及课程介绍 简介: websocket介绍.使用场景分享.学习课程需要什么基础 笔记: websocket介绍: WebSocket协议是基于TCP的一种新的网络协议.它实现 ...

  6. springboot整合websocket原生版

    目录 HTTP缺点 HTTP websocket区别 websocket原理 使用场景 springboot整合websocket 环境准备 客户端连接 加入战队 微信公众号 主题 HTTP请求用于我 ...

  7. SpringBoot+Vue+WebSocket 实现在线聊天

    一.前言 本文将基于 SpringBoot + Vue + WebSocket 实现一个简单的在线聊天功能 页面如下: 在线体验地址:http://www.zhengqingya.com:8101 二 ...

  8. WebSocket的简单认识&SpringBoot整合websocket

    1. 什么是WebSocket?菜鸟对websocket的解释如下 WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议. WebSocket 使得客户端和服务 ...

  9. SpringBoot + Vue + ElementUI 实现后台管理系统模板 -- 后端篇(一): 搭建基本环境、整合 Swagger、MyBatisPlus、JSR303 以及国际化操作

    相关 (1) 相关博文地址: SpringBoot + Vue + ElementUI 实现后台管理系统模板 -- 前端篇(一):搭建基本环境:https://www.cnblogs.com/l-y- ...

随机推荐

  1. Java数据结构(一):栈

    导言:栈和我们的现实当中的箱子是一样的,保持一个先进后出,后进先出的原则.比如我们往一个箱子堆积衣服,一件一件地放进去之后,过一段时间再回来拿.那么最先放进去的衣服肯定最后拿出来,最后放进去的衣服就会 ...

  2. tableView左划自定义带图片按钮

    本方法实现的原理是将自定义按钮加在tableViewCell.contentView的屏幕外的frame上,打个比方,如果是5系的话,那么你自定义按钮的frame的起点就在(320+,0)(320+表 ...

  3. git终端提交代码

  4. split("\\,")引起的java.lang.ArrayIndexOutOfBoundsException异常解决方案

    由split("\,")引起的指标越界异常 如果字符串最后分隔符里的字段为空,使用split("\\,")进行切割时,最后的空字段不会切割 例如"a, ...

  5. HashMap底层实现及原理

    注意:文章的内容基于JDK1.7进行分析.1.8做的改动文章末尾进行讲解.       一.先来熟悉一下我们常用的HashMap: 1.HashSet和HashMap概述 对于HashSst及其子类而 ...

  6. c# WF 第2节 窗体的添加与删除

    本节内容: 1: 窗体的添加 2: 窗体的删除 1: 窗体的添加 2: 窗体的删除 3:窗口的运行,发现只有一个form1 是因为

  7. Kvm命令集管理虚拟机

    KVM虚拟机配置文件位置 [root@localhost ~]# ll /etc/libvirt/qemu/ 总用量 drwxr-xr-x root root 12月 : autostart drwx ...

  8. 自己整理的模拟爬虫的user-agent

    自己经常用的一些爬虫用的user-agent头部 This XML file does not appear to have any style information associated with ...

  9. 元昊讲django框架

    一 什么是web框架? 框架,即framework,特指为解决一个开放性问题而设计的具有一定约束性的支撑结构,使用框架可以帮你快速开发特定的系统,简单地说,就是你用别人搭建好的舞台来做表演. 对于所有 ...

  10. 《高性能MySQL》读后感——聚簇索引

    <高性能MySQL>读后感——聚簇索引 聚簇索引并不是一种单独的索引类型,而是一种数据存储方式.比如,InnoDB的聚簇索引使用B+Tree的数据结构存储索引和数据. 当表有聚簇索引时,它 ...