nettywebsocket springboot,springboot2 netty websocket
目录
一、pom.xml依赖配置二、代码2.1、网络服务器类2.2、SocketHandler类2.3、频道句柄池类2.4、应用启动类三、测试
一、pom.xml依赖配置
!-netty-依赖组idio。netty/groupId artifactId netty-all/artifactId version4.1.50.Final/version/dependency
二、代码
2.1、NettyServer 类
包com。望京。插座。服务器;导入com。望京。插座。处理程序。coordinationsockethandler导入io。妮蒂。自举。服务器引导;导入io。妮蒂。渠道。渠道未来;导入io。妮蒂。渠道。通道初始值设定项;导入io。妮蒂。渠道。引导开发;导入io。妮蒂。渠道。事件循环组;导入io。妮蒂。渠道。nio。nioeventloopgroup导入io。妮蒂。渠道。插座。套接字通道;导入io。妮蒂。渠道。插座。nio。nioserversocketchannel导入io。妮蒂。处理程序。编解码器。http。httpobjectaggregator导入io。妮蒂。处理程序。编解码器。http。http服务器编解码器;导入io。妮蒂。处理程序。编解码器。http。websocketx。websocketserverprotocolhandler;导入io。妮蒂。处理程序。溪流。chunkedwritehandlerpublic class coordination netty server { private final int port;public CoordinationNettyServer(int port){ this。port=端口;}公共void start()抛出异常{ EventLoopGroup boss group=new NioEventLoopGroup();EventLoopGroup group=new NioEventLoopGroup();请尝试{服务器引导sb=新服务器引导();某人选项(通道选项1024);某人团体(集团,老板集团)//绑定线程池。通道(nioserversocketchannel。class)//指定使用的渠道. localAddress(this.port)//绑定监听端口子处理程序(new ChannelInitializerSocketChannel(){//绑定客户端连接时候触发操作@覆盖受保护的void初始化通道(套接字通道ch)抛出异常{ //websocket协议本身是基于超文本传送协议(超文本传输协议的缩写)协议的,所以这边也要使用超文本传送协议(超文本传输协议的缩写)解编码器ch.pipeline().addLast(新的http服务器编解码器());//以块的方式来写的处理器管道()
.addLast(new ChunkedWriteHandler()); ch.pipeline().addLast(new HttpObjectAggregator(8192)); ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", "WebSocket", true, 65536 * 10)); ch.pipeline().addLast(new CoordinationSocketHandler());//自定义消息处理类 } }); ChannelFuture cf = sb.bind().sync(); // 服务器异步创建绑定 System.out.println(CoordinationNettyServer.class + "已启动,正在监听: " + cf.channel().localAddress()); cf.channel().closeFuture().sync(); // 关闭服务器通道 } finally { group.shutdownGracefully().sync(); // 释放线程池资源 bossGroup.shutdownGracefully().sync(); } }}
2.2、SocketHandler 类
package com.wangjing.socket.handler; import com.wangjing.socket.pool.CoordinationChannelHandlerPool;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; public class CoordinationSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("与客户端建立连接,通道开启!"); //添加到channelGroup通道组 CoordinationChannelHandlerPool.channelGroup.add(ctx.channel()); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("与客户端断开连接,通道关闭!"); //从channelGroup通道组删除 CoordinationChannelHandlerPool.channelGroup.remove(ctx.channel()); } @Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { //接收的消息 System.out.println(String.format("收到客户端%s的数据:%s", ctx.channel().id(), msg.text())); // 单独发消息 // sendMessage(ctx); // 群发消息 sendAllMessage(); } private void sendMessage(ChannelHandlerContext ctx) throws InterruptedException { String message = "我是服务器,你好呀"; ctx.writeAndFlush(new TextWebSocketFrame("hello")); } private void sendAllMessage() { String message = "我是服务器,这是群发消息"; CoordinationChannelHandlerPool.channelGroup.writeAndFlush(new TextWebSocketFrame(message)); } }
2.3、ChannelHandlerPool 类
package com.wangjing.socket.pool; import io.netty.channel.group.ChannelGroup;import io.netty.channel.group.DefaultChannelGroup;import io.netty.util.concurrent.GlobalEventExecutor; public class CoordinationChannelHandlerPool { public CoordinationChannelHandlerPool() { } //可以存储userId与ChannelId的映射表// public static ConcurrentHashMap<String, ChannelId> channelIdMap = new ConcurrentHashMap<>(); //channelGroup通道组 public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); }
2.4、Application启动类
package com.wangjing.socket; import com.wangjing.socket.server.CoordinationNettyServer;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication(scanBasePackages = "com.wangjing")public class SocketApplication { public static void main(String[] args) { SpringApplication.run(SocketApplication.class, args); try { new CoordinationNettyServer(8804).start(); } catch (Exception e) { System.out.println("NettyServerError:" + e.getMessage()); } } }
三、测试
websocket 在线测试推荐:在线websocket测试-online tool-postjson
到此这篇关于SpringBoot整合Netty实现WebSocket的示例代码的文章就介绍到这了,更多相关SpringBoot整合Netty实现WebSocket内容请搜索盛行IT以前的文章或继续浏览下面的相关文章希望大家以后多多支持盛行IT!
郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。