netty demo

Netty 4.0 demo

 

netty是一個異步,事件驅動的網絡編程框架&工具,使用netty,能夠快速開發從可維護,高性能的協議服務和客戶端應用。是一個繼mina以後,一個很是受歡迎的nio網絡框架html

 

netty4.x和以前的版本變化很大,包結構、對象和以前有很大不一樣。原來的包結構都是org.jboss.netty.*;目前改成了io.netty.* 的方式,其中,server,client的對象也和原來不一樣了java

 

根據4.x的穩定版本4.0.14爲藍本,寫一個hello world試試看。值得注意的是,4.0.x的beta版和final版本也有不小調整。很不幸的時,在4.x中剛出現的部分方法,到5.x中也將廢棄。哎,苦逼的IT人。廢話不說,看個4.x的例子吧編程

須要說明的是,我用的是netty4.0.13這個版本。由於netty有不少包,你們能夠引入這個all包,其餘的就所有包括了。bootstrap

server端代碼:服務器

複製代碼
 1 package netty.test;
 2 
 3 
 4 import io.netty.bootstrap.ServerBootstrap;
 5 import io.netty.channel.Channel;
 6 import io.netty.channel.ChannelFuture;
 7 import io.netty.channel.ChannelInitializer;
 8 import io.netty.channel.ChannelPipeline;
 9 import io.netty.channel.EventLoopGroup;
10 import io.netty.channel.nio.NioEventLoopGroup;
11 import io.netty.channel.socket.nio.NioServerSocketChannel;
12 import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
13 import io.netty.handler.codec.LengthFieldPrepender;
14 import io.netty.handler.codec.string.StringDecoder;
15 import io.netty.handler.codec.string.StringEncoder;
16 import io.netty.util.CharsetUtil;
17 
18 public class MyNettyServer {
19     private static final String IP = "127.0.0.1";
20     private static final int PORT = 5656;
21     private static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors()*2;
22     
23     private static final int BIZTHREADSIZE = 100;
24     private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
25     private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
26     public static void service() throws Exception {
27         ServerBootstrap bootstrap = new ServerBootstrap();
28         bootstrap.group(bossGroup, workerGroup);
29         bootstrap.channel(NioServerSocketChannel.class);
30         bootstrap.childHandler(new ChannelInitializer<Channel>() {
31 
32             @Override
33             protected void initChannel(Channel ch) throws Exception {
34                 // TODO Auto-generated method stub
35                 ChannelPipeline pipeline = ch.pipeline();
36                  pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
37                     pipeline.addLast(new LengthFieldPrepender(4));
38                     pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
39                     pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
40                     pipeline.addLast(new TcpServerHandler());
41             }
42             
43         });
44           ChannelFuture f = bootstrap.bind(IP, PORT).sync();
45             f.channel().closeFuture().sync();
46             System.out.println("TCP服務器已啓動");
47         }
48 
49         protected static void shutdown() {
50             workerGroup.shutdownGracefully();
51             bossGroup.shutdownGracefully();
52         }
53 
54         public static void main(String[] args) throws Exception {
55             System.out.println("開始啓動TCP服務器...");
56             MyNettyServer.service();
57 //            HelloServer.shutdown();
58         }
59 }
複製代碼

對應的Handler對象 TcpServerHandler.java網絡

複製代碼
 1 package netty.test;
 2 
 3 import io.netty.channel.ChannelHandlerAdapter;
 4 import io.netty.channel.ChannelHandlerContext;
 5 import io.netty.channel.ChannelInboundHandlerAdapter;
 6 
 7 public class TcpServerHandler extends ChannelInboundHandlerAdapter {
 8     
 9     
10     @Override
11     public void channelRead(ChannelHandlerContext ctx, Object msg)
12             throws Exception {
13         // TODO Auto-generated method stub
14         System.out.println("server receive message :"+ msg);
15         ctx.channel().writeAndFlush("yes server already accept your message" + msg);
16         ctx.close();
17     }
18     @Override
19     public void channelActive(ChannelHandlerContext ctx) throws Exception {
20         // TODO Auto-generated method stub
21         System.out.println("channelActive>>>>>>>>");
22     }
23       @Override
24    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
25         System.out.println("exception is general");
26     }
27 }
複製代碼

客戶端代碼:框架

複製代碼
 1 package netty.test;
 2 
 3 import io.netty.bootstrap.Bootstrap;
 4 import io.netty.channel.ChannelFuture;
 5 import io.netty.channel.ChannelInitializer;
 6 import io.netty.channel.ChannelOption;
 7 import io.netty.channel.ChannelPipeline;
 8 import io.netty.channel.EventLoopGroup;
 9 import io.netty.channel.nio.NioEventLoopGroup;
10 import io.netty.channel.socket.SocketChannel;
11 import io.netty.channel.socket.nio.NioSocketChannel;
12 import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
13 import io.netty.handler.codec.LengthFieldPrepender;
14 import io.netty.handler.codec.string.StringDecoder;
15 import io.netty.handler.codec.string.StringEncoder;
16 import io.netty.util.CharsetUtil;
17 
18 public class NettyClient implements Runnable {
19     
20     @Override
21      public void run() {
22             EventLoopGroup group = new NioEventLoopGroup();
23             try {
24                 Bootstrap b = new Bootstrap();
25                 b.group(group);
26                 b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
27                 b.handler(new ChannelInitializer<SocketChannel>() {
28                     @Override
29                     protected void initChannel(SocketChannel ch) throws Exception {
30                         ChannelPipeline pipeline = ch.pipeline();
31                         pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
32                         pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
33                         pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
34                         pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
35 
36                         pipeline.addLast("handler", new HelloClient());
37                     }
38                 });
39                 for (int i = 0; i < 100000; i++) {
40                      ChannelFuture f = b.connect("127.0.0.1", 5656).sync();
41                      f.channel().writeAndFlush("hello Service!"+Thread.currentThread().getName()+":--->:"+i);
42                      f.channel().closeFuture().sync();
43                 }
44                
45 
46             } catch (Exception e) {
47 
48             } finally {
49                 group.shutdownGracefully();
50             }
51         }
52 
53         public static void main(String[] args) throws Exception {
54             for (int i = 0; i < 1000; i++) {
55                 new Thread(new NettyClient(),">>>this thread "+i).start();
56             }
57         }
58 }
複製代碼

客戶端對應的Handler對象代碼,HelloClient.java異步

複製代碼
package netty.test;

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

public class HelloClient extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("client接收到服務器返回的消息:" + msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("client exception is general");
    }
}
複製代碼
相關文章
相關標籤/搜索