1. 程式人生 > 實用技巧 >Netty 入門

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