itstack | Netty The Sniper



基于Netty4.0入门案例一之NettyServer创建

2015-8-8 付政委 Netty4.0 初级篇

前言介绍:

    1、netty4.0 与 netty5.0 差别是最小的,看上去跟废话一样。但是netty的版本在netty3.x 4.x 5.x版本内跨度编码的命名确实很多不同

    2、netty4.0 在学习本案例过程中如果有不明白的可以先从博客中netty5.0开始学起,因为案例比较全,也便于入手,之后回头在研究4.0

环境需求:

    1、jdk1.5以上,低于1.5会直接报错

    2、netty-all-4.0.30.Final.jar【官网可以下载,本案例提供的例子也含有此jar】

    3、网络调试助手一个

代码部分:


NettyServer.java


    
    
  1. package com.itstack.netty;
  2.  
  3. import io.netty.bootstrap.ServerBootstrap;
  4. import io.netty.channel.ChannelFuture;
  5. import io.netty.channel.ChannelOption;
  6. import io.netty.channel.EventLoopGroup;
  7. import io.netty.channel.nio.NioEventLoopGroup;
  8. import io.netty.channel.socket.nio.NioServerSocketChannel;
  9.  
  10. public class NettyServer {
  11.  
  12. public void bind() {
  13.  
  14. EventLoopGroup bossGroup = new NioEventLoopGroup();
  15. EventLoopGroup workGroup = new NioEventLoopGroup();
  16.  
  17. try {
  18.  
  19. ServerBootstrap b = new ServerBootstrap();
  20. b.group(bossGroup, workGroup);
  21. b.channel(NioServerSocketChannel.class);
  22. b.option(ChannelOption.SO_BACKLOG, 1024);
  23. b.childHandler(new ChildChannelHandler());
  24.  
  25. // 绑定端口
  26. ChannelFuture f = b.bind(53606).sync();
  27.  
  28. // 等待服务端监听端口关闭
  29. f.channel().closeFuture().sync();
  30.  
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. } finally {
  34. // 优雅的退出
  35. bossGroup.shutdownGracefully();
  36. workGroup.shutdownGracefully();
  37. }
  38.  
  39. }
  40.  
  41. }
ChildChannelHandler.java


    
    
  1. package com.itstack.netty;
  2.  
  3. import io.netty.channel.ChannelInitializer;
  4. import io.netty.channel.socket.SocketChannel;
  5. import io.netty.handler.codec.LineBasedFrameDecoder;
  6. import io.netty.handler.codec.string.StringDecoder;
  7. import io.netty.handler.codec.string.StringEncoder;
  8.  
  9. public class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
  10.  
  11. @Override
  12. protected void initChannel(SocketChannel ch) throws Exception {
  13.  
  14. System.out.println("报告");
  15. System.out.println("信息:有一客户端链接到本服务端");
  16. System.out.println("IP:" + ch.localAddress().getHostName());
  17. System.out.println("Port:" + ch.localAddress().getPort());
  18. System.out.println("报告完毕");
  19.  
  20. // 半包处理【基于换行符】
  21. ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
  22. // 字符串编码
  23. ch.pipeline().addLast(new StringDecoder());
  24. // 字符串解码
  25. ch.pipeline().addLast(new StringEncoder());
  26. // 在管道中添加我们自己的接收数据实现方法
  27. ch.pipeline().addLast(new MyServerHanlder());
  28.  
  29. }
  30.  
  31. }
MyServerHanlder.java


    
    
  1. package com.itstack.netty;
  2.  
  3. import java.util.Date;
  4.  
  5. import io.netty.channel.ChannelHandlerContext;
  6. import io.netty.channel.SimpleChannelInboundHandler;
  7.  
  8. public class MyServerHanlder extends SimpleChannelInboundHandler<String>{
  9.  
  10. /*
  11. * channelAction
  12. *
  13. * channel 通道
  14. * action 活跃的
  15. *
  16. * 当客户端主动链接服务端的链接后,这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据
  17. *
  18. */
  19. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  20. super.channelActive(ctx);
  21. }
  22.  
  23. /*
  24. * channelInactive
  25. *
  26. * channel 通道
  27. * Inactive 不活跃的
  28. *
  29. * 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
  30. *
  31. */
  32. public void channelInactive(ChannelHandlerContext ctx) throws Exception {
  33. super.channelInactive(ctx);
  34. }
  35. /*
  36. * channelRead0
  37. *
  38. * channel 通道
  39. * Read 读
  40. *
  41. * I msg
  42. * I 枚举类型根据你继承的SimpleChannelInboundHandler<I>设置来的
  43. *
  44. * 同样你用channelRead也可以处理数据,但是作者已经提供了channelRead0,并且是抽象类
  45. *
  46. * 简而言之就是从通道中读取数据,也就是服务端接收客户端发来的数据
  47. * 但是这个数据在不进行解码时它是ByteBuf类型的后面例子我们在介绍
  48. *
  49. */
  50. protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
  51. System.out.println(new Date()+" 收到数据:");
  52. System.out.println(msg);
  53. }
  54. /*
  55. * channelReadComplete
  56. *
  57. * channel 通道
  58. * Read 读取
  59. * Complete 完成
  60. *
  61. * 在通道读取完成后会在这个方法里通知,对应可以做刷新操作
  62. * ctx.flush()
  63. *
  64. */
  65. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  66. super.channelReadComplete(ctx);
  67. }
  68. /*
  69. * exceptionCaught
  70. *
  71. * exception 异常
  72. * Caught 抓住
  73. *
  74. * 抓住异常,当发生异常的时候,可以做一些相应的处理,比如打印日志、关闭链接
  75. *
  76. */
  77. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  78. super.exceptionCaught(ctx, cause);
  79. ctx.close();
  80. System.out.println("异常信息:\r\n"+cause.getMessage());
  81. }
  82. }
测试运行:

1、启动NettyServer

2、控制台输出:

----------------------------------------------

服务端开启等待客户端链接

----------------------------------------------

3、开启 网络调试助手

4、输入测试数据,后面加回车换行【因为我们上面设置了只有遇到回车换行才会认为是一个完整数据,也就是netty的半包粘包处理】

5、测试结果


工程下载:

http://7narzt.com1.z0.glb.clouddn.com/Netty4.0%20TestNettyServerBaseDemo.zip

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值