Netty实战学习笔记02——简单Echo客户端编写

3 篇文章 0 订阅

今天来继续记录Echo的下半部分,Echo客户端的编写。

这里我们需要简单介绍一下我们所需要做的内容:

  • 为初始出啊客户端,创建一个Bootstarp实例;
  • 为进行事件处理分配一个NIOEventLoopGroup实例,其中事件处理包括创建新的连接以及处理入站和出站数据;
  • 为服务器连接创建一个InteSocketAddress实例;
  • 当连接被创建时,一个EchoClientHandler实例会被安装到该channel的ChannelPipeline中;
  • 在一切都设置完成后,调用Bootstrap.connect()方法连接到远程节点;

有了之前的基础之后,就比较简单了 ,话不多说直接上代码。

1.handler类

package com.youyou.netty.learn.echo.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.Date;

/**
 * //TODO 添加类/接口功能描述
 *
 * @author 刘朋
 * <br/>date 2019-10-06
 */
@ChannelHandler.Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //当被通知channel是活跃的时候,发送一条消息
        ctx.writeAndFlush(Unpooled.copiedBuffer("Netty Hello!", CharsetUtil.UTF_8));

        Runnable runnable = () -> {
            while (true){
                ctx.writeAndFlush(Unpooled.copiedBuffer(new Date().toString() ,CharsetUtil.UTF_8));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(runnable).start();
    }

    @Override
    public void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf in) throws Exception {
        //记录接收到的消息
        System.out.println("客户端接收到消息"+in.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        //关闭channle
        ctx.close();

    }


}

2.启动类

package com.youyou.netty.learn.echo.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * //TODO 添加类/接口功能描述
 *
 * @author 刘朋
 * <br/>date 2019-10-07
 */
public class EchoClient {
    private final String host = "localhost";
    private final int port = 8080;

    public static void main(String[] args) throws InterruptedException {
         new EchoClient().start();
    }

    public void start() throws InterruptedException {
        //事件循环处理组
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            //创建引导类
            Bootstrap b = new Bootstrap();
            //指定处理客户端时间的工作组,这里需要适用于NIO的实现
            b.group(eventLoopGroup)
                    //使用与NIO传输的channel类型
                    .channel(NioSocketChannel.class)
                    //设置服务器地址
                    .remoteAddress(new InetSocketAddress(host,port))
                    //在创建channel时,想channelPipeline中田间一个EchoClientHandler实例
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new EchoClientHandler());
                        }
                    });
            //连接到远程节点,阻塞等待直到连接完成
            ChannelFuture channelFuture = b.connect().sync();
            //阻塞,直到channel关闭
            channelFuture.channel().closeFuture().sync();
        }finally {
            //关闭线程池并且释放所有资源
            eventLoopGroup.shutdownGracefully().sync();
        }
    }


}

先启动服务端,再启动客户端,执行结果如下:

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值