当前位置: 首页 > news >正文

Java高级 |【实验八】springboot 使用Websocket

隶属文章:Java高级 | (二十二)Java常用类库-CSDN博客

系列文章:Java高级 | 【实验一】Springboot安装及测试 |最新-CSDN博客

                  Java高级 | 【实验二】Springboot 控制器类+相关注解知识-CSDN博客

                  Java高级 | 【实验三】Springboot 静态资源访问-CSDN博客

                  Java高级 | 【实验四】Springboot 获取前端数据与返回Json数据-CSDN博客

                  Java高级 | 【实验五】Spring boot+mybatis操作数据库-CSDN博客

                  Java高级 | 【实验六】Springboot文件上传和下载-CSDN博客

                  Java高级 | 【实验七】Springboot 过滤器和拦截器-CSDN博客

目录

一、WebSocket

1.1 HTTP协议 VS WebSocket协议

1.2 WebSocket 应用场景

二、springboot中WebSocket实现 

2.1 服务端代码

1)引入websocket依赖

2)定义WebSocket服务端程序

5)在主类中添加定器的执行

2.2 客户端代码

2.3 测试


一、WebSocket

         WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信,即允许服务器主动发送信息给客户端。因此,在WebSocket中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输,客户端和服务器之间的数据交换变得更加简单。

1.1 HTTP协议 VS WebSocket协议

HTTPWebSocket
连接类型短连接长连接
通信方式单向,基于请求响应模式支持双向通信
底层协议TCP连接

1.2 WebSocket 应用场景

应用场景说明
实时通信

非常适合需要实时通信的应用场景,例如,在线聊天室、即时消息传递和视频会议等应用中,用户可以通过WebSocket实时接收和发送消息。

比传统的HTTP轮询更高效,因为它不需要频繁地建立和关闭连接。

多用户游戏提供快速、实时的游戏状态更新,提供流畅的游戏体验。
协同编辑

协同编辑应用,如Google Docs,允许多个用户同时编辑同一个文档。

WebSocket可以用来同步不同用户的编辑操作,确保所有用户都能看到最新的内容。

股票或货币交易平台推送最新的交易数据,帮助交易者做出快速决策。
体育赛事直播实时更新比分和比赛状态,为用户提供即时的比赛信息。
在线教育实现实时的教学互动,如实时问答、投票和测验。

二、springbootWebSocket实现 

  

2.1 服务端代码

1)引入websocket依赖

在pom.xml中引入如下依赖:

<!--        引入websocket依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>

导入依赖后,再启动运行,确保日志没有error

  

2)定义WebSocket服务端程序

创建一个名为WebSocketServer的类,其代码如下:

正常log不需要注释才能看到提示结果,我注释是因为当时idea有点问题,暂时没管

package com.example.sp_websocket;import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {private static Map<String, Session> sessionMap = new HashMap<>();/*** 连接建立时触发* @param session* @param sid*/@OnOpenpublic void onOpen(Session session , @PathParam("sid") String sid){
//        log.info("有客户端连接到了服务器 , {}", sid);sessionMap.put(sid, session);}/*** 服务端接收到消息时触发* @param session* @param message* @param sid*/@OnMessagepublic void onMessage(Session session , String message, @PathParam("sid") String sid){
//        log.info("接收到了客户端 {} 发来的消息 : {}", sid ,message);}/*** 连接关闭时触发* @param session* @param sid*/@OnClosepublic void onClose(Session session , @PathParam("sid") String sid){System.out.println("连接断开:" + sid);sessionMap.remove(sid);}/*** 通信发生错误时触发* @param session* @param sid* @param throwable*/@OnErrorpublic void onError(Session session , @PathParam("sid") String sid , Throwable throwable){System.out.println("出现错误:" + sid);throwable.printStackTrace();}/*** 广播消息* @param message* @throws IOException*/public void sendMessageToAll(String message) throws IOException {Collection<Session> sessions = sessionMap.values();if(!CollectionUtils.isEmpty(sessions)){for (Session session : sessions) {//服务器向客户端发送消息session.getBasicRemote().sendText(message);}}}
}

3)定义配置类,注册WebSocket的服务端

创建WebSocketConfig类,其代码如下:

package com.example.sp_websocket;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;@Configuration
public class WebSocketConfig {/*** 注册基于@ServerEndpoint声明的Websocket Endpoint* @return*/@Beanpublic ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter();}
}

说明:如果ServerEndpointExporter无法正确识别,则在pom.xml文件删除tomcat的依赖。

4)定义定时任务类,定时向客户端推送数据

编写MessageTask类,其代码如下:

package com.example.sp_websocket;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;import java.io.IOException;
import java.time.LocalDateTime;
@Component
public class MessageTask {@Autowiredprivate WebSocketServer webSocketServer;@Scheduled(cron = "0/5 * * * * ?")public void sendMessageToAllClient() throws IOException {System.out.println("sssss");webSocketServer.sendMessageToAll("Hello Client , Current Server Time : " + LocalDateTime.now());}
}

5)在主类中添加定器的执行

在SpWebsocketApplication类中添加定时器执行的注解,修改后的代码如下:

package com.example.sp_websocket;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication
@EnableScheduling
public class SpWebsocketApplication {public static void main(String[] args) {SpringApplication.run(SpWebsocketApplication.class, args);}}

2.2 客户端代码

定义websocket.html页面充当客户端。

websocket.html存放在电脑上,比如,我放在了D盘

  

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<input id="text" type="text" />
<button onclick="send()">发送消息</button>
<button onclick="closeWebSocket()">关闭连接</button>
<div id="message">
</div>
</body>
<script type="text/javascript">var websocket = null;var clientId = Math.random().toString(36).substr(2);//判断当前浏览器是否支持WebSocketif('WebSocket' in window){//连接WebSocket节点websocket = new WebSocket("ws://localhost:8080/ws/"+clientId);}else{alert('Not support websocket')}//连接发生错误的回调方法websocket.onerror = function(){setMessageInnerHTML("error");};//连接成功建立的回调方法websocket.onopen = function(){setMessageInnerHTML("连接成功");}//接收到消息的回调方法websocket.onmessage = function(event){setMessageInnerHTML(event.data);}//连接关闭的回调方法websocket.onclose = function(){setMessageInnerHTML("close");}//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。window.onbeforeunload = function(){websocket.close();}//将消息显示在网页上function setMessageInnerHTML(innerHTML){document.getElementById('message').innerHTML += innerHTML + '<br/>';}//发送消息function send(){var message = document.getElementById('text').value;websocket.send(message);}//关闭连接function closeWebSocket() {websocket.close();}
</script>
</html>

2.3 测试

运行websocket.html。即双击websocket.html

  

 

相关文章:

  • 【计算机组成原理】计算机硬件的基本组成、详细结构、工作原理
  • 【云架构】
  • Node.js: express 使用 Open SSL
  • 新能源汽车热管理核心技术解析:冬季续航提升40%的行业方案
  • 怎么解决cesium加载模型太黑,程序崩溃,不显示,位置不对模型太大,Cesium加载gltf/glb模型后变暗
  • Windows账户管理,修改密码,创建帐户...(无需密码)
  • 基于SFC的windows系统损坏修复程序
  • SQL Server全局搜索:在整个数据库中查找特定值的高效方法
  • C++.OpenGL (2/64)你好,三角形(Hello Triangle)
  • mitmproxy 爬虫,下载自己的博客图片
  • 个人电脑部署本地大模型+UI
  • 湖北理元理律师事务所:企业债务重组的风险控制方法论
  • 11.RV1126-ROCKX项目 API和人脸检测画框
  • CMake 为 Debug 版本的库或可执行文件添加 d 后缀
  • DRV8833 电机控制芯片
  • 东芝Toshiba DP-4528AG打印机信息
  • 高精度加减乘除
  • 从零开始的python学习(七)P95+P96+P97+P98+P99+P100+P101
  • 软件测试:质量保障的基石与未来趋势
  • Linux 初始化与服务管理全解析:rc.d、systemctl与service对比
  • 辽宁建设工程信息网场内业绩/宁波seo基础入门
  • 一个人可以做多少网站/百度网址大全 官网
  • 迅睿cms建站/爱站网关键字挖掘
  • 电子商务专业网站设计/韩国热搜榜
  • 网站建设管理软件/windows优化大师是自带的吗
  • 济南做网站费用/怎样利用互联网进行网络推广