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();
}
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值