Netty使用实例

贴上两个自己写好的例子,以便备注,以下两个例子基于netty-3.5.7.Final.jar用Junit进行测试

第一个例子:简单的发送字符串,接收字符串“Hello, World”

Java代码 收藏代码
  1. packagecom.wujintao.netty;
  2. importjava.net.InetSocketAddress;
  3. importjava.util.concurrent.Executors;
  4. importorg.jboss.netty.bootstrap.ClientBootstrap;
  5. importorg.jboss.netty.bootstrap.ServerBootstrap;
  6. importorg.jboss.netty.channel.ChannelFuture;
  7. importorg.jboss.netty.channel.ChannelHandlerContext;
  8. importorg.jboss.netty.channel.ChannelPipeline;
  9. importorg.jboss.netty.channel.ChannelPipelineFactory;
  10. importorg.jboss.netty.channel.ChannelStateEvent;
  11. importorg.jboss.netty.channel.Channels;
  12. importorg.jboss.netty.channel.ExceptionEvent;
  13. importorg.jboss.netty.channel.MessageEvent;
  14. importorg.jboss.netty.channel.SimpleChannelHandler;
  15. importorg.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
  16. importorg.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
  17. importorg.jboss.netty.handler.codec.string.StringDecoder;
  18. importorg.jboss.netty.handler.codec.string.StringEncoder;
  19. importorg.junit.Test;
  20. classHelloWorldServerHandlerextendsSimpleChannelHandler{
  21. publicvoidchannelConnected(ChannelHandlerContextctx,ChannelStateEvente)
  22. throwsException{
  23. e.getChannel().write("Hello,World");
  24. }
  25. publicvoidexceptionCaught(ChannelHandlerContextctx,ExceptionEvente){
  26. System.out.println("Unexpectedexceptionfromdownstream."
  27. +e.getCause());
  28. e.getChannel().close();
  29. }
  30. }
  31. classHelloWorldClientHandlerextendsSimpleChannelHandler{
  32. publicvoidmessageReceived(ChannelHandlerContextctx,MessageEvente){
  33. Stringmessage=(String)e.getMessage();
  34. System.out.println(message);
  35. e.getChannel().close();
  36. }
  37. publicvoidexceptionCaught(ChannelHandlerContextctx,ExceptionEvente){
  38. System.out.println("Unexpectedexceptionfromdownstream."
  39. +e.getCause());
  40. e.getChannel().close();
  41. }
  42. }
  43. /**
  44. *NettyVSMinaNetty基于Pipeline处理,Mina基于Filter过滤
  45. *Netty的事件驱动模型具有更好的扩展性和易用性
  46. *Https,SSL,PB,RSTP,Text&Binary等协议支持
  47. *Netty中UDP传输有更好的支持官方测试Netty比Mina性能更好
  48. *@authorAdministrator
  49. *
  50. */
  51. publicclassTestCase{
  52. publicvoidtestServer(){
  53. //初始化channel的辅助类,为具体子类提供公共数据结构
  54. ServerBootstrapbootstrap=newServerBootstrap(
  55. newNioServerSocketChannelFactory(
  56. Executors.newCachedThreadPool(),
  57. Executors.newCachedThreadPool()));
  58. bootstrap.setPipelineFactory(newChannelPipelineFactory(){
  59. publicChannelPipelinegetPipeline(){
  60. ChannelPipelinepipeline=Channels.pipeline();
  61. pipeline.addLast("decoder",newStringDecoder());
  62. pipeline.addLast("encoder",newStringEncoder());
  63. pipeline.addLast("handler",newHelloWorldServerHandler());
  64. returnpipeline;
  65. }
  66. });
  67. //创建服务器端channel的辅助类,接收connection请求
  68. bootstrap.bind(newInetSocketAddress(8080));
  69. }
  70. publicvoidtestClient(){
  71. //创建客户端channel的辅助类,发起connection请求
  72. ClientBootstrapbootstrap=newClientBootstrap(
  73. newNioClientSocketChannelFactory(
  74. Executors.newCachedThreadPool(),
  75. Executors.newCachedThreadPool()));
  76. //ItmeansonesameHelloWorldClientHandlerinstanceisgoingtohandlemultipleChannelsandconsequentlythedatawillbecorrupted.
  77. //基于上面这个描述,必须用到ChannelPipelineFactory每次创建一个pipeline
  78. bootstrap.setPipelineFactory(newChannelPipelineFactory(){
  79. publicChannelPipelinegetPipeline(){
  80. ChannelPipelinepipeline=Channels.pipeline();
  81. pipeline.addLast("decoder",newStringDecoder());
  82. pipeline.addLast("encoder",newStringEncoder());
  83. pipeline.addLast("handler",newHelloWorldClientHandler());
  84. returnpipeline;
  85. }
  86. });
  87. //创建无连接传输channel的辅助类(UDP),包括client和server
  88. ChannelFuturefuture=bootstrap.connect(newInetSocketAddress(
  89. "localhost",8080));
  90. future.getChannel().getCloseFuture().awaitUninterruptibly();
  91. bootstrap.releaseExternalResources();
  92. }
  93. @Test
  94. publicvoidtestNetty(){
  95. testServer();
  96. testClient();
  97. }
  98. }

第二个例子,实际应用中会用到这个,发送POJO类Persons [name=周杰伦123, age=31, salary=10000.44]

Java代码 收藏代码
  1. packagecom.wujintao.netty;
  2. importstaticorg.jboss.netty.buffer.ChannelBuffers.dynamicBuffer;
  3. importjava.net.InetSocketAddress;
  4. importjava.util.concurrent.Executors;
  5. importorg.jboss.netty.bootstrap.ClientBootstrap;
  6. importorg.jboss.netty.bootstrap.ServerBootstrap;
  7. importorg.jboss.netty.buffer.ChannelBuffer;
  8. importorg.jboss.netty.channel.Channel;
  9. importorg.jboss.netty.channel.ChannelFactory;
  10. importorg.jboss.netty.channel.ChannelFuture;
  11. importorg.jboss.netty.channel.ChannelFutureListener;
  12. importorg.jboss.netty.channel.ChannelHandlerContext;
  13. importorg.jboss.netty.channel.ChannelPipeline;
  14. importorg.jboss.netty.channel.ChannelPipelineFactory;
  15. importorg.jboss.netty.channel.ChannelStateEvent;
  16. importorg.jboss.netty.channel.Channels;
  17. importorg.jboss.netty.channel.MessageEvent;
  18. importorg.jboss.netty.channel.SimpleChannelHandler;
  19. importorg.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
  20. importorg.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
  21. importorg.jboss.netty.handler.codec.frame.FrameDecoder;
  22. importorg.junit.Test;
  23. /**
  24. *用POJO代替ChannelBuffer
  25. */
  26. classTimeServerHandler3extendsSimpleChannelHandler{
  27. @Override
  28. publicvoidchannelConnected(ChannelHandlerContextctx,ChannelStateEvente)
  29. throwsException{
  30. Personsperson=newPersons("周杰伦123",31,10000.44);
  31. ChannelFuturefuture=e.getChannel().write(person);
  32. future.addListener(ChannelFutureListener.CLOSE);
  33. }
  34. }
  35. classTimeClientHandler3extendsSimpleChannelHandler{
  36. @Override
  37. publicvoidmessageReceived(ChannelHandlerContextctx,MessageEvente)
  38. throwsException{
  39. Personsperson=(Persons)e.getMessage();
  40. System.out.println(person);
  41. e.getChannel().close();
  42. }
  43. }
  44. /**
  45. *FrameDecoderandReplayingDecoderallowyoutoreturnanobjectofanytype.
  46. *
  47. */
  48. classTimeDecoderextendsFrameDecoder{
  49. privatefinalChannelBufferbuffer=dynamicBuffer();
  50. @Override
  51. protectedObjectdecode(ChannelHandlerContextctx,Channelchannel,
  52. ChannelBufferchannelBuffer)throwsException{
  53. if(channelBuffer.readableBytes()<4){
  54. returnnull;
  55. }
  56. if(channelBuffer.readable()){
  57. //读到,并写入buf
  58. channelBuffer.readBytes(buffer,channelBuffer.readableBytes());
  59. }
  60. intnamelength=buffer.readInt();
  61. Stringname=newString(buffer.readBytes(namelength).array(),"GBK");
  62. intage=buffer.readInt();
  63. doublesalary=buffer.readDouble();
  64. Personsperson=newPersons(name,age,salary);
  65. returnperson;
  66. }
  67. }
  68. classTimeEncoderextendsSimpleChannelHandler{
  69. privatefinalChannelBufferbuffer=dynamicBuffer();
  70. @Override
  71. publicvoidwriteRequested(ChannelHandlerContextctx,MessageEvente)
  72. throwsException{
  73. Personsperson=(Persons)e.getMessage();
  74. buffer.writeInt(person.getName().getBytes("GBK").length);
  75. buffer.writeBytes(person.getName().getBytes("GBK"));
  76. buffer.writeInt(person.getAge());
  77. buffer.writeDouble(person.getSalary());
  78. Channels.write(ctx,e.getFuture(),buffer);
  79. }
  80. }
  81. classPersons{
  82. privateStringname;
  83. privateintage;
  84. privatedoublesalary;
  85. publicPersons(Stringname,intage,doublesalary){
  86. this.name=name;
  87. this.age=age;
  88. this.salary=salary;
  89. }
  90. publicStringgetName(){
  91. returnname;
  92. }
  93. publicvoidsetName(Stringname){
  94. this.name=name;
  95. }
  96. publicintgetAge(){
  97. returnage;
  98. }
  99. publicvoidsetAge(intage){
  100. this.age=age;
  101. }
  102. publicdoublegetSalary(){
  103. returnsalary;
  104. }
  105. publicvoidsetSalary(doublesalary){
  106. this.salary=salary;
  107. }
  108. @Override
  109. publicStringtoString(){
  110. return"Persons[name="+name+",age="+age+",salary="+salary
  111. +"]";
  112. }
  113. }
  114. publicclassTestCase5{
  115. publicvoidtestServer(){
  116. ChannelFactoryfactory=newNioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool());
  117. ServerBootstrapbootstrap=newServerBootstrap(factory);
  118. bootstrap.setPipelineFactory(newChannelPipelineFactory(){
  119. publicChannelPipelinegetPipeline()throwsException{
  120. returnChannels.pipeline(newTimeEncoder(),newTimeServerHandler3());
  121. }
  122. });
  123. bootstrap.setOption("child.tcpNoDelay",true);
  124. bootstrap.setOption("child.keepAlive",true);
  125. bootstrap.bind(newInetSocketAddress("localhost",9999));
  126. }
  127. publicvoidtestClient(){
  128. //创建客户端channel的辅助类,发起connection请求
  129. ClientBootstrapbootstrap=newClientBootstrap(
  130. newNioClientSocketChannelFactory(
  131. Executors.newCachedThreadPool(),
  132. Executors.newCachedThreadPool()));
  133. bootstrap.setPipelineFactory(newChannelPipelineFactory(){
  134. publicChannelPipelinegetPipeline(){
  135. ChannelPipelinepipeline=Channels.pipeline();
  136. pipeline.addLast("decoder",newTimeDecoder());
  137. pipeline.addLast("encoder",newTimeEncoder());
  138. pipeline.addLast("handler",newTimeClientHandler3());
  139. returnpipeline;
  140. }
  141. });
  142. //创建无连接传输channel的辅助类(UDP),包括client和server
  143. ChannelFuturefuture=bootstrap.connect(newInetSocketAddress(
  144. "localhost",9999));
  145. future.getChannel().getCloseFuture().awaitUninterruptibly();
  146. bootstrap.releaseExternalResources();
  147. }
  148. @Test
  149. publicvoidtestNetty(){
  150. testServer();
  151. testClient();
  152. }
  153. }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
       在Java界,Netty无疑是开发网络应用的拿手菜。你不需要太多关注复杂的NIO模型和底层网络的细节,使用其丰富的接口,可以很容易的实现复杂的通讯功能。 本课程准备的十二个实例,按照由简单到复杂的学习路线,让你能够快速学习如何利用Netty来开发网络通信应用。                每个实例简洁、清爽、实用,重点在“用”上,即培训大家如何熟练的使用Netty解决实际问题,抛弃以往边讲应用边分析源码的培训模式所带来的“高不成低不就”情况,在已经能够熟练使用、并且清楚开发流程的基础上再去分析源码就会思路清晰、事半功倍。        本套课程的十二个实例,各自独立,同时又层层递进,每个实例都是针对典型的实际应用场景,学了马上就能应用到实际项目中去。 学习好Netty 总有一个理由给你惊喜!! 一、应用场景        Netty已经众多领域得到大规模应用,这些领域包括:物联网领域、互联网领域、电信领域、大数据领域、游戏行业、企业应用、银行证券金融领域、。。。  二、技术深度        多款开源框架中应用了Netty,如阿里分布式服务框架 Dubbo 的 RPC 框架、淘宝的消息中间件 R0cketMQ、Hadoop 的高性能通信和序列化组件 Avro 的 RPC 框架、开源集群运算框架 Spark、分布式计算框架 Storm、并发应用和分布式应用 Akka、。。。  三、就业前景         很多大厂在招聘高级/资深Java工程师时要求熟练学习、或熟悉Netty,下面只是简要列出,这个名单可以很长。。。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值