netty初认识



  1. packageme.hello.netty;
  2. importorg.jboss.netty.bootstrap.ServerBootstrap;
  3. importorg.jboss.netty.channel.*;
  4. importorg.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
  5. importorg.jboss.netty.handler.codec.string.StringDecoder;
  6. importorg.jboss.netty.handler.codec.string.StringEncoder;
  7. importjava.net.InetSocketAddress;
  8. importjava.util.concurrent.Executors;
  9. /**
  10. *GodBlessYou!
  11. *Author:Fangniude
  12. *Date:2013-07-15
  13. */
  14. publicclassNettyServer{
  15. publicstaticvoidmain(String[]args){
  16. ServerBootstrapbootstrap=newServerBootstrap(newNioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool()));
  17. //Setupthedefaulteventpipeline.
  18. bootstrap.setPipelineFactory(newChannelPipelineFactory(){
  19. @Override
  20. publicChannelPipelinegetPipeline()throwsException{
  21. returnChannels.pipeline(newStringDecoder(),newStringEncoder(),newServerHandler());
  22. }
  23. });
  24. //Bindandstarttoacceptincomingconnections.
  25. Channelbind=bootstrap.bind(newInetSocketAddress(8000));
  26. System.out.println("Server已经启动,监听端口:"+bind.getLocalAddress()+",等待客户端注册。。。");
  27. }
  28. privatestaticclassServerHandlerextendsSimpleChannelHandler{
  29. @Override
  30. publicvoidmessageReceived(ChannelHandlerContextctx,MessageEvente)throwsException{
  31. if(e.getMessage()instanceofString){
  32. Stringmessage=(String)e.getMessage();
  33. System.out.println("Client发来:"+message);
  34. e.getChannel().write("Server已收到刚发送的:"+message);
  35. System.out.println("\n等待客户端输入。。。");
  36. }
  37. super.messageReceived(ctx,e);
  38. }
  39. @Override
  40. publicvoidexceptionCaught(ChannelHandlerContextctx,ExceptionEvente)throwsException{
  41. super.exceptionCaught(ctx,e);
  42. }
  43. @Override
  44. publicvoidchannelConnected(ChannelHandlerContextctx,ChannelStateEvente)throwsException{
  45. System.out.println("有一个客户端注册上来了。。。");
  46. System.out.println("Client:"+e.getChannel().getRemoteAddress());
  47. System.out.println("Server:"+e.getChannel().getLocalAddress());
  48. System.out.println("\n等待客户端输入。。。");
  49. super.channelConnected(ctx,e);
  50. }
  51. }
  52. }

客户端:

Java代码 技术分享

  1. packageme.hello.netty;
  2. importorg.jboss.netty.bootstrap.ClientBootstrap;
  3. importorg.jboss.netty.channel.*;
  4. importorg.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
  5. importorg.jboss.netty.handler.codec.string.StringDecoder;
  6. importorg.jboss.netty.handler.codec.string.StringEncoder;
  7. importjava.io.BufferedReader;
  8. importjava.io.InputStreamReader;
  9. importjava.net.InetSocketAddress;
  10. importjava.util.concurrent.Executors;
  11. /**
  12. *GodBlessYou!
  13. *Author:Fangniude
  14. *Date:2013-07-15
  15. */
  16. publicclassNettyClient{
  17. publicstaticvoidmain(String[]args){
  18. //Configuretheclient.
  19. ClientBootstrapbootstrap=newClientBootstrap(newNioClientSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool()));
  20. //Setupthedefaulteventpipeline.
  21. bootstrap.setPipelineFactory(newChannelPipelineFactory(){
  22. @Override
  23. publicChannelPipelinegetPipeline()throwsException{
  24. returnChannels.pipeline(newStringDecoder(),newStringEncoder(),newClientHandler());
  25. }
  26. });
  27. //Starttheconnectionattempt.
  28. ChannelFuturefuture=bootstrap.connect(newInetSocketAddress("localhost",8000));
  29. //Waituntiltheconnectionisclosedortheconnectionattemptfails.
  30. future.getChannel().getCloseFuture().awaitUninterruptibly();
  31. //Shutdownthreadpoolstoexit.
  32. bootstrap.releaseExternalResources();
  33. }
  34. privatestaticclassClientHandlerextendsSimpleChannelHandler{
  35. privateBufferedReadersin=newBufferedReader(newInputStreamReader(System.in));
  36. @Override
  37. publicvoidmessageReceived(ChannelHandlerContextctx,MessageEvente)throwsException{
  38. if(e.getMessage()instanceofString){
  39. Stringmessage=(String)e.getMessage();
  40. System.out.println(message);
  41. e.getChannel().write(sin.readLine());
  42. System.out.println("\n等待客户端输入。。。");
  43. }
  44. super.messageReceived(ctx,e);
  45. }
  46. @Override
  47. publicvoidchannelConnected(ChannelHandlerContextctx,ChannelStateEvente)throwsException{
  48. System.out.println("已经与Server建立连接。。。。");
  49. System.out.println("\n请输入要发送的信息:");
  50. super.channelConnected(ctx,e);
  51. e.getChannel().write(sin.readLine());
  52. }
  53. }
  54. }

Netty整体架构


技术分享

Netty组件

ChannelFactory

Boss

Worker

Channel

ChannelEvent

Pipeline

ChannelContext

Handler

Sink

Server端核心类

NioServerSocketChannelFactory

NioServerBossPool

NioWorkerPool

NioServerBoss

NioWorker

NioServerSocketChannel

NioAcceptedSocketChannel

DefaultChannelPipeline

NioServerSocketPipelineSink

Channels

ChannelFactory

Channel工厂,很重要的类

保存启动的相关参数

NioServerSocketChannelFactory

NioClientSocketChannelFactory

NioDatagramChannelFactory

这是Nio的,还有Oio和Local的

SelectorPool

Selector的线程池

NioServerBossPool 默认线程数:1

NioClientBossPool 1

NioWorkerPool 2 * Processor

NioDatagramWorkerPool

Selector

选择器,很核心的组件

NioServerBoss

NioClientBoss

NioWorker

NioDatagramWorker

Channel

通道

NioServerSocketChannel

NioClientSocketChannel

NioAcceptedSocketChannel

NioDatagramChannel

Sink

负责和底层的交互

如bind,Write,Close等

NioServerSocketPipelineSink

NioClientSocketPipelineSink

NioDatagramPipelineSink

Pipeline

负责维护所有的Handler

ChannelContext

一个Channel一个,是Handler和Pipeline的中间件

Handler

对Channel事件的处理器

ChannelPipeline


技术分享

技术分享

优秀的设计----事件驱动


技术分享

优秀的设计----线程模型


技术分享

注意事项

解码时的Position

Channel的关闭

更多Handler

Channel的关闭

用完的Channel,可以直接关闭;

1、ChannelFuture加Listener

2、writeComplete

一段时间没用,也可以关闭

TimeoutHandler

转自: http://lippeng.iteye.com/blog/1907279

netty初认识

原文地址:http://www.cnblogs.com/xifenglou/p/7261356.html


最新回复(0)
/jishu_2BvDNQPtz7KOI4AEcFXLC6aWFPknfxMQzQbdn2_2Bl07So_3D4719342
8 简首页