Nettty入门(一)

Netty常用类介绍

  1. Bootstrap类,Bootstrap是Netty应用程序的启动类,我们可以通过其指定采用某种Channel,以及处理IO操作的EventLoopgroup,同时还可以指定我们需要操作的handler.
  2. 一个EventLoop可以为多个Channel服务,EventLoopGroup会包含多个EventLoop。
  3. ChannelInitializer 类中提供了ChannelPipeLine,我们可以通过这个类进行拦截,处理某个时间,ChannelPipeLine还可以指定我们对传输的信息进行那种编码,解码,以及怎样处理各种事件
  4. Handler类,我们通常是继承ChannelInboundHandlerAdapter来重写channelActive(连接成功调用),channelRead(当消息来的时候调用),exceptionCaught(发生异常时调用)等方法。
  5. Future和ChannelFutures。可以通过注册一个监听,当操作执行成功或失败时监听会自动触发。

netty jar包下载

简单的列子

客户端

public class NettyClient {
private String address;
private int port;
public NettyClient(String address,int port){
    this.address=address;
    this.port=port;
}
public void start(){
    EventLoopGroup group=new NioEventLoopGroup();
    Bootstrap bootstrap=new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ClientChannelInitializer());
    try {
        Channel channel=bootstrap.connect(address,port).sync().channel();
        while(true){
            String str=new Scanner(System.in).next();
            channel.writeAndFlush(str);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }finally {
        group.shutdownGracefully();
    }
}

ChannelInitializer类的实现(主要是指定连接的编码,解码处理事件的handler)

public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {

protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline pipeline=socketChannel.pipeline();
    pipeline.addLast("encoder",new StringEncoder());
    pipeline.addLast("decoder",new StringDecoder());
    pipeline.addLast("handler",new ClientHandler());
}
}

Handler类的实现(主要定义一些事件的处理)

public class ClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("客户端连接成功");
}

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("客户端断开连接");
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
   System.out.println(msg.toString());
}
}

服务端

public class NettyServer {
private int port;
public NettyServer(int port){
    this.port=port;
}
public void startServer(){
    EventLoopGroup bossGroup=new NioEventLoopGroup();
    EventLoopGroup workGroup=new NioEventLoopGroup();
    ServerBootstrap serverBootstrap=new ServerBootstrap().group(bossGroup,workGroup)
            .channel(NioServerSocketChannel.class)
            .childHandler(new ServerChannelInitializer());
    try {
        ChannelFuture future=serverBootstrap.bind(port).sync();
        future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
}

服务端的ChannelInitializer类

public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline pipeline=socketChannel.pipeline();
    pipeline.addLast("encoder",new StringEncoder());
    pipeline.addLast("decoder",new StringDecoder());
    pipeline.addLast("handler",new ServerHandler());
}
}

服务端的Handler类

public class ServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    System.out.println(ctx.channel().remoteAddress()+" "+msg.toString());
    ctx.write("已收到消息");
    ctx.flush();
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    System.out.println(cause.toString());
    ctx.close();
}
}

我也是在学习,如果有错误的,请提出来,一起进步,一起学习

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章