【IT老齊238】十分鐘上手WebSocket全雙工通信協(xié)議_嗶哩嗶哩_bilibili【IT老齊238】十分鐘上手WebSocket全雙工通信協(xié)議, 視頻播放量 8348、彈幕量 23、點贊數(shù) 318、投硬幣枚數(shù) 157、收藏人數(shù) 257、轉(zhuǎn)發(fā)人數(shù) 30, 視頻作者 IT老齊, 作者簡介 老齊的個人V: itlaoqi001 ~~歡迎前來交流,相關(guān)視頻:基于redis訂閱消息和websocket技術(shù)實現(xiàn)的消息推送功能,【websocket】【前端】保證前端實時性的技術(shù):websocket,43 Spring Boot整合WebSocket詳解,SpringBoot WebSocket Echarts 服務(wù)器實時向客戶端推送數(shù)據(jù),12分鐘搞定基于websocket,springboot,vue的簡單聊天室。,WebFlux如何使用SSE做服務(wù)端的定向推送,springboot快速接入webSocket(心跳連接)- RuoYi-Vue-Plus系列教程,SpringBoot系列-Websocket 實時聊天,socket和websocket有什么區(qū)別?,【W(wǎng)ebSocket通信】網(wǎng)絡(luò)聊天室在線聊天系統(tǒng)___搭建自己的即時聊天室 WebSocket+Vue網(wǎng)絡(luò)聊天室在線聊天系統(tǒng)畢業(yè)源碼案例設(shè)計https://www.bilibili.com/video/BV1Kd4y1w7JR/?spm_id_from=333.337.search-card.all.click&vd_source=3b2d00a63e8d4ae7dea36274e5447a45
一、后端pom.xml引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
二、啟動類注入Bean
@SpringBootApplication
public class TtSdemoApplication {
public static void main(String[] args) {
SpringApplication.run(TtSdemoApplication.class, args);
}
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
三、編寫WebSocket類
package com.zj.ttsdemo.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
/**
* Created by
*
* @Author: JoyceZhang
* @Date: 2023/05/25/15:28
* @Description:
*/
@Slf4j
@ServerEndpoint(value="/websocket")
@Component
public class Websocket {
private static Session[] sessionContainer = new Session[2];
/**
* A,B與服務(wù)器建立連接
*/
@OnOpen
public void onOpen(Session session) {
if (sessionContainer[0] == null && sessionContainer[1] == null) {
sessionContainer[0] = session;
log.info("a連接成功");
} else if (sessionContainer[0] != null && sessionContainer[1] == null) {
sessionContainer[1] = session;
log.info("b連接成功");
} else {
log.info("連接失敗");
}
}
/**
* 鏈接關(guān)閉
*/
@OnClose
public void onClose(Session session) {
for(int i=0;i<sessionContainer.length;i++){
if(sessionContainer[i] == session){
sessionContainer[i] = null;
log.info((i==0?"a":"b")+"斷開連接");
}
}
}
/**
* 得到另一個session對象
*/
private Session getOtherSession(Session session) {
for(int i = 0; i<sessionContainer.length;i++){
if(session == sessionContainer[i]){
log.info("獲取到另一個session");
return sessionContainer[(i==0?1:0)];
}
}
return null;
}
/**
* 向另一個session發(fā)送消息
*/
@OnMessage
public void sendMessage(String message,Session session) throws IOException{
Session otherSession = this.getOtherSession(session);
log.info("發(fā)送消息"+message+"到"+(otherSession==sessionContainer[0]?"a":"b"));
otherSession.getBasicRemote().sendText(message);
}
/**
* 異常處理
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("發(fā)生錯誤");
error.printStackTrace();
}
}
四、編寫測試頁面
在resource/static目錄下編寫chat.html文章來源:http://www.zghlxwxcb.cn/news/detail-462888.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input id = "text" type ="text">
<button onclick = "send()">Send</button>
<button onclick = "closeWebSocket()">Close</button>
<div id = "message"></div>
</body>
<script type="text/javascript">
var websocket = null;
//判斷當(dāng)前瀏覽器是否支持WebSocket
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8083/websocket");
}
else{
alert('Not support websocket')
}
//連接發(fā)生錯誤的回調(diào)方法
websocket.onerror = function(){
setMessageInnerHTML("服務(wù)器通信故障");
};
//連接成功建立的回調(diào)方法
websocket.onopen = function(event){
setMessageInnerHTML("與服務(wù)器通信成功");
}
//接收到消息的回調(diào)方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//連接關(guān)閉的回調(diào)方法
websocket.onclose = function(){
setMessageInnerHTML("WebSocket連接關(guān)閉");
}
//監(jiān)聽窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時,主動去關(guān)閉websocket連接,防止連接還沒斷開就關(guān)閉窗口,server端會拋異常。
window.onbeforeunload = function(){
websocket.close();
}
//將消息顯示在網(wǎng)頁上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//關(guān)閉連接
function closeWebSocket(){
websocket.close();
}
//發(fā)送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
五、通信測試
文章來源地址http://www.zghlxwxcb.cn/news/detail-462888.html
到了這里,關(guān)于WebSocket全雙工通信SpringBoot實現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!