package cn.mb.cloud.gateway.util.echo; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.timeout.IdleStateHandler; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; /** * 即时通讯服务启动类 * * @date 2016年6月25日 * @version 1.0 */ public class NettyServer { /** * NettyServer启动方法. */ public void bind() { final Thread thread = new Thread(new NettyRunnable()); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { thread.start(); } }, 10000); } /** * 即时通讯服务启动 * * @date 2016年6月24日 * @version 1.0 */ public class NettyRunnable implements Runnable { /** * 获取即时通讯启动端口 */ private Integer nettyPort = 8888; @Override public void run() { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup); bootstrap.channel(NioServerSocketChannel.class); bootstrap.option(ChannelOption.SO_BACKLOG, 1024); // 通过TCP_NODELAY禁用NAGLE,使消息立即发出去,不用等待到一定的数据量才发出去 bootstrap.option(ChannelOption.TCP_NODELAY, true); // 保持长连接状态 bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); bootstrap.childHandler(new ServerInit() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); pipeline.addLast("ping", new IdleStateHandler(120, 60, 5, TimeUnit.SECONDS)); pipeline.addLast("decoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); pipeline.addLast("encoder", new LengthFieldPrepender(4)); //pipeline.addLast(new LineBasedFrameDecoder(1048576 * 10)); //pipeline.addLast(new StringDecoder(Charset.forName("UTF-8"))); //pipeline.addLast(new StringEncoder(Charset.forName("UTF-8"))); pipeline.addLast(new DiscardServerHandler()); } }); // 服务器绑定端口监听 ChannelFuture f = bootstrap.bind(nettyPort).sync(); if(f.isSuccess()) { System.out.println("******************************Netty启动成功******************************"); } // 监听服务器关闭监听 f.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } }