Netty学习:搭建一个简单的Netty服务(ne,netty,服务,移动开发)

时间:2024-04-28 02:53:17 作者 : 石家庄SEO 分类 : 移动开发
  • TAG :

Netty学习:搭建一个简单的Netty服务

Netty 是一个基于 JAVA NIO 类库的异步通信框架,它的架构特点是:异步非阻塞、基于事件驱动、高性能、高可靠性和高可定制性。换句话说,Netty是一个NIO框架,使用它可以简单快速地开发网络应用程序,比如客户端和服务端的协议。Netty大大简化了网络程序的开发过程比如TCP和UDP的 Socket的开发。Netty 已逐渐成为 Java NIO 编程的首选框架。

项目官方地址:http://netty.io/index.html

一. Netty 的优点:
  • API 使用简单,开发门槛低;

  • 功能强大,预置了多种编解码功能,支持多种主流协议;

  • 定制能力强,可以通过 ChannelHandler 对通信框架进行灵活的扩展;

  • 性能高,通过与其它业界主流的 NIO 框架对比,Netty 的综合性能最优;

  • 社区活跃,版本迭代周期短,发现的 BUG 可以被及时修复,同时,更多的新功能会被加入;

  • 经历了大规模的商业应用考验,质量得到验证。在互联网、大数据、网络游戏、企业应用、电信软件等众多行业得到成功商用,证明了它完全满足不同行业的商用标准。

二. 搭建Netty服务:
  1. 添加pom依赖

    Pom代码Netty学习:搭建一个简单的Netty服务

    1. <dependency>

    2. <groupId>io.netty</groupId>

    3. <artifactId>netty-all</artifactId>

    4. <version>4.1.0.Final</version>

    5. </dependency>

  2. SimpleServer(服务端)

    Java代码Netty学习:搭建一个简单的Netty服务

    1. packagecom.yingjun.netty.server;

    2. importio.netty.bootstrap.ServerBootstrap;

    3. importio.netty.channel.ChannelFuture;

    4. importio.netty.channel.ChannelInitializer;

    5. importio.netty.channel.ChannelOption;

    6. importio.netty.channel.EventLoopGroup;

    7. importio.netty.channel.nio.NioEventLoopGroup;

    8. importio.netty.channel.socket.SocketChannel;

    9. importio.netty.channel.socket.nio.NioServerSocketChannel;

    10. /**

    11. *

    12. *Netty中,通讯的双方建立连接后,会把数据按照ByteBuf的方式进行传输,

    13. *例如http协议中,就是通过HttpRequestDecoder对ByteBuf数据流进行处理,转换成http的对象。

    14. *

    15. */

    16. publicclassSimpleServer{

    17. privateintport;

    18. publicSimpleServer(intport){

    19. this.port=port;

    20. }

    21. publicvoidrun()throwsException{

    22. //EventLoopGroup是用来处理IO操作的多线程事件循环器

    23. //bossGroup用来接收进来的连接

    24. EventLoopGroupbossGroup=newNioEventLoopGroup();

    25. //workerGroup用来处理已经被接收的连接

    26. EventLoopGroupworkerGroup=newNioEventLoopGroup();

    27. try{

    28. //启动NIO服务的辅助启动类

    29. ServerBootstrapb=newServerBootstrap();

    30. b.group(bossGroup,workerGroup)

    31. //配置Channel

    32. .channel(NioServerSocketChannel.class)

    33. .childHandler(newChannelInitializer<SocketChannel>(){

    34. @Override

    35. publicvoidinitChannel(SocketChannelch)throwsException{

    36. //注册handler

    37. ch.pipeline().addLast(newSimpleServerHandler());

    38. }

    39. })

    40. .option(ChannelOption.SO_BACKLOG,128)

    41. .childOption(ChannelOption.SO_KEEPALIVE,true);

    42. //绑定端口,开始接收进来的连接

    43. ChannelFuturef=b.bind(port).sync();

    44. //等待服务器socket关闭。

    45. f.channel().closeFuture().sync();

    46. }finally{

    47. workerGroup.shutdownGracefully();

    48. bossGroup.shutdownGracefully();

    49. }

    50. }

    51. publicstaticvoidmain(String[]args)throwsException{

    52. newSimpleServer(9999).run();

    53. }

    54. }

  3. SimpleServerHandler(服务端请求处理Handler)

    Java代码Netty学习:搭建一个简单的Netty服务

    1. packagecom.yingjun.netty.server;

    2. importio.netty.buffer.ByteBuf;

    3. importio.netty.channel.ChannelHandlerContext;

    4. importio.netty.channel.ChannelInboundHandlerAdapter;

    5. publicclassSimpleServerHandlerextendsChannelInboundHandlerAdapter{

    6. @Override

    7. publicvoidchannelRead(ChannelHandlerContextctx,Objectmsg)throwsException{

    8. System.out.println("SimpleServerHandler.channelRead");

    9. ByteBufresult=(ByteBuf)msg;

    10. byte[]result1=newbyte[result.readableBytes()];

    11. //msg中存储的是ByteBuf类型的数据,把数据读取到byte[]中

    12. result.readBytes(result1);

    13. StringresultStr=newString(result1);

    14. //接收并打印客户端的信息

    15. System.out.println("Clientsaid:"+resultStr);

    16. //释放资源,这行很关键

    17. result.release();

    18. //向客户端发送消息

    19. Stringresponse="helloclient!";

    20. //在当前场景下,发送的数据必须转换成ByteBuf数组

    21. ByteBufencoded=ctx.alloc().buffer(4*response.length());

    22. encoded.writeBytes(response.getBytes());

    23. ctx.write(encoded);

    24. ctx.flush();

    25. }

    26. @Override

    27. publicvoidexceptionCaught(ChannelHandlerContextctx,Throwablecause)throwsException{

    28. //当出现异常就关闭连接

    29. cause.printStackTrace();

    30. ctx.close();

    31. }

    32. @Override

    33. publicvoidchannelReadComplete(ChannelHandlerContextctx)throwsException{

    34. ctx.flush();

    35. }

    36. }

  4. SimpleServer(客户端)

    Java代码Netty学习:搭建一个简单的Netty服务

    1. packagecom.yingjun.netty.server;

    2. importio.netty.bootstrap.Bootstrap;

    3. importio.netty.bootstrap.ServerBootstrap;

    4. importio.netty.channel.ChannelFuture;

    5. importio.netty.channel.ChannelInitializer;

    6. importio.netty.channel.ChannelOption;

    7. importio.netty.channel.EventLoopGroup;

    8. importio.netty.channel.nio.NioEventLoopGroup;

    9. importio.netty.channel.socket.SocketChannel;

    10. importio.netty.channel.socket.nio.NioServerSocketChannel;

    11. importio.netty.channel.socket.nio.NioSocketChannel;

    12. publicclassSimpleClient{

    13. publicvoidconnect(Stringhost,intport)throwsException{

    14. EventLoopGroupworkerGroup=newNioEventLoopGroup();

    15. try{

    16. Bootstrapb=newBootstrap();

    17. b.group(workerGroup);

    18. b.channel(NioSocketChannel.class);

    19. b.option(ChannelOption.SO_KEEPALIVE,true);

    20. b.handler(newChannelInitializer<SocketChannel>(){

    21. @Override

    22. publicvoidinitChannel(SocketChannelch)throwsException{

    23. ch.pipeline().addLast(newSimpleClientHandler());

    24. }

    25. });

    26. //Starttheclient.

    27. ChannelFuturef=b.connect(host,port).sync();

    28. //Waituntiltheconnectionisclosed.

    29. f.channel().closeFuture().sync();

    30. }finally{

    31. workerGroup.shutdownGracefully();

    32. }

    33. }

    34. publicstaticvoidmain(String[]args)throwsException{

    35. SimpleClientclient=newSimpleClient();

    36. client.connect("127.0.0.1",9999);

    37. }

    38. }

  5. SimpleServerHandler(客户端请求处理Handlerspringmvc+mybatis+spring 整合下载地址

    Java代码Netty学习:搭建一个简单的Netty服务

    1. packagecom.yingjun.netty.server;

    2. importio.netty.buffer.ByteBuf;

    3. importio.netty.channel.ChannelHandlerContext;

    4. importio.netty.channel.ChannelInboundHandlerAdapter;

    5. publicclassSimpleClientHandlerextendsChannelInboundHandlerAdapter{

    6. @Override

    7. publicvoidchannelRead(ChannelHandlerContextctx,Objectmsg)throwsException{

    8. System.out.println("SimpleClientHandler.channelRead");

    9. ByteBufresult=(ByteBuf)msg;

    10. byte[]result1=newbyte[result.readableBytes()];

    11. result.readBytes(result1);

    12. System.out.println("Serversaid:"+newString(result1));

    13. result.release();

    14. }

    15. @Override

    16. publicvoidexceptionCaught(ChannelHandlerContextctx,Throwablecause)throwsException{

    17. //当出现异常就关闭连接

    18. cause.printStackTrace();

    19. ctx.close();

    20. }

    21. //连接成功后,向server发送消息

    22. @Override

    23. publicvoidchannelActive(ChannelHandlerContextctx)throwsException{

    24. Stringmsg="helloServer!";

    25. ByteBufencoded=ctx.alloc().buffer(4*msg.length());

    26. encoded.writeBytes(msg.getBytes());

    27. ctx.write(encoded);

    28. ctx.flush();

    29. }

    30. }

  6. 运行结果:

    Java代码Netty学习:搭建一个简单的Netty服务

    1. SimpleClientHandler.channelRead

    2. Serversaid:helloclient!

    3. ------------------------------------------

    4. SimpleServerHandler.channelRead

    5. Clientsaid:helloServer!

    6. SimpleServerHandler.channelRead

    7. Clientsaid:helloServer!


 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:Netty学习:搭建一个简单的Netty服务的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:JavaScript全局属性和全局函数下一篇:

6 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18