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

使用Websocket进行前后端实时通信

1、引入jar,spring-websocket-starter

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2、配置websocket config

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {registry.addHandler(myHandler(), "/myEndpoint").setAllowedOrigins("*");}public WebSocketHandler myHandler() {return new MyWebSocketHandler();}
}

3、使用实现websocket handler

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;public class MyWebSocketHandler extends TextWebSocketHandler {@Overridepublic void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {System.out.println("Received: " + message.getPayload());session.sendMessage(new TextMessage("Hello from server"));}
}

4、前端使用

<script>var socket = new WebSocket("ws://localhost:8080/myEndpoint");socket.onmessage = function(event) {console.log('Received from server:', event.data);};socket.onopen = function() {socket.send('Hello Server');};
</script>

http://www.lryc.cn/news/523925.html

相关文章:

  • vue2使用flv.js在浏览器打开flv格式视频
  • OpenCV相机标定与3D重建(61)处理未校准的立体图像对函数stereoRectifyUncalibrated()的使用
  • [cg] glProgramBinary
  • LeetCode hot 力扣热题100 二叉树的最大深度
  • 速通Docker === 网络
  • 【MySQL — 数据库基础】深入解析MySQL常用数据类型
  • Linux高级--3.3.1 C++ spdlog 开源异步日志方案
  • 电梯系统的UML文档05
  • 如何使 LLaMA-Factory 支持 google/gemma-2-2b-jpn-it 的微调
  • MySQL中日期和时间戳的转换:字符到DATE和TIMESTAMP的相互转换
  • HarmonyOS NEXT开发进阶(十):UIAbility 组件交互
  • 深入探索Math.NET:开启高效数值计算之旅
  • AI编程工具横向评测--Cloudstudio塑造完全态的jupyter notebook助力数据分析应用开发
  • 【2024 CSDN博客之星】技术洞察类:从DeepSeek-V3的成功,看MoE混合专家网络对深度学习算法领域的影响(MoE代码级实战)
  • Linux——入门基本指令汇总
  • 54,【4】BUUCTF WEB GYCTF2020Ezsqli
  • 【Leetcode 热题 100】45. 跳跃游戏 II
  • C/C++ 时间复杂度(On)
  • 【STM32-学习笔记-10-】BKP备份寄存器+时间戳
  • React 中hooks之 React.memo 和 useMemo用法总结
  • 日志收集Day001
  • 机器人“大脑+小脑”范式:算力魔方赋能智能自主导航
  • python程序跑起来后,然后引用的数据文件发生了更新,python读取的数据会发生变化吗
  • VSCode最新离线插件拓展下载方式
  • 算法题目总结-栈和队列
  • IO进程----进程
  • 【机器学习实战高阶】基于深度学习的图像分割
  • 「免填邀请码」赋能各类APP,提升转化率与用户体验
  • 基于海思soc的智能产品开发(视频的后续开发)
  • 创建 pdf 合同模板