Netty

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Netty相关的知识,希望对你有一定的参考价值。

  首先值得注意的是netty的jar包版本问题,版本不同,运用的方式也不同。我这里用4.0版本。

  对于小白来说,netty到底是什么,我就没必要在这里阐明了,因为百度上比我描述的更全面。

  这里就直接开门见山,代码走起。。。

 1 import io.netty.bootstrap.ServerBootstrap;
 2 import io.netty.channel.ChannelFuture;
 3 import io.netty.channel.ChannelInitializer;
 4 import io.netty.channel.ChannelOption;
 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.NioserverSocketChannel;
 9 
10 /**
11  * 服务器
12  */
13 public class NettyServer {
14     private final int port = 8989;
15     
16     
17     public static void main(String[] args) {
18         new NettyServer().nettyServer();
19     }
20     
21     public void nettyServer(){
22         EventLoopGroup bossGroup = new NioEventLoopGroup();
23         EventLoopGroup workerGroup = new NioEventLoopGroup();
24         
25         
26         try {
27             ServerBootstrap serverBootStrap = new ServerBootstrap();
28             
29             serverBootStrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
30             .option(ChannelOption.SO_BACKLOG, 1024)
31             .childHandler(new ChildChannelHandler());
32             
33             
34             ChannelFuture futrue = serverBootStrap.bind(port).sync();
35             futrue.channel().closeFuture().sync();
36             
37         } catch (Exception e) {
38             // TODO: handle exception
39         }
40     }
41     
42     private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{
43 
44         @Override
45         protected void initChannel(SocketChannel ch) throws Exception {
46             ch.pipeline().addLast(new SimpleServerHandler());
47         }
48         
49     }
50 }
 1 import java.util.Scanner;
 2 
 3 import io.netty.buffer.ByteBuf;
 4 import io.netty.buffer.Unpooled;
 5 import io.netty.channel.ChannelHandlerContext;
 6 import io.netty.channel.ChannelInboundHandlerAdapter;
 7 
 8 
 9 public class SimpleServerHandler extends ChannelInboundHandlerAdapter {
10 
11     
12     @Override
13     public void channelActive(ChannelHandlerContext ctx) throws Exception {
14         
15         ChannelManager.serverChannel = ctx;
16         
17         new Thread(new Runnable() {
18             
19             @Override
20             public void run() {
21                 // TODO Auto-generated method stub
22                 while(true){
23                     
24                     Scanner sc = new Scanner(System.in);
25                     byte [] req = sc.nextLine().getBytes();
26                     ByteBuf msg = Unpooled.buffer(req.length);
27                     msg.writeBytes(req);
28                     ChannelManager.serverChannel.writeAndFlush(msg);
29                 }
30             }
31         }).start();
32     }
33 
34     
35     @Override
36     public void channelRead(ChannelHandlerContext ctx, Object msg)
37             throws Exception {
38         ByteBuf buf = (ByteBuf) msg;
39         byte [] req = new byte[buf.readableBytes()];
40         
41         buf.readBytes(req);
42         String message = new String(req,"UTF-8");
43         System.out.println("server:"+message);
44     }
45     
46 }

  上述两个类实现netty的服务端,下面就是客户端啦

 1 import io.netty.bootstrap.Bootstrap;
 2 import io.netty.channel.ChannelFuture;
 3 import io.netty.channel.ChannelInitializer;
 4 import io.netty.channel.ChannelOption;
 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 
11 public class NettyClient {
12     
13     public static void main(String[] args) {
14         new NettyClient().connect(8989, "127.0.0.1");
15     }
16     
17     public void connect(int port, String host){
18         EventLoopGroup  group = new NioEventLoopGroup();
19         
20         try {
21             Bootstrap bootstrap = new Bootstrap();
22             bootstrap.group(group)
23             .channel(NioSocketChannel.class)
24             .option(ChannelOption.TCP_NODELAY, true)
25             .handler(new ChannelInitializer<SocketChannel>() {
26 
27                 @Override
28                 protected void initChannel(SocketChannel ch) throws Exception {
29                     // TODO Auto-generated method stub
30                     ch.pipeline().addLast(new SimpleClientHandler());
31                 }
32                 
33             });
34             ChannelFuture channelFuture = bootstrap.connect(host,port).sync();
35             channelFuture.channel().closeFuture().sync();
36             
37         } catch (Exception e) {
38             // TODO: handle exception
39         }
40     }
41 }
 1 import java.util.Scanner;
 2 
 3 import io.netty.buffer.ByteBuf;
 4 import io.netty.buffer.Unpooled;
 5 import io.netty.channel.ChannelHandlerContext;
 6 import io.netty.channel.ChannelInboundHandlerAdapter;
 7 
 8 
 9 public class SimpleClientHandler extends ChannelInboundHandlerAdapter {
10 
11     private ByteBuf clientMessage;
12     
13     public SimpleClientHandler(){
14         byte [] req = "call-user-service".getBytes();
15         clientMessage = Unpooled.buffer(req.length);
16         clientMessage.writeBytes(req);
17     }
18 
19     
20     @Override
21     public void channelActive(ChannelHandlerContext ctx) throws Exception {
22         
23         ChannelManager.clientChannel = ctx;
24         
25         new Thread(new Runnable() {
26             
27             @Override
28             public void run() {
29                 // TODO Auto-generated method stub
30                 while(true){
31                     
32                     Scanner sc = new Scanner(System.in);
33                     byte [] req = sc.nextLine().getBytes();
34                     ByteBuf msg = Unpooled.buffer(req.length);
35                     msg.writeBytes(req);
36                     ChannelManager.clientChannel.writeAndFlush(msg);
37                 }
38             }
39         }).start();
40     }
41 
42     @Override
43     public void channelRead(ChannelHandlerContext ctx, Object msg)
44             throws Exception {
45         ByteBuf buf = (ByteBuf) msg;
46         byte [] req = new byte[buf.readableBytes()];
47         buf.readBytes(req);
48         
49         String message = new String(req,"UTF-8");
50         System.out.println("client:"+message);
51     }
52 
53     @Override
54     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
55             throws Exception {
56         ctx.close();
57     }
58     
59     
60     
61 }

  好了,万事俱备,再添加一个ChannelManager.java netty的通道管理器

1 import io.netty.channel.ChannelHandlerContext;
2 
3 
4 public class ChannelManager {
5     
6     public static ChannelHandlerContext serverChannel;
7     public static ChannelHandlerContext clientChannel;
8 }

这样就可以实现netty的前后端的控制台通讯了,代码解释就不进行了

以上是关于Netty的主要内容,如果未能解决你的问题,请参考以下文章

Netty入门学习

Netty入门学习

Netty系列三Netty实战篇

Netty入门——Future和Promise接口

Java线程池详解

Netty图文解析+代码Demo