WebSocket——SpringBoot+Vue3+TS+SockJS+STOMP简单连接使用
- 本文视频以及相关资源
- 关于WebSocket
- 文档
- 什么时候使用WebSocket
- WebSocket连接头
- 服务器返回状态码
- 客户端
- 使用技术
- Github地址
- npm安装
- 为什么要安装sockjs的.d.ts文件
- 常用方法
- 1.连接
- 2.关闭连接
- 3.发送消息
- 4.设置订阅
- 构建
- 1.创建webSocket.ts
- 2.完整构建
- 3.页面逻辑
- 服务端
- 技术
- 文档地址
- 构建
- 1.引入依赖
- 2.构建WebSocketConfig
- 解释
- 3.构建两个实体类
- Greeting
- Hello
- 4.设置yaml
- 5.构建web控制器
- 结果展示
本文视频以及相关资源
视频链接
前端Vue3标准化模板
Spring官方案例
关于WebSocket
WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范。WebSocket API也被W3C定为标准。
WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
文档
https://docs.spring.io/spring-framework/docs/5.3.24/reference/html/web.html#websocket
什么时候使用WebSocket
延迟本身不是决定因素。如果消息量相对较低(例如,监视网络故障),HTTP流或轮询可以提供有效的解决方案。
低延迟、高频率和高容量的组合,是使用WebSocket的最佳选择。
WebSocket连接头
GET /spring-websocket-portfolio/portfolio HTTP/1.1
Host: localhost:8080
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: Uc9l9TMkWGbHFD2qnFHltg==
Sec-WebSocket-Protocol: v10.stomp, v11.stomp
Sec-WebSocket-Version: 13
Origin: http://localhost:8080
服务器返回状态码
具有WebSocket支持的服务器返回类似于以下内容的输出,而不是通常的200状态代码
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: 1qVdfYHU9hPOl4JYYNXF623Gzn0=
Sec-WebSocket-Protocol: v10.stomp
客户端
使用技术
- SocketJS
- StompJS
- Vue3
- TypeScript
- Setup语法
Github地址
https://github.com/sockjs/sockjs-client
https://github.com/jmesnil/stomp-websocket
npm安装
npm install sockjs-client@1.6.1
//安装sockjs的.d.ts文件
npm i --save-dev @types/sockjs-client
//安装stomp
npm install stompjs
npm i --save-dev @types/stompjs
npm i net -S
为什么要安装sockjs的.d.ts文件
我们使用的ts代替了js,在ts中直接引入使用js是不能被识别的,这时候就需要有一个.d.ts的声明文件,显然原始的SockJS库中并没有这个文件,所以我们需要自己去下载一个,当然你要是厉害可以自己写一个。
不然在ts中会报找不到SockJS模块的错误
常用方法
1.连接
connect(headers: { login: string, passcode: string, host?: string | undefined }, connectCallback: (frame?: Frame) => any, errorCallback?: (error: Frame | string) => any): any;
connect(headers: { }, connectCallback: (frame?: Frame) => any, errorCallback?: (error: Frame | string) => any): any;
connect(login: string, passcode: string, connectCallback: (frame?: Frame) => any, errorCallback?: (error: Frame | string) => any, host?: string): any;
2.关闭连接
disconnect(disconnectCallback: () => any, headers?: {}): any;
3.发送消息
send(destination: string, headers?: {}, body?: string): any;
4.设置订阅
subscribe(destination: string, callback?: (message: Message) => any, headers?: {}): Subscription;
构建
1.创建webSocket.ts
//引入使用SockJS
import SockJS from "sockjs-client";
import Stomp from "stompjs";
2.完整构建
//引入使用SockJS
import SockJS from "sockjs-client";
import Stomp from "stompjs";
//请求地址
const baseUrl = "http://localhost:9000/port";
//请求头
const header = {};
//stomp客户端
let stompClient: Stomp.Client;
//连接状态
let connetStatus = false;
/**
* 初始化连接
*/
export const initSocket = () => {
con();
setInterval(() => {
//根据连接状态
if (connetStatus) {
try {
//发送请求
stompClient.send(
"/app/hello",
header,
JSON.stringify({ name: "wangau" })
);
} catch (error) {
con();
}
}
}, 10000);
};
/**
* 连接
*/
export const con = () => {
let socket = new SockJS(baseUrl);
stompClient = Stomp.over(socket);
let header = {};
stompClient.connect(
header,
() => {
console.log("===========connect success===========");
connetStatus = true;
//设置订阅
stompClient.subscribe(
"/topic/greetings",
(res: any) => {
console.log(res);
},
header
);
},
(err: any) => {
console.log("error");
console.log(err);
}
);
};
/**
* 断开
*/
export const close = () => {
if (stompClient) {
stompClient.disconnect(() => {
console.log("============connect release============");
connetStatus = false;
});
}
};
3.页面逻辑
<template>
<div id="index_container">
<!-- 使用图标库示例 -->
<i class="iconfont icon-smile-fill "></i>
<el-button type="primary" @click="closeCon">关闭</el-button>
</div>
</template>
<script lang="ts" setup>
import { initSocket, close } from '@/request/webSocket/webSocket'
import { ref, reactive, onMounted } from 'vue'
const closeCon = () => {
close()
}
onMounted(() => {
initSocket()
})
</script>
<style lang="scss" scoped>
@use './Index.scss';
#index_container {
height: 100vh;
width: 100vw;
}
</style>
服务端
技术
- spring-boot-starter-websocket
- SpringBoot2.7.6
- STOMP
文档地址
https://docs.spring.io/spring-framework/docs/5.3.24/reference/html/web.html#websocket-stomp
构建
1.引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.构建WebSocketConfig
package com.example.stomp.config;
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;
/**
* @author Syf200208161018
* @date 2022/12/11 11:11
* @ClassName:WebSocketConfig
* @Effect:WebSocketConfig is used for
* /port是WebSocket(或SockJS)指向的端点的HTTP URL
* 客户端需要连接以进行WebSocket握手。
* 目标标头以/app开头的STOMP消息被路由到
* @Controller类中的MessageMapping方法。
* 使用内置的消息代理进行订阅和广播
* 将目标标头以/topic或/queue开头的消息路由到代理。
*/
@EnableWebSocketMessageBroker
@Configuration
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/port").setAllowedOriginPatterns("*").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/app");
registry.enableSimpleBroker("/topic","/queue");
}
}
解释
使用@EnableWebSocketMessageBroker
开启WebSocket的子协议STOMP,配置类需要实现WebSocketMessageBrokerConfigurer
接口,重写其中的注册STOMP节点方法和配置信息代理者方法
在注册STOMP节点方法中我们需要:
- 添加监听节点
addEndpoint
- 设置跨域
setAllowedOriginPatterns
- 设置使用SockJS
withSockJS
(你也可以选择使用原生方式)
配置信息代理者中需要:
- 设置目的地前缀
setApplicationDestinationPrefixes
- 设置代理者(代理者对应订阅者)
3.构建两个实体类
Greeting
package com.example.stomp.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @author Syf200208161018
* @date 2022/12/11 14:10
* @ClassName:Greeting
* @Effect:Greeting is used for
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Greeting implements Serializable {
private String content;
}
Hello
package com.example.stomp.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @author Syf200208161018
* @date 2022/12/11 14:10
* @ClassName:Hello
* @Effect:Hello is used for
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Hello implements Serializable {
private String name;
}
4.设置yaml
server:
port: 9000
5.构建web控制器
package com.example.stomp.controller;
import com.example.stomp.entity.Greeting;
import com.example.stomp.entity.Hello;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Syf200208161018
* @date 2022/12/11 14:11
* @ClassName:TestController
* @Effect:TestController is used for
*/
@RestController
public class TestController {
// @MessageMapping("/hello")
// @SendTo("/topic/greetings")
// public Greeting greeting(){
// return new Greeting("hello!");
// }
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(Hello hello){
return new Greeting(hello.getName());
}
}
结果展示