Netty 客户端

客户端 和服务端差不多

注意 需要单独开线程 做netty , 如果不开线程会阻塞主线程(spring @Bean) , 客户端不能直接发送字符串 需要转换成Bytebuffer

public class NettyClient {

    public static void main(String[] args) {

        NioEventLoopGroup boss = new NioEventLoopGroup(1);

        Bootstrap bootstrap = new Bootstrap().group(boss);
        bootstrap.channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {

                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new SimpleChannelInboundHandler<Object>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                                System.out.println(msg);
                            }
                        });

                    }

                });

        try {
            ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 13140)).sync();

            future.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture arg0) throws Exception {
                    if (future.isSuccess()) {
                        System.out.println("连接服务器成功");

                    } else {
                        System.out.println("连接服务器失败");
                        future.cause().printStackTrace();
                        boss.shutdownGracefully(); //关闭线程组
                    }
                }
            });
            Executors.newFixedThreadPool(1).submit(()->{
                Channel channel = future.channel();
                while(true) {
                    channel.writeAndFlush(Unpooled.copiedBuffer("hello world".getBytes()));

                    TimeUnit.SECONDS.sleep(2);
                }
            });

            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nier6088

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值