在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Netty学习笔记(一)

2016-12-16 12:53| 发布者: zhangjf| 查看: 534| 评论: 0

摘要: Netty是一个高性能 事件驱动的异步的非堵塞的IO(NIO)框架,用于建立TCP等底层的连接,基于Netty可以建立高性能的Http服务器。1、首先来复习下非堵塞IO(NIO)NIO这个库是在JDK1.4中才引入的。NIO和IO有相同的作用和目 ...

Netty是一个高性能 事件驱动的异步的非堵塞的IO(NIO)框架,用于建立TCP等底层的连接,基于Netty可以建立高性能的Http服务器。
1、首先来复习下非堵塞IO(NIO)
NIO这个库是在JDK1.4中才引入的。NIO和IO有相同的作用和目的,但实现方式不同,NIO主要用到的是块,所以NIO的效率要比IO高很多。
在Java API中提供了两套NIO,一套是针对标准输入输出NIO,另一套就是网络编程NIO。
*BufferChannel是标准NIO中的核心对象*
Channel是对原IO中流的模拟,任何来源和目的数据都必须通过一个Channel对象。一个Buffer实质上是一个容器对象,发给Channel的所有对象都必须先放到Buffer中;同样的,从Channel中读取的任何数据都要读到Buffer中。


网络编程NIO中还有一个核心对象Selector,它可以注册到很多个Channel上,监听各个Channel上发生的事件,并且能够根据事件情况决定Channel读写。这样,通过一个线程管理多个Channel,就可以处理大量网络连接了。

Selector 就是注册对各种 I/O 事件兴趣的地方,而且当那些事件发生时,就是这个对象告诉你所发生的事件。
Selector selector = Selector.open(); //创建一个selector
为了能让Channel和Selector配合使用,我们需要把Channel注册到Selector上。通过调用channel.register()方法来实现注册:
channel.configureBlocking(false); //设置成异步IO
SelectionKey key =channel.register(selector,SelectionKey.OP_READ); //对所关心的事件进行注册(connet,accept,read,write)
SelectionKey 代表这个通道在此 Selector 上的这个注册。

2、异步
CallBack:回调是异步处理经常用到的编程模式,回调函数通常被绑定到一个方法上,并且在方法完成之后才执行,这种处理方式在javascript当中得到了充分的运用。回调给我们带来的难题是当一个问题处理过程中涉及很多回调时,代码是很难读的。
Futures:Futures是一种抽象,它代表一个事情的执行过程中的一些关键点,我们通过Future就可以知道任务的执行情况,比如当任务没完成时我们可以做一些其它事情。它给我们带来的难题是我们需要去判断future的值来确定任务的执行状态。
3、netty到底怎么工作的呢?
直接来看个最简单的实例

服务器端

  1. public class EchoServer {
  2. private final static int port = 8007;
  3. public void start() throws InterruptedException{
  4. ServerBootstrap bootstrap = new ServerBootstrap(); //引导辅助程序
  5. EventLoopGroup group = new NioEventLoopGroup(); //通过nio的方式接受连接和处理连接
  6. try {
  7. bootstrap.group(group)
  8. .channel(NioServerSocketChannel.class) //设置nio类型的channel
  9. .localAddress(new InetSocketAddress(port)) //设置监听端口
  10. .childHandler(new ChannelInitializer<SocketChannel>() { //有连接到达时会创建一个channel
  11. // pipline 管理channel中的handler,在channel队列中添加一个handler来处理业务
  12. @Override
  13. protected void initChannel(SocketChannel ch) throws Exception {
  14. ch.pipeline().addLast("myHandler", new EchoServerHandler());
  15. //ch.pipeline().addLast("idleStateHandler",new IdleStateHandler(0, 0, 180));
  16. }
  17. });
  18. ChannelFuture future = bootstrap.bind().sync(); //配置完成,绑定server,并通过sync同步方法阻塞直到绑定成功
  19. System.out.println(EchoServer.class.getName() + " started and listen on " + future.channel().localAddress());
  20. future.channel().closeFuture().sync(); //应用程序会一直等待,直到channel关闭
  21. } catch (Exception e) {
  22. e.getMessage();
  23. }finally {
  24. group.shutdownGracefully().sync();
  25. }
  26. }
复制代码

创建一个ServerBootstrap实例

创建一个EventLoopGroup来处理各种事件,如处理链接请求,发送接收数据等。

定义本地InetSocketAddress( port)好让Server绑定

创建childHandler来处理每一个链接请求

所有准备好之后调用ServerBootstrap.bind()方法绑定Server

handler 处理核心业务

  1. @Sharable //注解@Sharable可以让它在channels间共享
  2. public class EchoServerHandler extends ChannelInboundHandlerAdapter{
  3. @Override
  4. public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception {
  5. ByteBuf buf = ctx.alloc().buffer();
  6. buf.writeBytes("Hello World".getBytes());
  7. ctx.write(buf);
  8. }
  9. @Override
  10. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  11. ctx.flush();
  12. }
  13. @Override
  14. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  15. cause.printStackTrace();
  16. ctx.close();
  17. }
  18. }
复制代码

客户端 连接

  1. public class EchoClient {
  2. private final int port;
  3. private final String hostIp;
  4. public EchoClient(int port, String hostIp) {
  5. this.port = port;
  6. this.hostIp = hostIp;
  7. }
  8. public void start() throws InterruptedException {
  9. Bootstrap bootstrap = new Bootstrap();
  10. EventLoopGroup group = new NioEventLoopGroup();
  11. try {
  12. bootstrap.group(group).channel(NioSocketChannel.class)
  13. .remoteAddress(new InetSocketAddress(hostIp, port))
  14. .handler(new ChannelInitializer<SocketChannel>() {
  15. @Override
  16. protected void initChannel(SocketChannel ch) throws Exception {
  17. ch.pipeline().addLast(new EchoClientHandler());
  18. }
  19. });
  20. ChannelFuture future = bootstrap.connect().sync();
  21. future.addListener(new ChannelFutureListener() {
  22. public void operationComplete(ChannelFuture future) throws Exception {
  23. if (future.isSuccess()) {
  24. System.out.println("client connected");
  25. } else {
  26. System.out.println("server attemp failed");
  27. future.cause().printStackTrace();
  28. }
  29. }
  30. });
  31. future.channel().closeFuture().sync();
  32. } catch (InterruptedException e) {
  33. e.printStackTrace();
  34. } finally {
  35. group.shutdownGracefully().sync();
  36. }
  37. }
复制代码

客户端handler

  1. @Sharable
  2. public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf>{
  3. /**
  4. *此方法会在连接到服务器后被调用
  5. * */
  6. public void channelActive(ChannelHandlerContext ctx) {
  7. System.out.println("Netty rocks!");
  8. ctx.write(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
  9. }
  10. /**
  11. * 接收到服务器数据时调用
  12. */
  13. @Override
  14. protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
  15. System.out.println("Client received: " + ByteBufUtil.hexDump(msg.readBytes(msg.readableBytes())));
  16. }
  17. /**
  18. *捕捉到异常
  19. * */
  20. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
  21. cause.printStackTrace();
  22. ctx.close();
  23. }
  24. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-7 18:07

Copyright 2015-2025 djqfx

返回顶部