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

java开源Socket.io服务器端长链接通信解决方案

netty-socketio 概述
netty-socketio是一个开源的Socket.io服务器端的一个java的实现,它基于Netty框架,可用于服务端推送消息给客户端。

说到服务端推送技术,一般会涉及WebSocket,WebSocket是HTML5最新提出的规范,虽然主流浏览器都已经支持,但仍然可能有不兼容的情况,为了兼容所有浏览器,给程序员提供一致的编程体验,SocketIO将WebSocket、AJAX和其它的通信方式全部封装成了统一的通信接口,也就是说,使用SocketIO时不用担心兼容问题,底层会自动选用最佳的通信方式。

netty-socketio 框架事件流程

netty-socketio 示例demo
pom.xml

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.corundumstudio.socketio</groupId><artifactId>netty-socketio</artifactId><version>1.7.17</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.4</version><scope>provided</scope></dependency></dependencies>

启动类 NettySocketioApplication

@SpringBootApplication
@Slf4j
public class NettySocketioApplication implements CommandLineRunner {public static void main(String[] args) {SpringApplication.run(NettySocketioApplication.class, args);}@Autowiredprivate SocketIOServer socketIOServer;@Overridepublic void run(String... strings) {socketIOServer.start();log.info("socket.io启动成功!");}
}
Message@Data
public class Message {private String msg;
}
配置类 NettySocketioConfig@Configuration
public class NettySocketioConfig {/*** netty-socketio服务器*/@Beanpublic SocketIOServer socketIOServer() {com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();config.setHostname("localhost");config.setPort(9092);SocketIOServer server = new SocketIOServer(config);return server;}/*** 用于扫描netty-socketio的注解,比如 @OnConnect、@OnEvent*/@Beanpublic SpringAnnotationScanner springAnnotationScanner() {return new SpringAnnotationScanner(socketIOServer());}
}

消息处理器 MessageEventHandler

@Component
@Slf4j
public class MessageEventHandler {@Autowiredprivate SocketIOServer socketIoServer;public static ConcurrentMap<String, SocketIOClient> socketIOClientMap = new ConcurrentHashMap<>();/*** 客户端连接的时候触发** @param client*/@OnConnectpublic void onConnect(SocketIOClient client) {String mac = client.getHandshakeData().getSingleUrlParam("mac");//存储SocketIOClient,用于发送消息socketIOClientMap.put(mac, client);//回发消息client.sendEvent("message", "onConnect back");log.info("客户端:" + client.getSessionId() + "已连接,mac=" + mac);}/*** 客户端关闭连接时触发** @param client*/@OnDisconnectpublic void onDisconnect(SocketIOClient client) {log.info("客户端:" + client.getSessionId() + "断开连接");}/*** 客户端事件** @param client   客户端信息* @param request 请求信息* @param data     客户端发送数据*/@OnEvent(value = "messageevent")public void onEvent(SocketIOClient client, AckRequest request, Message data) {log.info("发来消息:" + data);//回发消息client.sendEvent("messageevent", "我是服务器都安发送的信息");//广播消息sendBroadcast();}/*** 广播消息*/public void sendBroadcast() {for (SocketIOClient client : socketIOClientMap.values()) {if (client.isChannelOpen()) {client.sendEvent("Broadcast", "当前时间", System.currentTimeMillis());}}}
}

html 页面

<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, user-scalable=no"><title>websocket-java-socketio</title><script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
</head>
<body>
<h1>Socket.io Test</h1>
<div><p id="status">Waiting for input</p></div>
<div><p id="message">hello world!</p></div>
<button id="connect" onClick='connect()'/>Connect</button>
<button id="disconnect" onClick='disconnect()'>Disconnect</button>
<button id="send" onClick='send()'/>Send Message</button>
</body><script type="text/javascript">/*** 前端js的 socket.emit("事件名","参数数据")方法,是触发后端自定义消息事件的时候使用的,* 前端js的 socket.on("事件名",匿名函数(服务器向客户端发送的数据))为监听服务器端的事件**/var socket = io.connect("http://localhost:9092?mac=2");var firstconnect = true;function connect() {if(firstconnect) {//socket.on('reconnect', function(){ status_update("Reconnected to Server"); });//socket.on('reconnecting', function( nextRetry ){ status_update("Reconnecting in "//+ nextRetry + " seconds"); });//socket.on('reconnect_failed', function(){ message("Reconnect Failed"); });//firstconnect = false;} else {socket.socket.reconnect();}}//监听服务器连接事件socket.on('connect', function(){ status_update("Connected to Server"); });//监听服务器关闭服务事件socket.on('disconnect', function(){ status_update("Disconnected from Server"); });//监听服务器端发送消息事件socket.on('messageevent', function(data) {message(data)//console.log("服务器发送的消息是:"+data);});//断开连接function disconnect() {socket.disconnect();}function message(data) {document.getElementById('message').innerHTML = "Server says: " + data;}function status_update(txt){document.getElementById('status').innerHTML = txt;}function esc(msg){return msg.replace(/</g, '<').replace(/>/g, '>');}//点击发送消息触发function send() {console.log("点击了发送消息,开始向服务器发送消息")var msg = "我很好的,是的.";socket.emit('messageevent', {msgContent: msg});};
</script>
</html>

执行输出
运行 SpringBoot 服务器

mvn spring-boot:run
点击网页按钮

标签: netty-socketio, springBoot

http://www.dtcms.com/a/602087.html

相关文章:

  • 牛客2025秋季算法编程训练联赛4-基础组
  • 视频类网站怎么做软件开发专业技能
  • 具身智能-一文详解视觉-语言-动作(VLA)大模型1.前言2.VLA的进化之路:从单兵作战到三位一体3.拆解VLA的大脑:核心组件全解析 预训练视觉表征
  • 空口协议栈的介绍及CA对其的影响
  • 网站建设制作优化推广类电商文案
  • 网站空间购买价格电子商务以后能干什么
  • C语言编译预处理 | 探索C语言编译过程中的预处理环节
  • kubernetes(k8s)-扩缩容(工作负载HPA、节点)
  • 广告设计网站官网北京小程序定制开发
  • 做网站怎样收费的怎样更换网站模板
  • 狸窝转换器将MP4格式视频转换为以下格式后的大小对比:RM、RMVB、AVI、MKV、WMV、VOB、MOV、FLV、ASF、DAT、3GP、MPG、MPEG
  • 【QT/C++】Qt样式设置之CSS知识(系统性概括)
  • 《华为应用市场编程工具上架深度拆解:鸿蒙适配与合规实战指南》
  • 29.删除链表的倒数第 N 个结点
  • 做黑帽需不需要搭建网站o2o的四种营销模式
  • 中英文的网站是怎么做的中国建设官网信息查询
  • 大航母网站建设流程黑龙江网站制作平台
  • C语言编译软件文档 | 如何高效使用C语言编译工具,提升编程效率
  • Android ROOM 数据库
  • 从红军城烽火到无人机时代:两场战争的跨越与现代军事启示
  • 营口网站seo网站开发的相关网站
  • 解决PyQt6安装失败:文件重命名权限错误与缓存清理方法
  • 第五章:MySQL DQL 进阶 —— 动态计算与分类(IF 与 CASE WHEN)多表查询
  • 【SQL server】不同平台相同数据库之间某个平台经常性死锁
  • Ubuntu系统安装.NET SDK 7.0
  • 基于深度学习与MATLAB的脑电信号情绪识别系统
  • 十大旅游电子商务网站wordpress 国内 慢
  • 大连网站制作姚喜运成都网页设计培训班
  • Apache POI
  • 某景区网站建设策划书利用codeing做网站