| | |
| | | import io.netty.channel.socket.SocketChannel; |
| | | import io.netty.channel.socket.nio.NioServerSocketChannel; |
| | | import io.netty.handler.codec.DelimiterBasedFrameDecoder; |
| | | import io.netty.handler.codec.LengthFieldBasedFrameDecoder; |
| | | import io.netty.handler.codec.LengthFieldPrepender; |
| | | import io.netty.handler.codec.string.StringDecoder; |
| | | import io.netty.handler.logging.LoggingHandler; |
| | | |
| | | import java.nio.ByteOrder; |
| | | import java.nio.charset.Charset; |
| | | import io.netty.util.ReferenceCountUtil; |
| | | |
| | | |
| | | public class TcpServer { |
| | |
| | | // 绑定处理group |
| | | bootstrap.group(boss, worker).channel(NioServerSocketChannel.class) |
| | | //保持连接数 |
| | | .option(ChannelOption.SO_BACKLOG, 128) |
| | | .option(ChannelOption.SO_BACKLOG, 30) |
| | | //设置缓冲区大小 |
| | | .option(ChannelOption.SO_RCVBUF, 1024*1024) |
| | | .option(ChannelOption.SO_SNDBUF, 1024*1024) |
| | | //有数据立即发送 |
| | | .option(ChannelOption.TCP_NODELAY, true) |
| | | //保持连接 |
| | | .childOption(ChannelOption.SO_KEEPALIVE, true) |
| | | .childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(512*250)) |
| | | .childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024)) |
| | | .childHandler(new NettyChannelHandler()); |
| | | |
| | | //绑定端口,同步等待成功 |
| | |
| | | //优雅地退出,释放线程池资源 |
| | | boss.shutdownGracefully(); |
| | | worker.shutdownGracefully(); |
| | | |
| | | } |
| | | } |
| | | }); |
| | |
| | | @Override |
| | | protected void initChannel(SocketChannel socketChannel) |
| | | throws Exception { |
| | | //socketChannel.pipeline().addLast(new MyNettyDecode()); |
| | | //socketChannel.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8"))); |
| | | //socketChannel.pipeline().addLast("decoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4)); |
| | | //socketChannel.pipeline().addLast("encoder", new LengthFieldPrepender(4, false)); |
| | | ByteBuf delimiter = Unpooled.copiedBuffer("}".getBytes()); |
| | | socketChannel.pipeline().addLast( new DelimiterBasedFrameDecoder(200000,delimiter)); |
| | | socketChannel.pipeline().addLast(new TcpServerHandler()); |
| | | } |
| | | } |