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();
    }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值