Netty第一天

Netty的基本使用

Hello Netty

Maven引用

<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.28.Final</version>

客户端代码

/*
EchoClient类
*/
public class EchoClient {
    private final int port;
    private final String host;

    public EchoClient(int port, String host) {
        this.port = port;
        this.host = host;
    }
    public void start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();//线程组
        try {
            Bootstrap b = new Bootstrap();//客户端启动必备
            b.group(group)
                    .channel(NioSocketChannel.class)//指明使用NIO进行网络通信
                    .remoteAddress(new InetSocketAddress(host, port))//配置远程服务器地址
                    .handler(new EchoClientHandler());
            ChannelFuture f = b.connect().sync();//连接到远程节点,阻塞等待直到连接完成
            f.channel().closeFuture().sync();//阻塞直到channel关闭
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new EchoClient(9999, "127.0.0.1").start();
    }
 }
/*
EchoClientHandle类
*/
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    //数据端读取到数据后做什么
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("客户端读取到" + msg.toString(CharsetUtil.UTF_8));
    }
    //客户端被通知channel活跃以后,做事

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //往服务器写数据
        ctx.writeAndFlush(Unpooled.copiedBuffer("Hello,Netty", CharsetUtil.UTF_8));


    }

    //异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //把错误打出来,
        cause.printStackTrace();
        //关闭服务
        ctx.close();
    }
}

服务端代码


/*
EchoServer 类
*/
public class EchoServer {
    private  final  int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        int port = 9999;
        EchoServer echoServer = new EchoServer(port);
        System.out.println("服务器即将启动");
        echoServer.start();
        System.out.println("服务器关闭");
    }
    public void start() throws InterruptedException {
        final EchoServerHandler serverHandler = new EchoServerHandler();
        //线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap(); //服务端启动必备
            b.group(group)
                    .channel(NioServerSocketChannel.class)//使用NIO进行网络通信
                    .localAddress(new InetSocketAddress(port))//指明服务器监听端口
                    //接收到连接请求 新启一个socker通信,
                    // 也就是新启一个channel,每一个channel有自己的事件的handler
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(serverHandler);
                        }
                    });
            ChannelFuture f = b.bind().sync();//绑定到端口,阻塞等待直到连接完成
            f.channel().closeFuture().sync();//阻塞直到channel关闭
        }finally {
            group.shutdownGracefully().sync();
        }
    }
}
/*
EchoServerHandler 类
*/
//指明这个Handler可以在多个channel之间共享
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    //服务器端读取到网络数据后的处理
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf)msg;//netty实现的缓冲区
        System.out.println("server"+in.toString(CharsetUtil.UTF_8));
        ctx.write(in);

    }

    //服务端读取完成网络数据后的处理
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) //flush掉所有数据
            .addListener(ChannelFutureListener.CLOSE);//当flush完成后 关闭连接

    }

    //发生异常后的处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}


方法作用
group设置EventLoopGroup用于处理所有的Channel的事件
channel()channelFactory()指定Channel的实现类。如果没有提供一个默认的构造函数,你可以调用调用channelFactory()来指定一个工厂被bind()调用
localAddress()指定应该绑定的本地地址Channel.如果没有提供将由操作系统创建一个随机。或者你可以使用bind()或connect()指定localAddress
option设置ChannelOption应用于新创建Channel的ChannelConfig.这些选项将被bind或connect设置在通道,这取决于哪个被前调用。这个方法在创建管道后没用影响。
attr这些选项将被bind或connect设置在通道,这取决于那个被前调用。这个方法在管道被创建后没有影响
handler设置添加到ChannelPipeline中的ChannelHandle接收事件通知
clone创建一个当前Bootstrap的克隆拥有原来相同的设置
remoteAddress设置远程地址 此外可以通过connect()指定
connect连接到远端 返回一个ChannelFuture,用于通知连接操作完成
bind将通道绑定并返回一个ChannelFuture,用于通知绑定操作完成后必须调用Channel.connect()来建立连接
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值