包结构:

第一步,在pom文件中导入netty依赖:
<!--netty--> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.6.Final</version> </dependency>
第二步,编写服务器端启动类
public class WSServer { private NioEventLoopGroup boss; //负责接收客户端过来的线程模型 private NioEventLoopGroup worker;//负责数据读写的线程模型 private ServerBootstrap bootstrap;//Netty服务器启动引导类 private ChannelFuture channelFuture;//一个执行异步操作后,将来可能会发生事件的状态 private static class SingletonInstance{ static final WSServer wsServer = new WSServer(); } public static WSServer getInstance(){ return SingletonInstance.wsServer; } private WSServer(){ boss = new NioEventLoopGroup(); worker = new NioEventLoopGroup(); bootstrap = new ServerBootstrap(); bootstrap.group(boss,worker)//指定服务器的线程模型 .channel(NioServerSocketChannel.class)//指定IO操作的模型 .option(ChannelOption.SO_BACKLOG,10240)//客户端可连接队列大小 .option(ChannelOption.SO_REUSEADDR,true)//允许重复使用地址和端口 .childOption(ChannelOption.SO_KEEPALIVE,true)//保活开关 .childOption(ChannelOption.TCP_NODELAY,true)//是否禁用Nagle算法,true表示禁用,即消息来了立即发送,false表示开启,即攒够一定数据了然后批量发送 .childHandler(new MyChannelInitializer());//初始化处理器 } public void start(){ this.channelFuture = bootstrap.bind(8808); System.out.println("WSServer启动成功..."); } }
第三步:创建上一步中的初始化处理器:MyChannelInitializer
public class MyChannelInitializer extends ChannelInitializer { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // websocket 基于http协议,所以要有http编解码器 pipeline.addLast(new HttpServerCodec()); // 对写大数据流的支持 pipeline.addLast(new ChunkedWriteHandler()); // 对httpMessage进行聚合,聚合成FullHttpRequest或FullHttpResponse pipeline.addLast(new HttpObjectAggregator(1024*64)); //指定客户端连接过来时,访问的路由以:ws开头 pipeline.addLast(new WebSocketServerProtocolHandler("/ws")); //心跳检测 pipeline.addLast(new IdleStateHandler(8,10,15));//写这一行之后,会触发ChannelInboundHandlerAdapter中的userEventTriggered方法,也就是第四步中定义的心跳处理器 pipeline.addLast(new HeartBeatHandler()); //自定义处理器 pipeline.addLast(new CustomChatHandler()); } }
第四步:编写心跳处理器
文章评论