当前位置: 首页 > 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

  

 

http://www.xdnf.cn/news/917875.html

相关文章:

  • 174页PPT家居制造业集团战略规划和运营管控规划方案
  • 【android bluetooth 协议分析 15】【SPP详解 1】【SPP 介绍】
  • ThinkPHP 5.1 中的 error 和 success 方法详解
  • 【LangchainAgent】Agent基本构建与使用
  • 基于Spring Boot的云音乐平台设计与实现
  • Vue3 项目的基本架构解读
  • K8S认证|CKS题库+答案| 6. 创建 Secret
  • Gartner《How to Create and Maintain a Knowledge Base forHumans and AI》学习报告
  • 学习使用YOLO的predict函数使用
  • Android 平台RTSP/RTMP播放器SDK接入说明
  • 现代简约壁炉:藏在极简线条里的温暖魔法
  • 数据库(sqlite)基本操作
  • 量子计算突破:新型超导芯片重构计算范式
  • Axure应用交互设计:注册登录页完整交互设计
  • Web前端基础
  • Axure应用交互设计:如何构建注册登录页
  • AxureRP-Pro-Beta-Setup_114413.exe (6.0.0.2887)
  • 1.5 Node.js 的 HTTP
  • 9.进程间通信
  • 提供MD5解密的网站
  • JAVA学习 DAY3 注释与编码规范讲解
  • Supersonic 新一代AI数据分析平台
  • 【题解-洛谷】B3622 枚举子集(递归实现指数型枚举)
  • 设计一个算法:删除非空单链表L中结点值为x的第一个结点的前驱结点
  • 零基础玩转物联网-串口转以太网模块如何快速实现与TCP服务器通信
  • 【20250607接单】Spark + Scala + IntelliJ 项目的开发环境配置从零教学
  • Spark 之 AQE
  • OneNet + openssl + MTLL
  • 科学选购儿童用品 | 了解增塑剂(尤其邻苯类)化学成分的来源与用途,为孩子多加一层健康防护。
  • 基于SpringBoot解决RabbitMQ消息丢失问题