zoukankan      html  css  js  c++  java
  • Netty 入门

      Netty是一个nio的框架。但是对于新学习的同学来说,netty有点不太好入手。这里写个小demo,实现一个比较简单的netty的服务端和客户端。

      Netty 大概有几个模块:

      服务端:

      1.服务端的接入类。用于创建和接收相应的传入信息。2.handler 用于对请求进行实际处理。

      客户端:

      1.客户端接入,用于创建接入连接。 2.handler 用于接收服务端的返回内容。

      代码如下:  

     1 import io.netty.bootstrap.ServerBootstrap;
     2 import io.netty.channel.ChannelFuture;
     3 import io.netty.channel.ChannelInitializer;
     4 import io.netty.channel.EventLoopGroup;
     5 import io.netty.channel.nio.NioEventLoopGroup;
     6 import io.netty.channel.socket.SocketChannel;
     7 import io.netty.channel.socket.nio.NioServerSocketChannel;
     8 
     9 public class Server {
    10 
    11     public static void main(String[] args) throws Exception {
    12         //1 第一个线程组 是用于接收Client端连接的
    13         EventLoopGroup bossGroup = new NioEventLoopGroup();
    14         //2 第二个线程组 是用于实际的业务处理操作的
    15         EventLoopGroup workerGroup = new NioEventLoopGroup();
    16         
    17         //3 创建一个辅助类Bootstrap,就是对我们的Server进行一系列的配置
    18 
    19         ServerBootstrap b = new ServerBootstrap();
    20         //把俩个工作线程组加入进来
    21         b.group(bossGroup, workerGroup)
    22         //我要指定使用NioServerSocketChannel这种类型的通道
    23          .channel(NioServerSocketChannel.class)
    24         //一定要使用 childHandler 去绑定具体的 事件处理器
    25          .childHandler(new ChannelInitializer<SocketChannel>() {
    26             @Override
    27             protected void initChannel(SocketChannel sc) throws Exception {
    28                 sc.pipeline().addLast(new ServerHandler());
    29             }
    30         });
    31 
    32         //绑定指定的端口 进行监听
    33         ChannelFuture f = b.bind(8765).sync(); 
    34         
    35         //Thread.sleep(1000000);
    36         f.channel().closeFuture().sync();
    37         
    38         bossGroup.shutdownGracefully();
    39         workerGroup.shutdownGracefully();
    40          
    41         
    42         
    43     }
    44     
    45 }
    服务端代码 service类
     1 import io.netty.buffer.ByteBuf;
     2 import io.netty.buffer.Unpooled;
     3 import io.netty.channel.ChannelHandlerAdapter;
     4 import io.netty.channel.ChannelHandlerContext;
     5 
     6 
     7 public class ServerHandler  extends ChannelHandlerAdapter {
     8 
     9     @Override
    10     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    11     
    12             //do something msg
    13             ByteBuf buf = (ByteBuf)msg;
    14             byte[] data = new byte[buf.readableBytes()];
    15             buf.readBytes(data);
    16             String request = new String(data, "utf-8");
    17             System.out.println("Server: " + request);
    18             //写给客户端
    19             String response = "我是反馈的信息";
    20             ctx.writeAndFlush(Unpooled.copiedBuffer("888".getBytes()));
    21             //.addListener(ChannelFutureListener.CLOSE);
    22             
    23 
    24     }
    25 
    26     @Override
    27     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    28         cause.printStackTrace();
    29         ctx.close();
    30     }
    31 
    32 }
    服务端handler
     1 import io.netty.bootstrap.Bootstrap;
     2 import io.netty.buffer.Unpooled;
     3 import io.netty.channel.ChannelFuture;
     4 import io.netty.channel.ChannelInitializer;
     5 import io.netty.channel.EventLoopGroup;
     6 import io.netty.channel.nio.NioEventLoopGroup;
     7 import io.netty.channel.socket.SocketChannel;
     8 import io.netty.channel.socket.nio.NioSocketChannel;
     9 
    10 public class Client {
    11 
    12     public static void main(String[] args) throws Exception {
    13         
    14         EventLoopGroup workgroup = new NioEventLoopGroup();
    15         Bootstrap b = new Bootstrap();
    16         b.group(workgroup)
    17         .channel(NioSocketChannel.class)
    18         .handler(new ChannelInitializer<SocketChannel>() {
    19             @Override
    20             protected void initChannel(SocketChannel sc) throws Exception {
    21                 sc.pipeline().addLast(new ClientHandler());
    22             }
    23         });
    24         
    25         ChannelFuture cf1 = b.connect("127.0.0.1", 8765).sync();
    26         
    27         //buf
    28         cf1.channel().writeAndFlush(Unpooled.copiedBuffer("777".getBytes()));
    29         
    30         cf1.channel().closeFuture().sync();
    31         workgroup.shutdownGracefully();
    32         
    33     }
    34 }
    客户端 Client
     1 import io.netty.buffer.ByteBuf;
     2 import io.netty.channel.ChannelHandlerAdapter;
     3 import io.netty.channel.ChannelHandlerContext;
     4 import io.netty.util.ReferenceCountUtil;
     5 
     6 public class ClientHandler extends ChannelHandlerAdapter {
     7 
     8     @Override
     9     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    10         try {
    11             //do something msg
    12             ByteBuf buf = (ByteBuf)msg;
    13             byte[] data = new byte[buf.readableBytes()];
    14             buf.readBytes(data);
    15             String request = new String(data, "utf-8");
    16             System.out.println("Client: " + request);
    17             
    18             
    19         } finally {
    20             ReferenceCountUtil.release(msg);
    21         }
    22     }
    23 
    24     @Override
    25     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    26         cause.printStackTrace();
    27         ctx.close();
    28     }
    29 
    30 }
    客户端 Handler

  • 相关阅读:
    spark 脚本示例
    R树的应用
    将博客搬至CSDN
    select
    注册页面的验证码的实现
    web项目.注册及登陆
    eclipse web 项目中遇到的问题总结
    Apache与Tomcat
    关于MVC整理
    JDBC
  • 原文地址:https://www.cnblogs.com/liyasong/p/netty.html
Copyright © 2011-2022 走看看