SpringBoot 使用WebSocket功能(實(shí)現(xiàn)步驟)
實(shí)現(xiàn)步驟:
1.導(dǎo)入WebSocket坐標(biāo)。
在pom.xml中增加依賴項(xiàng):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
2.編寫WebSocket配置類,用于注冊(cè)WebSocket的Bean。
package com.rc114.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* WebSocket配置類,用于注冊(cè)WebSocket的Bean
* @author Administrator
*/
@Configuration
public class WebSocketConfiguration {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}3.編寫WebSocketServer類。
package com.rc114.websocket;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* WebSocket服務(wù)
* @author Administrator
*/
@Component // 交給spring容器管理
@ServerEndpoint("/ws/{sid}") // 路徑請(qǐng)求
public class WebSocketServer {
//存放會(huì)話對(duì)象
private static Map<String, Session> sessionMap = new HashMap();
/**
* 連接建立成功調(diào)用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("sid") String sid) {
System.out.println("客戶端:" + sid + "建立連接");
sessionMap.put(sid, session);
}
/**
* 收到客戶端消息后調(diào)用的方法
*
* @param message 客戶端發(fā)送過來的消息
*/
@OnMessage
public void onMessage(String message, @PathParam("sid") String sid) {
System.out.println("收到來自客戶端:" + sid + "的信息:" + message);
}
/**
* 連接關(guān)閉調(diào)用的方法
*
* @param sid
*/
@OnClose
public void onClose(@PathParam("sid") String sid) {
System.out.println("連接斷開:" + sid);
sessionMap.remove(sid);
}
/**
* 群發(fā)
*
* @param message
*/
public void sendToAllClient(String message) {
Collection<Session> sessions = sessionMap.values();
for (Session session : sessions) {
try {
//服務(wù)器向客戶端發(fā)送消息
session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}4.測(cè)試WebSocket
編寫一個(gè)測(cè)試WebSocket的html頁面:
<html>
<head>
<title>WebSocket測(cè)試頁面</title>
<style type="text/css">
* {
font-size: 14px;
line-height: 22px;
}
.main {
border: 0px solid #ccc;
width: 60%;
margin: 0 auto;
padding: 10px;
}
.main-table {
width: 100%;
border: 1px solid #ccc;
border-collapse: collapse;
}
.main-table td {
border: 1px solid #ccc;
padding: 5px;
}
.td-left {
text-align: right;
}
input[type="text"] {
border: 1px solid #ccc;
padding: 5px;
outline: none;
width: 200px;
}
input[type="button"] {
border: 1px solid #ccc;
padding: 3px 10px;
outline: none;
}
.green {
color: green;
}
.red {
color: red;
}
#msg {
font-size: 12px;
line-height: 22px;
}
</style>
</head>
<body>
<div class="main">
<table class="main-table">
<tr>
<td colspan="2" style=" text-align: center;font-weight: bold;">WebSocket測(cè)試</td>
</tr>
<tr>
<td style="width: 100px;" class="td-left">服務(wù)器地址</td>
<td><input type="text" id="server" value="ws://localhost:8080/ws/"></td>
</tr>
<tr>
<td class="td-left">客戶端名稱</td>
<td><input type="text" id="clientId">
<input type="button" value="隨機(jī)生成" onclick="GenerateClientId()" />
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="button" value="連接" onclick="ConnectServer()" />
</td>
</tr>
<tr>
<td class="td-left">連接狀態(tài)</td>
<td> <span id="status"><span class='red'>未連接</span></span></td>
</tr>
<tr>
<td class="td-left">發(fā)送消息</td>
<td>
<input type="text" id="txt">
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="button" value="發(fā)送" onclick="SendMsg()" />
<input type="button" value="清空" onclick="ClearLog()" />
</td>
</tr>
<tr>
<td class="td-left">日志</td>
<td>
<div id="msg"></div>
</td>
</tr>
</table>
<script type="text/javascript">
var websocket = null;
var clientId = "";
//隨機(jī)生成客戶端編號(hào)
function GenerateClientId() {
clientId = Math.random().toString().substr(2);
document.getElementById("clientId").value = clientId;
}
GenerateClientId();
//連接到服務(wù)器
function ConnectServer() {
var clientId = document.getElementById("clientId").value;
if (clientId == "") {
alert("客戶端編號(hào)不能為空!");
} else {
if ("WebSocket" in window) {
websocket = new WebSocket("ws://localhost:8080/ws/" + clientId);
websocket.onerror = function () {
ShowMsg("<span class='red'>ERROR</span>");
}
websocket.onopen = function () {
document.getElementById("status").innerHTML = "<span class='green'>已連接</span>";
ShowMsg("<span class='green'>連接成功!</span>");
}
websocket.onmessage = function (event) {
ShowMsg(event.data);
}
websocket.onclose = function () {
ShowMsg("<span class='red'>斷開連接</span>");
}
}
else {
alert("NOT SUPPORT WEBSOCKET!");
}
}
}
//網(wǎng)頁關(guān)閉時(shí),斷開鏈接
window.onbeforeunload = function () {
websocket.close();
}
//顯示日志
function ShowMsg(msg) {
document.getElementById("msg").innerHTML += Now() + " " + msg + "<br/>";
}
//發(fā)送消息
function SendMsg() {
var txt = document.getElementById("txt").value;
websocket.send(txt);
ShowMsg("<span class='green'>發(fā)送消息:" + txt + "</span>");
}
//斷開鏈接
function closeWebSocket() {
websocket.close();
}
function Now() {
const date = new Date();
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const hour = date.getHours().toString().padStart(2, '0');
const minute = date.getMinutes().toString().padStart(2, '0');
const second = date.getSeconds().toString().padStart(2, '0');
const format = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
return format;
}
//清空日志
function ClearLog() {
document.getElementById("msg").innerHTML = "";
}
</script>
</div>
</body>
</html>運(yùn)行效果:


注意:
如果使用了Nginx轉(zhuǎn)發(fā)請(qǐng)求的,需在Nginx配置WebSocket的轉(zhuǎn)發(fā)規(guī)則。
到此這篇關(guān)于SpringBoot 使用WebSocket功能的文章就介紹到這了,更多相關(guān)SpringBoot 使用WebSocket內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot部署到外部Tomcat無法注冊(cè)到Nacos服務(wù)端的解決思路
這篇文章主要介紹了SpringBoot部署到外部Tomcat無法注冊(cè)到Nacos服務(wù)端,本文給大家分享完美解決思路,結(jié)合實(shí)例代碼給大家講解的非常詳細(xì),需要的朋友可以參考下2023-03-03
Java調(diào)用Shell命令和腳本的實(shí)現(xiàn)
這篇文章主要介紹了Java調(diào)用Shell命令和腳本的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
java反射之Method的invoke方法實(shí)現(xiàn)教程詳解
這篇文章主要給大家介紹了關(guān)于java反射之Method的invoke方法的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
springboot項(xiàng)目如何設(shè)置時(shí)區(qū)
這篇文章主要介紹了springboot項(xiàng)目如何設(shè)置時(shí)區(qū)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
RestTemplate Get請(qǐng)求實(shí)現(xiàn)bean參數(shù)傳遞詳解
RestTemplate 是從 Spring3.0 開始支持的一個(gè) HTTP 請(qǐng)求工具,也有的稱之為網(wǎng)絡(luò)框架,說白了就是Java版本的一個(gè)postman,這篇文章主要介紹了詳解RestTemplate 用法,需要的朋友可以參考下2022-11-11
MyBatis 動(dòng)態(tài)SQL之where標(biāo)簽的使用
本文主要介紹了MyBatis 動(dòng)態(tài)SQL之where標(biāo)簽,where 標(biāo)簽主要用來簡(jiǎn)化 SQL 語句中的條件判斷,可以自動(dòng)處理 AND/OR 條件,下面就來具體介紹一下2024-01-01

