Netty入门学习笔记2-核心组件Channel

一、定义

把 channel 理解为数据的通道。

二、channel 的主要作用

  • close() 可以用来关闭 channel

  • closeFuture() 用来处理 channel 的关闭

    • sync 方法作用是同步等待 channel 关闭

    • 而 addListener 方法是异步等待 channel 关闭

  • pipeline() 方法添加处理器

  • write() 方法将数据写入

  • writeAndFlush() 方法将数据写入并刷出

演示客户端的代码:

 public static void main(String[] args) throws InterruptedException, IOException {

        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast(new StringEncoder());

                    }
                })
                .connect("localhost", 8080);

        
        Channel channel = channelFuture
                 .sync()  //sync 方法是同步等待连接建立完成
                .channel();
        channel.writeAndFlush("hello  my netty3");


    }

Channel向服务器端发送数据,除了使用sync同步方式,还可以使用 异步回调方法:

package netty.channeltest;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.io.IOException;

public class NettyClientTest {


    public static void main(String[] args) throws InterruptedException, IOException {

        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast(new StringEncoder());

                    }
                })
                .connect("localhost", 8080);

//1、同步等待方法
//        Channel channel = channelFuture
//                 .sync()  //sync 方法是同步等待连接建立完成
//                .channel();
//        channel.writeAndFlush("hello  my netty3");

        //2异步回调方式

        channelFuture.addListener(new ChannelFutureListener(){
            @Override
            public void operationComplete(ChannelFuture cf) throws Exception {
                channelFuture.channel().writeAndFlush("hello my netty4");
            }
        }); 

    }


}

猜你喜欢

转载自blog.csdn.net/puzi0315/article/details/129226863