Netty实现TCP通信

Netty实现TCP通信

Netty实现网络通信时实际上是根据不同的通道类型来实现不同类型的协议处理

1. 服务端实现

public class NettyDiscardServer {
     
    public static void main(String[] args) throws InterruptedException {
     
        //启动管理器
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // workGroup and bossGroup
        // 处理链接建立
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // 消息处理
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
     
            serverBootstrap
                    .group(bossGroup, workGroup) //装配线程
                    .channel(NioServerSocketChannel.class) //通道类型
                    .localAddress(8888) //绑定端口
                    .childHandler(new ChannelInitializer<SocketChannel>() {
     
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
     
                            // 添加每个用户通道的处理器,处理用户的请求
                            socketChannel.pipeline().addLast(new NettyDiscardHandler());
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind().sync();
            ChannelFuture channelFuture1 = channelFuture.channel().closeFuture();
            channelFuture1.sync();
        } finally {
     
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

    }
}

2. Handler实现

public class NettyDiscardHandler extends ChannelInboundHandlerAdapter {
     

    /**
     * 处理通道中的数据
     * @param ctx 当前请求上下文
     * @param msg 消息
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
     
        // 客户端消息
        ByteBuf byteBuf = (ByteBuf) msg;
        try {
     
            while (byteBuf.isReadable()) {
     
                System.out.println((char) byteBuf.readByte());
            }
        } finally {
     
            ReferenceCountUtil.release(msg);
        }
    }
}

3. 客户端实现

  • 此处的客户端实际上还是NIO实现的socket通信
public class MyClient {
     
    public static void main(String[] args) throws Exception {
     
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);

        if (!socketChannel.connect(new InetSocketAddress("127.0.0.1", 8888))) {
     
            while (!socketChannel.finishConnect()) {
     
                System.out.println("connecting...");
            }
        }

        String str = "hello hgy";
        ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes());
        socketChannel.write(byteBuffer);
        System.in.read();
    }
}

你可能感兴趣的:(Netty,Netty基础网络通信,Netty,TCP通信,Netty,TCP)