Netty 介绍

在这里插入图片描述
在这里插入图片描述

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

在这里插入图片描述

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Netty 服务端
 */
public class NettyServerListenerSimple {

  /**
   * 创建bootstrap
   */
  private static final ServerBootstrap serverBootstrap = new ServerBootstrap();

  /**
   * Worker
   */
  private static final EventLoopGroup work = new NioEventLoopGroup();

  /**
   * 端口号
   */
  private int port = getPort();

  /**
   * 关闭服务器方法
   */
  public void close() {
    System.out.println("关闭服务器....");
    //优雅退出
    work.shutdownGracefully();
  }

  /**
   * 开启及服务线程
   */
  public void start() {
    serverBootstrap.group(work)
        .channel(NioServerSocketChannel.class)
        .option(ChannelOption.SO_BACKLOG, 100)
        .handler(new LoggingHandler(LogLevel.INFO));
    try {
      //设置事件处理
      serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
          ChannelPipeline pipeline = ch.pipeline();
          pipeline.addLast(new ServerChannelHandlerSimple());
        }
      });
      System.out.println("netty服务器在[" + port + "]端口启动监听");
      ChannelFuture f = serverBootstrap.bind(port).sync();
      f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
      System.out.println("[出现异常] 释放资源");
      work.shutdownGracefully();
    }
  }

  private static int getPort() {
    Double port = (Math.random() + 1) * 10000;
    return port.intValue();
  }

  public static void main(String[] args) {
    NettyServerListenerSimple nsl = new NettyServerListenerSimple();
    nsl.start();
  }
}

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.nio.charset.Charset;

/**
 * 服务端的通道适配器
 */
public class ServerChannelHandlerSimple extends ChannelInboundHandlerAdapter {

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    System.out.println("error.");
    cause.printStackTrace();
    ctx.close();
  }

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) {
    // 具体处理客户端的数据信息
    System.out.println("receive message. ");
    ByteBuf buf = (ByteBuf) msg;
    String rev = getMessage(buf);
    System.out.println(rev);
  }

  private String getMessage(ByteBuf buf) {
    byte[] con = new byte[buf.readableBytes()];
    buf.readBytes(con);
    try {
      return new String(con, Charset.forName("GBK"));
    } catch (Exception e) {
      System.out.println("trans bytes to string error. ");
      e.printStackTrace();
      return null;
    }
  }
}

在这里插入图片描述

     ChannelPipeline pipeline = ch.pipeline();
          pipeline.addLast(new ServerChannelHandlerSimple());
        }
      });
      System.out.println("netty服务器在[" + port + "]端口启动监听");
      ChannelFuture f = serverBootstrap.bind(port).sync();
      f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
      System.out.println("[出现异常] 释放资源");
      work.shutdownGracefully();
    }
  }

  private static int getPort() {
    Double port = (Math.random() + 1) * 10000;
    return port.intValue();
  }

  public static void main(String[] args) {
    NettyServerListenerSimple nsl = new NettyServerListenerSimple();
    nsl.start();
  }
}

在这里插入图片描述

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.nio.charset.Charset;

/**
 * 服务端的通道适配器
 */
public class ServerChannelHandlerSimple extends ChannelInboundHandlerAdapter {

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    System.out.println("error.");
    cause.printStackTrace();
    ctx.close();
  }

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) {
    // 具体处理客户端的数据信息
    System.out.println("receive message. ");
    ByteBuf buf = (ByteBuf) msg;
    String rev = getMessage(buf);
    System.out.println(rev);
  }

  private String getMessage(ByteBuf buf) {
    byte[] con = new byte[buf.readableBytes()];
    buf.readBytes(con);
    try {
      return new String(con, Charset.forName("GBK"));
    } catch (Exception e) {
      System.out.println("trans bytes to string error. ");
      e.printStackTrace();
      return null;
    }
  }
}

在这里插入图片描述
在这里插入图片描述
部署实现自己的netty 客户端

package com.youkeda.test.netty.handler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.nio.charset.Charset;
public class ServerChannelHandlerSimple extends ChannelInboundHandlerAdapter {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("error.");
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 具体处理客户端的数据信息
        System.out.println("receive message. ");
        ByteBuf buf = (ByteBuf) msg;
        String rev = getMessage(buf);
        System.out.println(rev);
    }

    private String getMessage(ByteBuf buf) {
        byte[] con = new byte[buf.readableBytes()];
        buf.readBytes(con);
        try {
            return new String(con, Charset.forName("GBK"));
        } catch (Exception e) {
            System.out.println("trans bytes to string error. ");
            e.printStackTrace();
            return null;
        }
    }
}

package com.youkeda.test.netty.server;
import com.youkeda.test.netty.handler.ServerChannelHandlerSimple;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
public class NettyServerListenerSimple {

/**
 * 创建bootstrap
 */
private static final ServerBootstrap serverBootstrap = new ServerBootstrap();

/**
 * Worker
 */
private static final EventLoopGroup work = new NioEventLoopGroup();

/**
 * 端口号
 */
private int port = getPort();

/**
 * 关闭服务器方法
 */
public void close() {
    System.out.println("关闭服务器....");
    //优雅退出
    work.shutdownGracefully();
}

/**
 * 开启及服务线程
 */
public void start() {
    serverBootstrap.group(work)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100)
            .handler(new LoggingHandler(LogLevel.INFO));
    try {
        //设置事件处理
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new ServerChannelHandlerSimple());
            }
        });
        System.out.println("netty服务器在[" + port + "]端口启动监听");
        ChannelFuture f = serverBootstrap.bind(port);
        f.channel().closeFuture();
    } catch (Exception e) {
        System.out.println("[出现异常] 释放资源");
    } finally {
        close();
    }
}

private static int getPort() {
    Double port = (Math.random() + 1) * 10000;
    return port.intValue();
}

public static void main(String[] args) {
    NettyServerListenerSimple nsl = new NettyServerListenerSimple();
    nsl.start();
}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值