一、認識WebSocket
WebSockets是一種在Web應用程序中實現(xiàn)實時通信的技術(shù)。它允許客戶端和服務器之間建立持久的、雙向的通信通道,從而使得服務器可以實時向客戶端推送數(shù)據(jù),而不需要客戶端不斷地向服務器發(fā)起請求。這種實時通信的能力對于需要即時更新數(shù)據(jù)的應用程序非常有用,比如在線聊天應用、實時游戲、股票市場更新等。
在使用WebSockets時,通常需要以下步驟:
-
建立連接:客戶端向服務器發(fā)起WebSocket連接請求,服務器接受連接請求后,雙方建立WebSocket連接。
-
通信:一旦建立了連接,客戶端和服務器就可以通過該連接進行雙向通信,可以發(fā)送和接收數(shù)據(jù)。
-
處理消息:客戶端和服務器需要處理接收到的消息,并根據(jù)需要進行相應的操作。消息的格式和內(nèi)容可以根據(jù)應用程序的需求來定義。
-
關(guān)閉連接:當通信結(jié)束時,可以通過發(fā)送關(guān)閉消息來關(guān)閉WebSocket連接,釋放資源。
在實際開發(fā)中,可以使用各種現(xiàn)代Web框架和庫來簡化WebSocket的使用,例如:
- 在前端,可以使用現(xiàn)代JavaScript框架如Vue.js、React.js或Angular來處理WebSocket連接和消息傳遞。
- 在后端,常見的Web框架如Spring Boot(Java)、Express.js(Node.js)、Django(Python)等都提供了對WebSocket的支持。
要實現(xiàn)實時通信,你需要在客戶端和服務器端分別實現(xiàn)WebSocket連接的建立和消息的處理邏輯。具體的實現(xiàn)方式會根據(jù)你選擇的編程語言、框架和庫而有所不同。
二、使用WebSocket(參照若依后端SpringBoot,前端Vue.js)
1、在pom.xml中添加websocket依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2、配置匿名訪問
.antMatchers("/websocket/**").permitAll()
3、若依的websocket實現(xiàn)實時通信代碼
(1)SemaphoreUtils.java
package com.ruoyi.framework.websocket;
import java.util.concurrent.Semaphore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 信號量相關(guān)處理
*
* @author ruoyi
*/
public class SemaphoreUtils
{
/**
* SemaphoreUtils 日志控制器
*/
private static final Logger LOGGER = LoggerFactory.getLogger(SemaphoreUtils.class);
/**
* 獲取信號量
*
* @param semaphore
* @return
*/
public static boolean tryAcquire(Semaphore semaphore)
{
boolean flag = false;
try
{
flag = semaphore.tryAcquire();
}
catch (Exception e)
{
LOGGER.error("獲取信號量異常", e);
}
return flag;
}
/**
* 釋放信號量
*
* @param semaphore
*/
public static void release(Semaphore semaphore)
{
try
{
semaphore.release();
}
catch (Exception e)
{
LOGGER.error("釋放信號量異常", e);
}
}
}
(2)WebSocketConfig.java
package com.ruoyi.framework.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* websocket 配置
*
* @author ruoyi
*/
@Configuration
public class WebSocketConfig
{
@Bean
public ServerEndpointExporter serverEndpointExporter()
{
return new ServerEndpointExporter();
}
}
(3)WebSocketServer.java
package com.ruoyi.framework.websocket;
import java.util.concurrent.Semaphore;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* websocket 消息處理
*
* @author ruoyi
*/
@Component
@ServerEndpoint("/websocket/message")
public class WebSocketServer
{
/**
* WebSocketServer 日志控制器
*/
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);
/**
* 默認最多允許同時在線人數(shù)100
*/
public static int socketMaxOnlineCount = 100;
private static Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);
/**
* 連接建立成功調(diào)用的方法
*/
@OnOpen
public void onOpen(Session session) throws Exception
{
boolean semaphoreFlag = false;
// 嘗試獲取信號量
semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
if (!semaphoreFlag)
{
// 未獲取到信號量
LOGGER.error("\n 當前在線人數(shù)超過限制數(shù)- {}", socketMaxOnlineCount);
WebSocketUsers.sendMessageToUserByText(session, "當前在線人數(shù)超過限制數(shù):" + socketMaxOnlineCount);
session.close();
}
else
{
// 添加用戶
WebSocketUsers.put(session.getId(), session);
LOGGER.info("\n 建立連接 - {}", session);
LOGGER.info("\n 當前人數(shù) - {}", WebSocketUsers.getUsers().size());
WebSocketUsers.sendMessageToUserByText(session, "連接成功");
}
}
/**
* 連接關(guān)閉時處理
*/
@OnClose
public void onClose(Session session)
{
LOGGER.info("\n 關(guān)閉連接 - {}", session);
// 移除用戶
WebSocketUsers.remove(session.getId());
// 獲取到信號量則需釋放
SemaphoreUtils.release(socketSemaphore);
}
/**
* 拋出異常時處理
*/
@OnError
public void onError(Session session, Throwable exception) throws Exception
{
if (session.isOpen())
{
// 關(guān)閉連接
session.close();
}
String sessionId = session.getId();
LOGGER.info("\n 連接異常 - {}", sessionId);
LOGGER.info("\n 異常信息 - {}", exception);
// 移出用戶
WebSocketUsers.remove(sessionId);
// 獲取到信號量則需釋放
SemaphoreUtils.release(socketSemaphore);
}
/**
* 服務器接收到客戶端消息時調(diào)用的方法
*/
@OnMessage
public void onMessage(String message, Session session)
{
String msg = message.replace("你", "我").replace("嗎", "");
WebSocketUsers.sendMessageToUserByText(session, msg);
}
}
(4)WebSocketUsers.java
package com.ruoyi.framework.websocket;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* websocket 客戶端用戶集
*
* @author ruoyi
*/
public class WebSocketUsers
{
/**
* WebSocketUsers 日志控制器
*/
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketUsers.class);
/**
* 用戶集
*/
private static Map<String, Session> USERS = new ConcurrentHashMap<String, Session>();
/**
* 存儲用戶
*
* @param key 唯一鍵
* @param session 用戶信息
*/
public static void put(String key, Session session)
{
USERS.put(key, session);
}
/**
* 移除用戶
*
* @param session 用戶信息
*
* @return 移除結(jié)果
*/
public static boolean remove(Session session)
{
String key = null;
boolean flag = USERS.containsValue(session);
if (flag)
{
Set<Map.Entry<String, Session>> entries = USERS.entrySet();
for (Map.Entry<String, Session> entry : entries)
{
Session value = entry.getValue();
if (value.equals(session))
{
key = entry.getKey();
break;
}
}
}
else
{
return true;
}
return remove(key);
}
/**
* 移出用戶
*
* @param key 鍵
*/
public static boolean remove(String key)
{
LOGGER.info("\n 正在移出用戶 - {}", key);
Session remove = USERS.remove(key);
if (remove != null)
{
boolean containsValue = USERS.containsValue(remove);
LOGGER.info("\n 移出結(jié)果 - {}", containsValue ? "失敗" : "成功");
return containsValue;
}
else
{
return true;
}
}
/**
* 獲取在線用戶列表
*
* @return 返回用戶集合
*/
public static Map<String, Session> getUsers()
{
return USERS;
}
/**
* 群發(fā)消息文本消息
*
* @param message 消息內(nèi)容
*/
public static void sendMessageToUsersByText(String message)
{
Collection<Session> values = USERS.values();
for (Session value : values)
{
sendMessageToUserByText(value, message);
}
}
/**
* 發(fā)送文本消息
*
* @param userName 自己的用戶名
* @param message 消息內(nèi)容
*/
public static void sendMessageToUserByText(Session session, String message)
{
if (session != null)
{
try
{
session.getBasicRemote().sendText(message);
}
catch (IOException e)
{
LOGGER.error("\n[發(fā)送消息異常]", e);
}
}
else
{
LOGGER.info("\n[你已離線]");
}
}
}
(5)webSocket.js
/**
* 參數(shù)說明:
* webSocketURL:String webSocket服務地址 eg: ws://127.0.0.1:8088/websocket (后端接口若為restful風格可以帶參數(shù))
* callback:為帶一個參數(shù)的回調(diào)函數(shù)
* message:String 要傳遞的參數(shù)值(不是一個必要的參數(shù))
*/
export default{
// 初始化webSocket
webSocketInit(webSocketURL){ // ws://127.0.0.1:8088/websocket
this.webSocket = new WebSocket(webSocketURL);
this.webSocket.onopen = this.onOpenwellback;
this.webSocket.onmessage = this.onMessageCallback;
this.webSocket.onerror = this.onErrorCallback;
this.webSocket.onclose = this.onCloseCallback;
},
// 自定義回調(diào)函數(shù)
setOpenCallback(callback){ // 與服務端連接打開回調(diào)函數(shù)
this.webSocket.onopen = callback;
},
setMessageCallback(callback){ // 與服務端發(fā)送消息回調(diào)函數(shù)
this.webSocket.onmessage = callback;
},
setErrorCallback(callback){ // 與服務端連接異?;卣{(diào)函數(shù)
this.webSocket.onerror = callback;
},
setCloseCallback(callback){ // 與服務端連接關(guān)閉回調(diào)函數(shù)
this.webSocket.onclose = callback;
},
close(){ // 關(guān)閉連接
this.webSocket.close();
},
sendMessage(message){ // 發(fā)送消息函數(shù)
this.webSocket.send(message);
},
}
(6)index.vue
<template>
<div class="contanier" >
</div>
</template>
<script>
import webSocket from '@/utils/webSocket'
import Cookie from 'js-cookie'
export default {
name: "WebSocketTest",
data() {
return {
id: null,
infoList: {
},
webSocketObject: null,
}
},
created() {
this.createWebSocket();
},
methods: {
sendMessage() {
// 數(shù)據(jù)發(fā)生改變時給WebSocket發(fā)送消息,讓其進行廣播操作
webSocket.sendMessage("11111");
},
// 與websocket服務器創(chuàng)建連接
createWebSocket() {
if (typeof (webSocket) === "undefined") {
alert("您的瀏覽器不支持socket")
}
const TokenKey = Cookie.get("Admin-Token");
webSocket.webSocketInit('ws://127.0.0.1:8080/websocket/message' ) //初始化webSocket
// 按需進行綁定回調(diào)函數(shù)
webSocket.setOpenCallback(res => {
console.log("連接建立成功", res);
})
webSocket.setMessageCallback(res => {
if (res.data === "連接成功") {
console.log("連接成功");
return;
}
// 在此處進行數(shù)據(jù)刷新操作即可實現(xiàn)數(shù)據(jù)發(fā)生改變時實時更新數(shù)據(jù)
console.log("接收到回信", res);
console.log("接收到回信", JSON.parse(res.data));
this.infoList = JSON.parse(res.data);
})
webSocket.setErrorCallback(res => {
console.log("連接異常", res);
})
webSocket.setCloseCallback(res => {
console.log("連接關(guān)閉", res);
})
}
}
}
</script>
<style scoped>
</style>
三、實現(xiàn)
前后端同時打開:
關(guān)閉后端:
?關(guān)閉前端:
后端向前端發(fā)送信息(群發(fā)):
WebSocketUsers.sendMessageToUsersByText(JSONObject.toJSONString(list));
?后端向前端發(fā)送信息(單發(fā)):
WebSocketUsers.sendMessageToUserByText(value,JSONObject.toJSONString(list));
參考:文章來源:http://www.zghlxwxcb.cn/news/detail-861635.html
插件集成 | RuoYi文章來源地址http://www.zghlxwxcb.cn/news/detail-861635.html
到了這里,關(guān)于SpringBoot(java)實現(xiàn)websocket實現(xiàn)實時通信的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!