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. Sublime Text 3 插件安装、搭建Python、Java开发环境

    一.下载并安装 Sublime Text 3 官网地址:http://www.sublimetext.com目前最新版本为:3.2.1 (BUILD 3207)安装时勾选“Add to explore ...

  2. netcore codefirst生成数据库命令

    1.程序通过nuget安装包 Microsoft.EntityFrameworkCore.Design 2.生成添加脚本 add-migration InitialCreate -Context AL ...

  3. mssql sqlserver 使用sql脚本实现相邻两条数据相减的方法分享

    摘要: 下文讲述使用sql脚本实现相邻两条数据相减的方法,如下所示: 实验环境:sql server 2008 R2 实现思路: 1.使用cte表达式,对当前表进行重新编号 2.使用左连接对 表达式 ...

  4. springboot + shiro + mysql + mybatis 工程快速搭建

    1. 新建 springboot 工程 2. 随便起个名字 3. 初始化工程 4. 导入 shiro 和 thymeleaf 依赖 <!-- thymeleaf依赖 --> <dep ...

  5. 谷歌浏览器安装JsonView插件

    可方便阅读json格式文件,参考https://www.jianshu.com/p/6ea9f2245f4d

  6. mysql命令大全一

    mysql -u root -p;create database qa;show databases;use qa; create table results(id int not null auto ...

  7. json.loads() json解码

    有些json数据里面套着json    一次json.loads()后还是会有数据是json格式 { "result": { "error_code": 0, ...

  8. 全网最新方法:win10下如何安装和配置64位JDK-13

    1.下载JDK-13 下载链接:https://www.oracle.com/technetwork/java/javase/downloads/index.html 2.安装JDK-13 双击下图的 ...

  9. 第七周第二次Scrum会议

    工作: 根据上个周对前端的布置学习,布置大家开发了相应的界面.(界面开发成果写在测试报告) 地点: 二餐二 会议照片: 忘记拍了... 核心问题: 如何编写统一风格的前端界面. 解决: 将相应资源打包 ...

  10. Leetcode146-lru-cache

    Leetcode146-lru-cache int capacity; int size; Map<Integer, ListNode> map = new HashMap<Inte ...