Netty 实现ServerSocket

Netty 实现ServerSocket

Netty是一款基于NIO(Nonblocking I/O,非阻塞IO)开发的网络通信框架,对比于BIO(Blocking I/O,阻塞IO),他的并发性能得到了很大提高。NIO,同步非阻塞IO,阻塞业务处理但不阻塞数据接收,适用于高并发且处理简单的场景。

相关概念:

Channel

数据传输流,与channel相关的概念有以下四个,上一张图让你了解netty里面的Channel。

  1. Channel,表示一个连接,可以理解为每一个请求,就是一个Channel。
  2. ChannelHandler,核心处理业务就在这里,用于处理业务请求。
  3. ChannelHandlerContext,用于传输业务数据。
  4. ChannelPipeline,用于保存处理过程需要用到的ChannelHandler和ChannelHandlerContext。

ByteBuf

ByteBuf是一个存储字节的容器,方便你对整段字节缓存进行读写,也支持get/set

  1. Heap Buffer 堆缓冲区 ,堆缓冲区是ByteBuf最常用的模式,他将数据存储在堆空间。
  2. Direct Buffer 直接缓冲区,他的内存分配都不发生在堆,jdk1.4引入的nio的ByteBuffer类允许jvm通过本地方法调用分配内存
  3. Composite Buffer 复合缓冲区,复合缓冲区相当于多个不同ByteBuf的视图,这是netty提供的,jdk不提供这样的功能。

Codec

Netty中的编码/解码器,HttpRequestDecoder和HttpResponseEncoder,也可自定义解码器

通过netty实现ServerSocket的步骤:

1.环境:ideal springboot

pom.xml中添加依赖:


   io.netty
   netty-all
   5.0.0.Alpha2

2.Server端代码:

public class EchoServer {
    private final Integer tcpServerPort;

    public EchoServer(Integer tcpServerPort) {
        this.tcpServerPort = tcpServerPort;
    }

    public void start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(group)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .localAddress(new InetSocketAddress(tcpServerPort))
                    .childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws
                        Exception {
                            socketChannel.pipeline().addLast(
                            		//添加读取超时
                                    new ReadTimeoutHandler(30),
                                    //添加写入超时
                                    new WriteTimeoutHandler(30),
                                    //消息处理Handler
                                    new EchoServerHandler()
                                    );
                        }
                    });
            ChannelFuture future = bootstrap.bind().sync();
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }
    
    public static void main(String[] args) {
        EchoServer tcpserver = new EchoServer(6788);
		try {
			tcpserver.start();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    }
}

Hander代码:

主要是实现几个接口函数

// 标志该Handler可以被多个Handler安全的共享。
@ChannelHandler.Sharable 
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(final ChannelHandlerContext ctx)throws Exception{
		//连接激活后,可做处理
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        System.out.println("Server received:" + in.toString(CharsetUtil.UTF_8)); 
        //根据消息类型回复报文数据
        ctx.writeAndFlush(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws
    Exception {
        cause.printStackTrace();
        ctx.close();
    }

}

你可能感兴趣的:(高并发)