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
- package com.itstack.netty;
-
- import io.netty.bootstrap.ServerBootstrap;
- import io.netty.channel.ChannelFuture;
- import io.netty.channel.ChannelOption;
- import io.netty.channel.EventLoopGroup;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.nio.NioServerSocketChannel;
-
- public class NettyServer {
-
- public void bind() {
-
- EventLoopGroup bossGroup = new NioEventLoopGroup();
- EventLoopGroup workGroup = new NioEventLoopGroup();
-
- try {
-
- ServerBootstrap b = new ServerBootstrap();
- b.group(bossGroup, workGroup);
- b.channel(NioServerSocketChannel.class);
- b.option(ChannelOption.SO_BACKLOG, 1024);
- b.childHandler(new ChildChannelHandler());
-
- // 绑定端口
- ChannelFuture f = b.bind(53606).sync();
-
- // 等待服务端监听端口关闭
- f.channel().closeFuture().sync();
-
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- // 优雅的退出
- bossGroup.shutdownGracefully();
- workGroup.shutdownGracefully();
- }
-
- }
-
- }
ChildChannelHandler.java
- package com.itstack.netty;
-
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.handler.codec.LineBasedFrameDecoder;
- import io.netty.handler.codec.string.StringDecoder;
- import io.netty.handler.codec.string.StringEncoder;
-
- public class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
-
- @Override
- protected void initChannel(SocketChannel ch) throws Exception {
-
- System.out.println("报告");
- System.out.println("信息:有一客户端链接到本服务端");
- System.out.println("IP:" + ch.localAddress().getHostName());
- System.out.println("Port:" + ch.localAddress().getPort());
- System.out.println("报告完毕");
-
- // 半包处理【基于换行符】
- ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
- // 字符串编码
- ch.pipeline().addLast(new StringDecoder());
- // 字符串解码
- ch.pipeline().addLast(new StringEncoder());
- // 在管道中添加我们自己的接收数据实现方法
- ch.pipeline().addLast(new MyServerHanlder());
-
- }
-
- }
MyServerHanlder.java
- package com.itstack.netty;
-
- import java.util.Date;
-
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.SimpleChannelInboundHandler;
-
- public class MyServerHanlder extends SimpleChannelInboundHandler<String>{
-
- /*
- * channelAction
- *
- * channel 通道
- * action 活跃的
- *
- * 当客户端主动链接服务端的链接后,这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据
- *
- */
- public void channelActive(ChannelHandlerContext ctx) throws Exception {
- super.channelActive(ctx);
- }
-
-
- /*
- * channelInactive
- *
- * channel 通道
- * Inactive 不活跃的
- *
- * 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
- *
- */
- public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- super.channelInactive(ctx);
- }
-
- /*
- * channelRead0
- *
- * channel 通道
- * Read 读
- *
- * I msg
- * I 枚举类型根据你继承的SimpleChannelInboundHandler<I>设置来的
- *
- * 同样你用channelRead也可以处理数据,但是作者已经提供了channelRead0,并且是抽象类
- *
- * 简而言之就是从通道中读取数据,也就是服务端接收客户端发来的数据
- * 但是这个数据在不进行解码时它是ByteBuf类型的后面例子我们在介绍
- *
- */
- protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
- System.out.println(new Date()+" 收到数据:");
- System.out.println(msg);
- }
-
- /*
- * channelReadComplete
- *
- * channel 通道
- * Read 读取
- * Complete 完成
- *
- * 在通道读取完成后会在这个方法里通知,对应可以做刷新操作
- * ctx.flush()
- *
- */
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- super.channelReadComplete(ctx);
- }
-
- /*
- * exceptionCaught
- *
- * exception 异常
- * Caught 抓住
- *
- * 抓住异常,当发生异常的时候,可以做一些相应的处理,比如打印日志、关闭链接
- *
- */
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- super.exceptionCaught(ctx, cause);
- ctx.close();
- System.out.println("异常信息:\r\n"+cause.getMessage());
- }
-
- }
测试运行:
1、启动NettyServer
2、控制台输出:
----------------------------------------------
服务端开启等待客户端链接
----------------------------------------------
3、开启 网络调试助手4、输入测试数据,后面加回车换行【因为我们上面设置了只有遇到回车换行才会认为是一个完整数据,也就是netty的半包粘包处理】
5、测试结果
工程下载:
http://7narzt.com1.z0.glb.clouddn.com/Netty4.0%20TestNettyServerBaseDemo.zip