Netty学习1(入门demo)

朱雀 2020-11-17 10:31 748阅读 0赞

1.定义:

Netty是一个NIO客户端服务器网络框架,用于快速开发可维护性、高性能的网络应用。

2. HelloWorld

  • 一个简单的Netty程序,包含服务器端server和客户端client,下面直接上代码…
  • 1.pom

    1. <dependency>
    2. <groupId>io.netty</groupId>
    3. <artifactId>netty-all</artifactId>
    4. <version>4.1.19.Final</version>
    5. </dependency>
  • 2.NettyServer

    1. package Netty;
    2. import io.netty.bootstrap.ServerBootstrap;
    3. import io.netty.channel.ChannelFuture;
    4. import io.netty.channel.ChannelInitializer;
    5. import io.netty.channel.ChannelOption;
    6. import io.netty.channel.EventLoopGroup;
    7. import io.netty.channel.nio.NioEventLoopGroup;
    8. import io.netty.channel.socket.SocketChannel;
    9. import io.netty.channel.socket.nio.NioServerSocketChannel;
    10. import io.netty.handler.codec.string.StringDecoder;
    11. import io.netty.handler.codec.string.StringEncoder;
    12. import java.net.InetSocketAddress;
    13. public class NettyServer {
    14. public void start(int port){
    15. EventLoopGroup bossGroup = new NioEventLoopGroup(1); //boss线程组,接收传入的连接,并将连接分配给worker线程组
    16. EventLoopGroup workerGroup = new NioEventLoopGroup();
    17. try {
    18. ServerBootstrap bootstrap = new ServerBootstrap();
    19. bootstrap.group(bossGroup,workerGroup)
    20. .channel(NioServerSocketChannel.class) //在这里,我们指定使用NioServerSocketChannel类来实例化一个新的Channel(通道)来接受传入的连接。
    21. .childHandler(new ChannelInitializer<SocketChannel>() { //设置服务器处理程序
    22. protected void initChannel(SocketChannel ch) throws Exception {
    23. ch.pipeline().addLast("decoder", new StringDecoder());
    24. ch.pipeline().addLast("encoder", new StringEncoder());
    25. ch.pipeline().addLast(new NettyServerHandler()); //自定义handler
    26. };
    27. })
    28. .option(ChannelOption.SO_BACKLOG, 128)
    29. .childOption(ChannelOption.SO_KEEPALIVE, true);
    30. ChannelFuture future = bootstrap.bind(port).sync(); //启动服务器
    31. System.out.println("netty Server port : " + port );
    32. future.channel().closeFuture().sync();
    33. } catch (Exception e) {
    34. bossGroup.shutdownGracefully();
    35. workerGroup.shutdownGracefully();
    36. }
    37. }
    38. public static void main(String[] args) throws Exception {
    39. new NettyServer().start(8081);
    40. }
    41. }
  • 3.NettyServerHandler:
    ````
    package Netty;

    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;

    public class NettyServerHandler extends ChannelInboundHandlerAdapter{

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

    1. System.out.println("Netty server 激活...");
    2. }
  1. @Override
  2. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  3. System.out.println("Netty server 接收消息:"+ msg);
  4. ctx.write("hello too");
  5. ctx.flush();
  6. }
  7. @Override
  8. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  9. cause.printStackTrace();
  10. ctx.close();
  11. }
  12. }
  1. * 4.NettyClient
  1. package Netty;
  2. import io.netty.bootstrap.Bootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.ChannelInitializer;
  5. import io.netty.channel.ChannelOption;
  6. import io.netty.channel.ChannelPipeline;
  7. import io.netty.channel.EventLoopGroup;
  8. import io.netty.channel.nio.NioEventLoopGroup;
  9. import io.netty.channel.socket.SocketChannel;
  10. import io.netty.channel.socket.nio.NioSocketChannel;
  11. import io.netty.handler.codec.string.StringDecoder;
  12. import io.netty.handler.codec.string.StringEncoder;
  13. public class NettyClient {
  14. public void run(String host,int port) {
  15. EventLoopGroup group = new NioEventLoopGroup();
  16. try {
  17. Bootstrap b = new Bootstrap();
  18. b.group(group)
  19. .channel(NioSocketChannel.class)
  20. .option(ChannelOption.TCP_NODELAY, true)
  21. .handler(new ChannelInitializer<SocketChannel>() {
  22. @Override
  23. public void initChannel(SocketChannel ch) throws Exception {
  24. ChannelPipeline p = ch.pipeline();
  25. p.addLast("decoder", new StringDecoder());
  26. p.addLast("encoder", new StringEncoder());
  27. p.addLast(new NettyClientHandler());
  28. }
  29. });
  30. ChannelFuture future = null;
  31. try {
  32. future = b.connect(host, port).sync();
  33. } catch (InterruptedException e) {
  34. e.printStackTrace();
  35. }
  36. try {
  37. future.channel().closeFuture().sync();
  38. } catch (InterruptedException e) {
  39. e.printStackTrace();
  40. }
  41. } finally {
  42. group.shutdownGracefully();
  43. }
  44. }
  45. public static void main(String[] args) throws Exception {
  46. new NettyClient().run("127.0.0.1",8081);
  47. }
  48. }
  1. \-5. NettyClientHandler
  1. package Netty;
  2. import io.netty.channel.ChannelHandlerContext;
  3. import io.netty.channel.ChannelInboundHandlerAdapter;
  4. public class NettyClientHandler extends ChannelInboundHandlerAdapter{
  5. @Override
  6. public void channelActive(ChannelHandlerContext ctx) {
  7. System.out.println("netty client 启动...");
  8. ctx.channel().writeAndFlush("hello lin");
  9. }
  10. @Override
  11. public void channelRead(ChannelHandlerContext ctx, Object msg) {
  12. System.out.println("netty 服务器响应信息:"+msg);
  13. }
  14. @Override
  15. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
  16. cause.printStackTrace();
  17. ctx.close();
  18. }
  19. }

````

6.Netty 一些主要技术点:

bootstrap : netty 客户端程序的引入类
serverBootstrap:netty 服务端程序的引入类
channel : 连接主体
channelHandler:netty 的处理程序,包括数据的出站、入站、解码、编码、具体业务处理 …功能都在这里完成。
channelPipeline:存放channelHandler的容器
EvenLoop:线程,每个channel都会注册到EvenLoop上面执行
channelFuture:异步执行状态
解码器:将字节流转换成java对象
编码器:将java对象转换成字节流

发表评论

表情:
评论列表 (有 0 条评论,748人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Netty学习1(入门demo)

    1.定义: > Netty是一个NIO客户端服务器网络框架,用于快速开发可维护性、高性能的网络应用。 2. HelloWorld * 一个简单的Netty...