簡(jiǎn)介
WebSocket 是一種全雙工通信協(xié)議,用于在 Web 瀏覽器和服務(wù)器之間建立持久的連接。
- WebSocket 協(xié)議由 IETF 定為標(biāo)準(zhǔn),WebSocket API 由 W3C 定為標(biāo)準(zhǔn)。
- 一旦 Web 客戶端與服務(wù)器建立連接,之后的全部數(shù)據(jù)通信都通過這個(gè)連接進(jìn)行。
- 可以互相發(fā)送 JSON、XML、HTML 或圖片等任意格式的數(shù)據(jù)。
WebSocket 與 HTTP 協(xié)議的異同:
相同點(diǎn):
- 都是基于 TCP 的應(yīng)用層協(xié)議。
- 都使用 Request/Response 模型進(jìn)行連接的建立。
- 可以在網(wǎng)絡(luò)中傳輸數(shù)據(jù)。
不同點(diǎn):
- WebSocket 使用 HTTP 來建立連接,但定義了一系列新的 header 域,這些域在 HTTP 中并不會(huì)使用。
- WebSocket 支持持久連接,而 HTTP 協(xié)議不支持持久連接。
WebSocket 優(yōu)點(diǎn):
高效性: 允許在一條 WebSocket 連接上同時(shí)并發(fā)多個(gè)請(qǐng)求,避免了傳統(tǒng) HTTP 請(qǐng)求的多個(gè) TCP 連接。
WebSocket 的長(zhǎng)連接特性提高了效率,避免了 TCP 慢啟動(dòng)和連接握手的開銷。
節(jié)省帶寬:HTTP 協(xié)議的頭部較大,且請(qǐng)求中的大部分頭部?jī)?nèi)容是重復(fù)的。WebSocket 復(fù)用長(zhǎng)連接,避免了這一問題。
服務(wù)器推送:WebSocket 支持服務(wù)器主動(dòng)推送消息,實(shí)現(xiàn)實(shí)時(shí)消息通知。
WebSocket 缺點(diǎn):
長(zhǎng)期維護(hù)成本:服務(wù)器需要維護(hù)長(zhǎng)連接,成本較高。
瀏覽器兼容性:不同瀏覽器對(duì) WebSocket 的支持程度不一致。
受網(wǎng)絡(luò)限制:WebSocket 是長(zhǎng)連接,受網(wǎng)絡(luò)限制較大,需要處理好重連。
WebSocket 應(yīng)用場(chǎng)景:
- 實(shí)時(shí)通信領(lǐng)域:
- 社交聊天彈幕
- 多玩家游戲
- 協(xié)同編輯
- 股票基金實(shí)時(shí)報(bào)價(jià)
- 體育實(shí)況更新
- 視頻會(huì)議/聊天
- 基于位置的應(yīng)用
- 在線教育
- 智能家居等需要高實(shí)時(shí)性的場(chǎng)景。
一、后端代碼
1、安裝核心jar包: spring-boot-starter-websocket
<dependencies>
<!-- SpringBoot Websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.1.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.22</version>
</dependency>
</dependencies>
2. 來一個(gè)配置類注入
package com.codeSE.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig2 {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
3. 寫個(gè)基礎(chǔ)webSocket服務(wù)
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
//import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
/**
* @ClassName: 開啟WebSocket支持
*/
@ServerEndpoint("/dev-api/websocket/{userId}")
@Component
public class WebSocketServer {
static Log log = LogFactory.get(WebSocketServer.class);
/**
* 靜態(tài)變量,用來記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計(jì)成線程安全的。
*/
private static int onlineCount = 0;
/**
* concurrent包的線程安全Set,用來存放每個(gè)客戶端對(duì)應(yīng)的MyWebSocket對(duì)象。
*/
private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
/**
* 與某個(gè)客戶端的連接會(huì)話,需要通過它來給客戶端發(fā)送數(shù)據(jù)
*/
private Session session;
/**
* 接收userId
*/
private String userId = "";
/**
* 連接建立成功調(diào)用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.session = session;
this.userId = userId;
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
webSocketMap.put(userId, this);
//加入set中
} else {
webSocketMap.put(userId, this);
//加入set中
addOnlineCount();
//在線數(shù)加1
}
log.info("用戶連接:" + userId + ",當(dāng)前在線人數(shù)為:" + getOnlineCount());
try {
sendMessage("連接成功");
} catch (IOException e) {
log.error("用戶:" + userId + ",網(wǎng)絡(luò)異常!!!!!!");
}
}
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose() {
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
//從set中刪除
subOnlineCount();
}
log.info("用戶退出:" + userId + ",當(dāng)前在線人數(shù)為:" + getOnlineCount());
}
/**
* 收到客戶端消息后調(diào)用的方法
*
* @param message 客戶端發(fā)送過來的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("用戶消息:" + userId + ",報(bào)文:" + message);
//可以群發(fā)消息
//消息保存到數(shù)據(jù)庫、redis
if (! StringUtils.isEmpty(message)) {
try {
//解析發(fā)送的報(bào)文
JSONObject jsonObject = JSON.parseObject(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("用戶錯(cuò)誤:" + this.userId + ",原因:" + error.getMessage());
error.printStackTrace();
}
/**
* 實(shí)現(xiàn)服務(wù)器主動(dòng)推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 實(shí)現(xiàn)服務(wù)器主動(dòng)推送
*/
public static void sendAllMessage(String message) throws IOException {
ConcurrentHashMap.KeySetView<String, WebSocketServer> userIds = webSocketMap.keySet();
for (String userId : userIds) {
WebSocketServer webSocketServer = webSocketMap.get(userId);
webSocketServer.session.getBasicRemote().sendText(message);
System.out.println("webSocket實(shí)現(xiàn)服務(wù)器主動(dòng)推送成功userIds====" + userIds);
}
}
/**
* 發(fā)送自定義消息
*/
public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
log.info("發(fā)送消息到:" + userId + ",報(bào)文:" + message);
if (!StringUtils.isEmpty(message) && webSocketMap.containsKey(userId)) {
webSocketMap.get(userId).sendMessage(message);
} else {
log.error("用戶" + userId + ",不在線!");
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
4. 寫一個(gè)測(cè)試類,定時(shí)向客戶端推送數(shù)據(jù)或者可以發(fā)起請(qǐng)求推送
package com.codeSE.controller;
import com.alibaba.fastjson2.JSONObject;
import com.codeSE.config.WebSocketServer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/money")
public class Test {
//設(shè)置定時(shí)十秒一次
@Scheduled(cron = "0/10 * * * * ?")
@PostMapping("/send")
public String sendMessage() throws Exception {
Map<String,Object> map = new HashMap<>();
// 獲取當(dāng)前日期和時(shí)間
LocalDateTime nowDateTime = LocalDateTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(dateTimeFormatter.format(nowDateTime));
map.put("server_time",dateTimeFormatter.format(nowDateTime));
map.put("server_code","200");
map.put("server_message","這是服務(wù)器推送到客戶端的消息哦!!");
JSONObject jsonObject = new JSONObject(map);
WebSocketServer.sendAllMessage(jsonObject.toString());
return jsonObject.toString();
}
}
5. 啟動(dòng)springboot
package com.codeSE;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling //定時(shí)任務(wù)
@ServletComponentScan //webSocket
@SpringBootApplication
public class WebSocketAppMain {
public static void main(String[] args) {
SpringApplication.run(WebSocketAppMain.class);
}
}
使用網(wǎng)上的測(cè)試工具試一下:http://coolaf.com/tool/chattest 或者h(yuǎn)ttp://www.jsons.cn/websocket/
效果如下:
二、前端代碼
使用vue3和原生websocket
1、簡(jiǎn)單寫一個(gè)websocket的公共類
需求:commentUtil/WebsocketTool.js文章來源:http://www.zghlxwxcb.cn/news/detail-840742.html
//需求:在JavaScript中實(shí)現(xiàn)WebSocket連接失敗后3分鐘內(nèi)嘗試重連3次的功能,你可以設(shè)置一個(gè)重連策略,
// 包括重連的間隔時(shí)間、嘗試次數(shù)以及總時(shí)間限制。
/**
* @param {string} url Url to connect
* @param {number} maxReconnectAttempts Maximum number of times
* @param {number} reconnect Timeout
* @param {number} reconnectTimeout Timeout
*
*/
class WebSocketReconnect {
constructor(url, maxReconnectAttempts = 3, reconnectInterval = 20000, maxReconnectTime = 180000) {
this.url = url
this.maxReconnectAttempts = maxReconnectAttempts
this.reconnectInterval = reconnectInterval
this.maxReconnectTime = maxReconnectTime
this.reconnectCount = 0
this.reconnectTimeout = null
this.startTime = null
this.socket = null
this.connect()
}
//連接操作
connect() {
console.log('connecting...')
this.socket = new WebSocket(this.url)
//連接成功建立的回調(diào)方法
this.socket.onopen = () => {
console.log('WebSocket Connection Opened!')
this.clearReconnectTimeout()
this.reconnectCount = 0
}
//連接關(guān)閉的回調(diào)方法
this.socket.onclose = (event) => {
console.log('WebSocket Connection Closed:', event)
this.handleClose()
}
//連接發(fā)生錯(cuò)誤的回調(diào)方法
this.socket.onerror = (error) => {
console.error('WebSocket Connection Error:', error)
this.handleClose() //重連
}
}
//斷線重連操作
handleClose() {
if (this.reconnectCount < this.maxReconnectAttempts && (this.startTime === null ||
Date.now() - this.startTime < this.maxReconnectTime)) {
this.reconnectCount++
console.log(`正在嘗試重連 (${this.reconnectCount}/${this.maxReconnectAttempts})次...`)
this.reconnectTimeout = setTimeout(() => {
this.connect()
}, this.reconnectInterval)
if (this.startTime === null) {
this.startTime = Date.now()
}
} else {
console.log('超過最大重連次數(shù)或重連時(shí)間超時(shí),已放棄連接!Max reconnect attempts reached or exceeded max reconnect time. Giving up.')
this.reconnectCount = 0 // 重置連接次數(shù)0
this.startTime = null // 重置開始時(shí)間
}
}
//清除重連定時(shí)器
clearReconnectTimeout() {
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout)
this.reconnectTimeout = null
}
}
//關(guān)閉連接
close() {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
this.socket.close()
}
this.clearReconnectTimeout()
this.reconnectCount = 0
this.startTime = null
}
}
// WebSocketReconnect 類封裝了WebSocket的連接、重連邏輯。
// maxReconnectAttempts 是最大重連嘗試次數(shù)。
// reconnectInterval 是每次重連嘗試之間的間隔時(shí)間。
// maxReconnectTime 是總的重連時(shí)間限制,超過這個(gè)時(shí)間后不再嘗試重連。
// reconnectCount 用于記錄已經(jīng)嘗試的重連次數(shù)。
// startTime 用于記錄開始重連的時(shí)間。
// connect 方法用于建立WebSocket連接,并設(shè)置相應(yīng)的事件監(jiān)聽器。
// handleClose 方法在WebSocket連接關(guān)閉或發(fā)生錯(cuò)誤時(shí)被調(diào)用,根據(jù)條件決定是否嘗試重連。
// clearReconnectTimeout 方法用于清除之前設(shè)置的重連定時(shí)器。
// close 方法用于關(guān)閉WebSocket連接,并清除重連相關(guān)的狀態(tài)。
// 使用示例
// const webSocketReconnect = new WebSocketReconnect('ws://your-websocket-url')
// 當(dāng)不再需要WebSocket連接時(shí),可以調(diào)用close方法
// webSocketReconnect.close();
export default WebSocketReconnect
2、在任意Vue頁面
<template>
<div>
<el-input v-model="textarea1" :rows="5" type="textarea" placeholder="請(qǐng)輸入" />
</div>
</template>
<script setup>
import { ref, reactive,, onMounted, onUnmounted } from 'vue'
import WebSocketReconnect from '@/commentUtil/WebsocketTool'
// --------------------------------------------
let textarea1 = ref('【消息】---->')
let websocket = null
//判斷當(dāng)前瀏覽器是否支持WebSocket
if ('WebSocket' in window) {
//連接WebSocket節(jié)點(diǎn)
websocket = new WebSocketReconnect('ws://127.0.0.1:8080' + '/dev-api/websocket/1122334455')
} else {
alert('瀏覽器不支持webSocket')
}
//接收到消息的回調(diào)方法
websocket.socket.onmessage = function (event) {
let data = event.data
console.log('后端傳遞的數(shù)據(jù):' + data)
//將后端傳遞的數(shù)據(jù)渲染至頁面
textarea1.value = textarea1.value + data + '\n' + '【消息】---->'
}
//監(jiān)聽窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時(shí),主動(dòng)去關(guān)閉websocket連接,防止連接還沒斷開就關(guān)閉窗口,server端會(huì)拋異常。
window.onbeforeunload = function () {
websocket.close()
}
//關(guān)閉連接
function closeWebSocket() {
websocket.close()
}
//發(fā)送消息
function send() {
websocket.socket.send({ kk: 123 })
}
//------------------------------------
</script>
<style scoped>
</style>
效果:文章來源地址http://www.zghlxwxcb.cn/news/detail-840742.html
到了這里,關(guān)于websocket 實(shí)現(xiàn)后端主動(dòng)前端推送數(shù)據(jù)、及時(shí)通訊(vue3 + springboot)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!