SpringBoot项目集成socketIo实现实时推送

2023-11-09 22:10

本文主要是介绍SpringBoot项目集成socketIo实现实时推送,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 

  • netty-socketio maven依赖
<dependency><groupId>com.corundumstudio.socketio</groupId><artifactId>netty-socketio</artifactId><version>1.7.7</version>
</dependency>

 

  • application.properties相关配置
#============================================================================
# netty socket io setting
#============================================================================
# host在本地测试可以设置为localhost或者本机IP,在Linux服务器跑可换成服务器IP
socketio.host=localhost
socketio.port=9099
# 设置最大每帧处理数据的长度,防止他人利用大数据来攻击服务器
socketio.maxFramePayloadLength=1048576
# 设置http交互最大内容长度
socketio.maxHttpContentLength=1048576
# socket连接数大小(如只监听一个端口boss线程组为1即可)
socketio.bossCount=1
socketio.workCount=100
socketio.allowCustomRequests=true
# 协议升级超时时间(毫秒),默认10秒。HTTP握手升级为ws协议超时时间
socketio.upgradeTimeout=1000000
# Ping消息超时时间(毫秒),默认60秒,这个时间间隔内没有接收到心跳消息就会发送超时事件
socketio.pingTimeout=6000000
# Ping消息间隔(毫秒),默认25秒。客户端向服务器发送一条心跳消息间隔
socketio.pingInterval=25000

 

  • SocketIOConfig.java配置文件相关配置
package com.vcgeek.hephaestus.socketio;import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** 功能描述** @author: zyu* @description:* @date: 2019/4/23 10:40*/
@Configuration
public class SocketIOConfig {@Value("${socketio.host}")private String host;@Value("${socketio.port}")private Integer port;@Value("${socketio.bossCount}")private int bossCount;@Value("${socketio.workCount}")private int workCount;@Value("${socketio.allowCustomRequests}")private boolean allowCustomRequests;@Value("${socketio.upgradeTimeout}")private int upgradeTimeout;@Value("${socketio.pingTimeout}")private int pingTimeout;@Value("${socketio.pingInterval}")private int pingInterval;/*** 以下配置在上面的application.properties中已经注明* @return*/@Beanpublic SocketIOServer socketIOServer() {SocketConfig socketConfig = new SocketConfig();socketConfig.setTcpNoDelay(true);socketConfig.setSoLinger(0);com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();config.setSocketConfig(socketConfig);config.setHostname(host);config.setPort(port);config.setBossThreads(bossCount);config.setWorkerThreads(workCount);config.setAllowCustomRequests(allowCustomRequests);config.setUpgradeTimeout(upgradeTimeout);config.setPingTimeout(pingTimeout);config.setPingInterval(pingInterval);return new SocketIOServer(config);}}

 

以下就是提供一个SocketIOService接口,供其他地方需要使用时调用。

package com.vcgeek.hephaestus.socketio;import com.vcgeek.hephaestus.pojo.PushMessage;/*** 功能描述** @author: zyu* @description:* @date: 2019/4/23 10:41*/
public interface SocketIOService {//推送的事件public static final String PUSH_EVENT = "push_event";// 启动服务void start() throws Exception;// 停止服务void stop();// 推送信息void pushMessageToUser(PushMessage pushMessage);}

 

  • SocketIOServiceImpl.java接口实现类
package com.vcgeek.hephaestus.socketio;import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.vcgeek.hephaestus.pojo.PushMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;/*** 功能描述** @author: zyu* @description:* @date: 2019/4/23 10:42*/
@Service(value = "socketIOService")
public class SocketIOServiceImpl implements SocketIOService {// 用来存已连接的客户端private static Map<String, SocketIOClient> clientMap = new ConcurrentHashMap<>();@Autowiredprivate SocketIOServer socketIOServer;/*** Spring IoC容器创建之后,在加载SocketIOServiceImpl Bean之后启动** @throws Exception*/@PostConstructprivate void autoStartup() throws Exception {start();}/*** Spring IoC容器在销毁SocketIOServiceImpl Bean之前关闭,避免重启项目服务端口占用问题** @throws Exception*/@PreDestroyprivate void autoStop() throws Exception {stop();}@Overridepublic void start() throws Exception {// 监听客户端连接socketIOServer.addConnectListener(client -> {String loginUserNum = getParamsByClient(client);if (loginUserNum != null) {System.out.println(loginUserNum);System.out.println("SessionId:  " + client.getSessionId());System.out.println("RemoteAddress:  " + client.getRemoteAddress());System.out.println("Transport:  " + client.getTransport());clientMap.put(loginUserNum, client);}});// 监听客户端断开连接socketIOServer.addDisconnectListener(client -> {String loginUserNum = getParamsByClient(client);if (loginUserNum != null) {clientMap.remove(loginUserNum);System.out.println("断开连接: " + loginUserNum);System.out.println("断开连接: " + client.getSessionId());client.disconnect();}});// 处理自定义的事件,与连接监听类似socketIOServer.addEventListener("text", Object.class, (client, data, ackSender) -> {// TODO do something
            client.getHandshakeData();System.out.println( " 客户端:************ " + data);});socketIOServer.start();}@Overridepublic void stop() {if (socketIOServer != null) {socketIOServer.stop();socketIOServer = null;}}@Overridepublic void pushMessageToUser(PushMessage pushMessage) {String loginUserNum = pushMessage.getLoginUserNum();if (StringUtils.isNotBlank(loginUserNum)) {SocketIOClient client = clientMap.get(loginUserNum);if (client != null)client.sendEvent(PUSH_EVENT, pushMessage);}}/*** 此方法为获取client连接中的参数,可根据需求更改* @param client* @return*/private String getParamsByClient(SocketIOClient client) {// 从请求的连接中拿出参数(这里的loginUserNum必须是唯一标识)Map<String, List<String>> params = client.getHandshakeData().getUrlParams();List<String> list = params.get("loginUserNum");if (list != null && list.size() > 0) {return list.get(0);}return null;}public static Map<String, SocketIOClient> getClientMap() {return clientMap;}public static void setClientMap(Map<String, SocketIOClient> clientMap) {SocketIOServiceImpl.clientMap = clientMap;}
}

 

  • 前端相关测试页面编写
<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>NETTY SOCKET.IO DEMO</title><base><script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.min.js"></script><script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script><style>body {padding: 20px;}#console {height: 450px;overflow: auto;}.username-msg {color: orange;}.connect-msg {color: green;}.disconnect-msg {color: red;}</style>
</head><body><div id="console" class="well"></div><button id="btnSend" onclick="send()">发送数据</button>
</body>
<script type="text/javascript">var socket;connect();function connect() {var loginUserNum = '79';var opts = {query: 'loginUserNum=' + loginUserNum};socket = io.connect('http://localhost:9099', opts);socket.on('connect', function () {console.log("连接成功");serverOutput('<span class="connect-msg">连接成功</span>');});socket.on('push_event', function (data) {output('<span class="username-msg">' + data + ' </span>');console.log(data);});socket.on('disconnect', function () {serverOutput('<span class="disconnect-msg">' + '已下线! </span>');});}function output(message) {var element = $("<div>" + " " + message + "</div>");$('#console').prepend(element);}function serverOutput(message) {var element = $("<div>" + message + "</div>");$('#console').prepend(element);}function send() {console.log('发送数据');socket.emit('text','你好');}</script>
</html>

 

文章转载:https://www.jianshu.com/p/c67853e729e2

 

转载于:https://www.cnblogs.com/zyulike/p/10775358.html

这篇关于SpringBoot项目集成socketIo实现实时推送的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/378740

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——