maven項目使用netty,前端是vue2,實現通訊

引入的java包

<!--        以下是即時通訊--><!-- Netty core modules  --><dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.76.Final</version> <!-- 使用最新的穩定版本 --></dependency><!-- Optional: Support for WebSocket --><dependency><groupId>io.netty</groupId><artifactId>netty-handler-proxy</artifactId><version>4.1.76.Final</version></dependency><!-- Optional: Support for HTTP/2 --><dependency><groupId>io.netty</groupId><artifactId>netty-resolver-dns-native-macos</artifactId><version>4.1.76.Final</version><classifier>osx-x86_64</classifier><optional>true</optional></dependency>

2.創建project對象(這個對象是跟業務相關的,如果業務簡單,不創建也可以,最后傳輸的都是字符串)

@Getter
@Setter
public class Project {private GroupStudentService groupStudentService;private Integer schoolId;  //學校idprivate Integer projectId;  //項目idprivate Integer leafId;  //小節idprivate Integer leafTypeId;  //小節類型private Integer chapterId;  //章節idprivate Object currentLeaf;//當前小節private  Integer currentLeafIndex;//當前小節的下標private  Integer currentChapterIndex;//當前章節的下標public Project(Integer projectId,Integer leafId,Integer leafTypeId,Integer chapterId,Object currentLeaf,Integer currentLeafIndex,Integer currentChapterIndex,Integer schoolId) {this.projectId = projectId;this.leafId = leafId;this.leafTypeId = leafTypeId;this.chapterId = chapterId;this.currentLeaf = currentLeaf;this.currentLeafIndex = currentLeafIndex;this.currentChapterIndex = currentChapterIndex;this.schoolId= schoolId;}public Project() {}

3.創建WebsocketHandler

public class WebsocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {// 定義一個全局變量用來保存所有連接的客戶端Channelprivate static final Set<Channel> connectedChannels = Collections.newSetFromMap(new ConcurrentHashMap<>());// 當有新的連接時,將Channel添加到集合中public void handlerAdded(ChannelHandlerContext ctx) {connectedChannels.add(ctx.channel());}// 當連接關閉時,從集合中移除該Channelpublic void handlerRemoved(ChannelHandlerContext ctx) {connectedChannels.remove(ctx.channel());}@Overrideprotected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {String text = msg.text();String prefix = text.substring(0, 7); //截取前綴if (prefix.contains("switch")) {//當前數據是切換小節handleSwitch(text.substring(7));} else if (prefix.contains("xsData")) {//當前數據是學生提交作業給老師的handleStudentData(text.substring(7));}}//這個是專門用來切換小節的,老師切換上一節,下一節,跳到指定小節,學生的大屏頁面也跟著切換private void handleSwitch(String parts) {//把parts轉成jsonobject對象JSONObject jsonObject = JSON.parseObject(parts);Integer projectId = (int) jsonObject.get("projectId");Integer leafId = (int) jsonObject.get("leafId");Integer leafTypeId = (int) jsonObject.get("leafTypeId");Integer chapterId = (int) jsonObject.get("chapterId");Integer currentLeafIndex = (int) jsonObject.get("currentLeafIndex");Integer currentChapterIndex = (int) jsonObject.get("currentChapterIndex");Object currentLeaf = jsonObject.get("currentLeaf");Integer schoolId = (int) jsonObject.get("institutionId");Project project = new Project(projectId,leafId,leafTypeId,chapterId,currentLeaf,currentLeafIndex,currentChapterIndex, schoolId);Gson gson = new Gson();String jsonProject = gson.toJson(project);if (project != null) {for (Channel channel : connectedChannels) {if (channel.isActive()) { // 檢查通道是否仍然活躍channel.writeAndFlush(new TextWebSocketFrame("switch:" + jsonProject));}}}}//這個是專門用來學生提交數據的,學生提交數據,老師大屏上能展示數據private void handleStudentData(String parts) {//把parts轉成jsonobject對象JSONObject jsonObject = JSON.parseObject(parts);Integer projectId =Integer.valueOf(jsonObject.get("projectId").toString());Integer leafId = Integer.valueOf(jsonObject.get("leafId").toString());Integer schoolId = Integer.valueOf( jsonObject.get("institutionId").toString());Project project = new Project();project.setProjectId(projectId);project.setSchoolId(schoolId);project.setLeafId(leafId);Gson gson = new Gson();String jsonProject = gson.toJson(project);if (project != null) {for (Channel channel : connectedChannels) {if (channel.isActive()) { // 檢查通道是否仍然活躍channel.writeAndFlush(new TextWebSocketFrame("xsData:" + jsonProject));}}}}

4.創建WebsocketServer啟動類

public class WebsocketServer {public static void main(String[] args) throws InterruptedException {initWebsocket();}public static void initWebsocket() throws InterruptedException {EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) {System.out.println("初始化WebsocketServer");ChannelPipeline p = ch.pipeline();p.addLast(new HttpServerCodec());p.addLast(new HttpObjectAggregator(65536));p.addLast(new ChunkedWriteHandler());p.addLast(new WebSocketServerProtocolHandler("/screen"));p.addLast(new WebsocketHandler());}});ChannelFuture f = b.bind(8084).sync();f.channel().closeFuture().sync();} finally {workerGroup.shutdownGracefully();bossGroup.shutdownGracefully();}}}

5.頁面上的發送數據

connectWebSocket() {this.socket = new WebSocket('ws://' + window.location.hostname + ':8084/screen');this.socket.addEventListener('open', (event) => {console.log('WebSocket connection opened--學生');});this.socket.addEventListener('message', (event) => {console.log(event);});this.socket.addEventListener('error', (event) => {console.error('WebSocket error:', event);});this.socket.addEventListener('close', (event) => {console.log('WebSocket connection closed');});}

///--------------------------------------------------這是scoketlet sendData = {projectId: this.projectId,leafId: this.leafId,institutionId: JSON.parse(localStorage.getItem('user')).institutionId};console.log(sendData)// 將數據對象轉化為JSON字符串let jsonData = JSON.stringify(sendData);let prefixedData = 'xsData:' + jsonData;this.socket.send(prefixedData);///----------------------------------------------------------------

6.頁面上接收數據

initWebSocket() {this.socket = new WebSocket(`ws://${window.location.hostname}:8084/screen`);this.socket.addEventListener('open', (event) => {console.log('WebSocket connection opened');});this.socket.addEventListener('message', (event) => {const data = event.data;if (data.startsWith('xsData:')) {const jsonData = data.substring(7);const vo = JSON.parse(jsonData);if (vo.schoolId == JSON.parse(localStorage.getItem('user')).institutionId &&vo.projectId == this.projectId && vo.leafId == this.leafId) {this.getQd();} else {console.log("無效信息")}}});this.socket.addEventListener('error', (event) => {console.error('WebSocket error:', event);});this.socket.addEventListener('close', (event) => {console.log('WebSocket connection closed');});},

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/40955.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/40955.shtml
英文地址,請注明出處:http://en.pswp.cn/web/40955.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

C++初學者指南-4.診斷---地址檢測器

C初學者指南-4.診斷—地址檢測器 幻燈片 地址檢測器&#xff08;ASan&#xff09; 適用編譯器g,clang檢測內存錯誤 內存泄露訪問已經釋放的內存訪問不正確的堆棧區域 用額外的指令檢測代碼 運行時間增加約70%內存使用量大約增加了3倍 示例&#xff1a;檢測空指針 使用地址…

中英雙語介紹百老匯著名歌劇:《貓》(Cats)和《劇院魅影》(The Phantom of the Opera)

中文版 百老匯著名歌劇 百老匯&#xff08;Broadway&#xff09;是世界著名的劇院區&#xff0c;位于美國紐約市曼哈頓。這里匯集了許多著名的音樂劇和歌劇&#xff0c;吸引了全球各地的觀眾。以下是兩部百老匯的經典音樂劇&#xff1a;《貓》和《劇院魅影》的詳細介紹。 1.…

CP AUTOSAR標準之RAMTest(AUTOSAR_CP_SWS_RAMTest)(更新中……)

1 簡介和功能概述 AUTOSAR基礎軟件模塊“RAM測試”的功能、API和配置。 ??RAM測試是對RAM單元的物理健康狀況的測試。它不是為了測試RAM的內容。用于寄存器的RAM也經過測試。 ??在本文檔中,RAM單元被理解為內存單位,可由處理器單獨尋址。因此,對于16位處理器,單元大小(…

拉普拉斯逆變換

https://www.bilibili.com/video/BV17i4y1475Y?p21&vd_source2e6b4ba548ec9462b2f9633ff700e9b9 CV 17 陳永平教授關于拉普拉斯逆變換的式子的推導 最關鍵的兩步 想到取一個合適的contour L R L_R LR?部分是實部 γ \gamma γ要大于所有極點的實部,這樣就可以搞一個大…

SCI二區TOP|麋鹿群優化算法: 一種新穎的受自然啟發的元啟發式算法

目錄 1.背景2.算法原理2.1算法思想2.2算法過程 3.結果展示4.參考文獻5.代碼獲取 1.背景 2024年&#xff0c;SO Oladejo受到麋鹿群的繁殖過程啟發&#xff0c;提出了麋鹿群優化算法&#xff08;Elk herd optimizer, EHO&#xff09;。 2.算法原理 2.1算法思想 EHO靈感來自麋鹿…

設計外包管理辦法和步驟之HMI

設計外包流程和步驟之人機界面HMI, Human-Machine Interface 1. 源由2. 流程&步驟2.1 明確需求2.2 尋找外包公司2.3 簽訂合同2.4 項目啟動2.5 設計過程2.6 迭代開發2.7 驗收和交付2.8 維護和支持 3. 工具和平臺推薦4. 總結5. 補充 - 需求、交付、驗收5.1 需求5.2 交付5.3 驗…

C語言編程與進階

1.0 C語言關鍵字 1-1C語言關鍵字-CSDN博客文章瀏覽閱讀831次&#xff0c;點贊13次&#xff0c;收藏24次。define使用define定義常量return 0;使用define定義宏// define 定義宏&#xff0c;名字是ADD(x,y),x y 是宏的參數int a 10;int b 20;return 0;宏定義的本質是替換&am…

pandas讀取CSV格式文件生成數據發生器iteration

背景 數據集標簽為csv文件格式&#xff0c;有三個字段column_hander [‘id’, ‘boneage’, ‘male’]&#xff0c;需要自己定義數據集。文件較大&#xff0c;做一個數據發生器迭代更新數據集。 實現模板 在Pandas中&#xff0c;可以使用pandas.read_csv函數讀取CSV文件&…

ShardingSphere實戰

ShardingSphere實戰 文章目錄 ShardingSphere實戰分庫分表實戰建表建表sql利用存儲過程建表Sharding-jdbc分庫分表配置 基于業務的Sharding-key考慮訂單id用戶id分片策略訂單id的設計與實現**設計思想**&#xff1a;設計思路&#xff1a; 具體分片策略實現測試數據插入商戶商品…

推薦好玩的工具之OhMyPosh使用

解除禁止腳本 Set-ExecutionPolicy RemoteSigned 下載Oh My Posh winget install oh-my-posh 或者 Install-Module oh-my-posh -Scope AllUsers 下載Git提示 Install-Module posh-git -Scope CurrentUser 或者 Install-Module posh-git -Scope AllUser 下載命令提示 Install-Mo…

SwinUnet詳解

文章目錄 摘要一. 編碼端模塊1. PatchEmbed2. SwinTransformerBlock2.1. Window_partition2.2. WindowAttention2.3. Window_reverse2.4. MLP 3. PatchMerging 二. 解碼端模塊三. 完整流程圖 摘要 swinunet基本結構&#xff1a; swinunet采用編碼器-解碼器結構&#xff1a; 編…

5、MP4解復用---AAC+H264

MP4 MP4同樣是一種容器格式&#xff0c;是由一個一個Box組成&#xff0c;每個Box又分為Header與Data&#xff0c;Data又包含很多子Box&#xff0c;具體的MP4文件結構也看過&#xff0c;內部Box結構比較復雜&#xff0c;一般不寫MP4解釋器的話&#xff0c;Box結構不用了解太細&a…

.NET編程:C#下WinForms多語種切換的藝術

概述 在全球化的今天&#xff0c;軟件的多語言支持已成為標配。.NET中的WinForms應用程序提供了多種方式來實現多語種切換&#xff0c;讓軟件能夠跨越語言障礙&#xff0c;觸及更廣闊的用戶群體。本文將帶領大家探索C#下WinForms應用程序實現多語種切換的不同方法&#xff0c;通…

2.1 tmux和vim

文章目錄 前言概述tmuxvim總結 前言 開始學習的時間是 2024.7.6 ,13&#xff1a;47 概述 最好多使用&#xff0c;練成條件反射式的 直接使用終端的工具&#xff0c;可以連接到服務器&#xff0c;不需要使用本地的軟件 tmux 這個主要有兩個功能&#xff0c;第一個功能是分…

Linux多進程和多線程(七)進程間通信-信號量

進程間通信之信號量 資源競爭 多個進程競爭同一資源時&#xff0c;會發生資源競爭。 資源競爭會導致進程的執行出現不可預測的結果。 臨界資源 不允許同時有多個進程訪問的資源, 包括硬件資源 (CPU、內存、存儲器以及其他外 圍設備) 與軟件資源(共享代碼段、共享數據結構) …

Redis Cluster 模式 的具體實施細節是什么樣的?

概述 參考&#xff1a;What are Redis Cluster and How to setup Redis Cluster locally ? | by Rajat Pachauri | Medium Redis Cluster 的工作原理是將數據分布在多個節點上&#xff0c;同時確保高可用性和容錯能力。以下是 Redis Cluster 運行方式的簡要概述&#xff1a; …

讀書到底有什么意義?從笨小孩到名人的逆襲之路

點擊上方△騰陽 關注 作者 l 騰陽 轉載請聯系授權 讀書到底有什么意義&#xff1f; 有一個鳥語花香的農場里&#xff0c;住著老農夫和他的小孫子。 老農夫經常在清晨會坐在窗邊&#xff0c;捧著厚厚的《圣經》&#xff0c;沉浸在知識的海洋里。 小孫子問他&#xff1a;…

[終端安全]-1 總體介紹

有朋友一直在和筆者研討智駕安全這個熱門話題&#xff0c;筆者十多年工作從不離終端安全這個核心話題&#xff08;芯片安全、操作系統安全、應用安全&#xff09;&#xff0c;近來也一直在梳理終端安全體系&#xff1b;手機、汽車皆是我們生活中應用最普遍的智能終端&#xff0…

VSCode設置好看清晰的字體!中文用鴻蒙,英文用Jetbrains Mono

一、中文字體——HarmonyOS Sans SC 1、下載字體 官網地址&#xff1a;https://developer.huawei.com/consumer/cn/design/resource/ 直接下載&#xff1a;https://communityfile-drcn.op.dbankcloud.cn/FileServer/getFile/cmtyPub/011/111/111/0000000000011111111.20230517…

Redis分布式鎖的應用場景有哪些

? 、應?場景 在多線程并發的場景下 &#xff0c;Java Synchronized/Reentrantlock 鎖能夠實現同?個JVM進程內多線程 并發的安全性 &#xff0c;但?法保證多個JVM進程實例構成的集群環境在多線程下的安全性。在?些業務場景 下需要引?分布式鎖。 1、緩存擊穿 當某個熱點緩…