NETTY

package com.androidwatcher.common;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyClient {

    EventLoopGroup bossGroup;
    EventLoopGroup workerGroup;
    ChannelFuture channelFuture;

    public void startServer() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new DataHandler());
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(8091).sync();
        }
        catch (InterruptedException e) {
            log.error("",e);
        }
    }

    public void stopServer(){
        try {
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("",e);
        }
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

    private static class DataHandler extends SimpleChannelInboundHandler {

        @Override
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
            if (o instanceof ByteBuf){
                ByteBuf byteBuf= ((ByteBuf) o);
                int length = byteBuf.readableBytes();
                byte[] array = new byte[length];
                byteBuf.getBytes(byteBuf.readerIndex(), array);
                log.info(new String(array));
            }
        }
    }

}
 
  

                            
                        
                    
                    
                    

你可能感兴趣的:(NETTY)