Netty实例

来源:互联网 发布:五线谱变简谱软件 编辑:程序博客网 时间:2024/06/06 05:33

Netty做为一款性能优秀的NIO框架,现在的版本是4.1.13,之前出到netty5了,但都是内测版本,可能作者觉得netty5并不是很好,于是官网和git上都没有了。所以本实例,还是采用netty4.1.13正式版,做为开发基础包。

这里就直接引用了一个完整包:netty-all-4.1.13.Final.jar

Netty需要客户端和服务端进行交互,

下面是代码,服务端类:AppServer.java

package com.zyujie.app;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;/** * Netty测试服务端类 * @author zhouyujie */public class AppServer {/** * 绑定端口 * @param port * @throws Exception */public void bing(int port) throws Exception {//服务器线程组 用于网络事件的处理一个用于服务器接收客户端的连接//另一个线程组用于处理SocketChannel的网络读写EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workGroup = new NioEventLoopGroup();try {//NIO服务器端的辅助启动类,及配置ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workGroup);b.channel(NioServerSocketChannel.class);b.option(ChannelOption.SO_BACKLOG, 1024);//Server需要一个渠道b.childHandler(new channelHandler());//服务器启动后 绑定监听端口,同步等待成功主要用于异步操作的通知回调,回调处理用的ChildChannelHandlerChannelFuture f = b.bind(port).sync();//等待服务端监听端口关闭f.channel().closeFuture().sync();} finally {//释放线程池资源bossGroup.shutdownGracefully();workGroup.shutdownGracefully();}}public static void main(String[] args) {try {System.out.println("服务端已经开启......");new AppServer().bing(8888);} catch (Exception e) {e.printStackTrace();}}}

这里定义了一个基础渠道类,相当于一个BASE渠道类:channelHandler.java,用于初始化一些参数,心跳检测的类可以用,但是具体还需要改进,先这样吧。

package com.zyujie.app;import java.util.concurrent.TimeUnit;import io.netty.channel.ChannelInitializer;import io.netty.channel.socket.SocketChannel;import io.netty.handler.timeout.IdleStateHandler;/** * Netty测试,渠道基础类 * @author zhouyujie */public class channelHandler extends ChannelInitializer<SocketChannel> {/** * 初始化渠道及参数,Netty5的自带心跳检测可用,Netty可以通过交互来模拟心跳 */protected void initChannel(SocketChannel e) throws Exception {System.out.println("有一客户端链接到本服务端");System.out.println("IP:" + e.localAddress().getHostName());System.out.println("Port:" + e.localAddress().getPort());/** * 心跳包 1、readerIdleTimeSeconds 读超时时间 2、writerIdleTimeSeconds 写超时时间 * 3、allIdleTimeSeconds 读写超时时间 4、TimeUnit.SECONDS 秒[默认为秒,可以指定] */e.pipeline().addLast(new IdleStateHandler(2, 2, 2, TimeUnit.SECONDS));//// 基于换行符号解码器//e.pipeline().addLast(new LineBasedFrameDecoder(1024));//// 解码转String//e.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8")));//// 编码器 String//e.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));// 处理心跳 【放在编码解码的下面,因为这个是通道有处理顺序】e.pipeline().addLast(new HeartBeatIdleHandler());// 在管道中添加我们自己的接收数据实现方法e.pipeline().addLast(new AppServerHandler());}}

基础渠道类里面定义了两个渠道监听类,一个是心跳,一个是接收数据的业务类,

HeartBeatIdleHandler.java

package com.zyujie.app;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;import io.netty.handler.timeout.IdleState;import io.netty.handler.timeout.IdleStateEvent;/** * Netty测试,心跳检测类 * @author zhouyujie */public class HeartBeatIdleHandler extends ChannelInboundHandlerAdapter {    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {        if (evt instanceof IdleStateEvent) {            IdleStateEvent e = (IdleStateEvent) evt;            if (e.state() == IdleState.READER_IDLE) {                System.out.println("--- Reader Idle ---");                ctx.writeAndFlush("读取等待:客户端你在吗... ...\r\n");                // ctx.close();            } else if (e.state() == IdleState.WRITER_IDLE) {                System.out.println("--- Write Idle ---");                ctx.writeAndFlush("写入等待:客户端你在吗... ...\r\n");                // ctx.close();            } else if (e.state() == IdleState.ALL_IDLE) {                System.out.println("--- All_IDLE ---");                ctx.writeAndFlush("全部时间:客户端你在吗... ...\r\n");            }        }    }}

服务端业务渠道监听类:AppServerHandler.java

package com.zyujie.app;import java.util.Date;import com.zyujie.app.pojo.BaseMsg;import com.zyujie.app.util.AppTool;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;/** * Netty测试,渠道监听类 * @author zhouyujie */public class AppServerHandler extends ChannelInboundHandlerAdapter {/* * channelAction channel 通道 action 活跃的 * 当客户端主动链接服务端的链接后,这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据 */public void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println(ctx.channel().localAddress().toString() + " channelActive");// 通知您已经链接上客户端String str = "您已经开启与服务端链接" + " " + ctx.channel().id() + new Date() + " " + ctx.channel().localAddress();ctx.writeAndFlush(str);}/* * channelInactive channel 通道 Inactive 不活跃的 * 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据 */public void channelInactive(ChannelHandlerContext ctx) throws Exception {System.out.println(ctx.channel().localAddress().toString() + " channelInactive");}/* * channelRead channel 通道 Read 读 简而言之就是从通道中读取数据,也就是服务端接收客户端发来的数据 * 但是这个数据在不进行解码时它是ByteBuf类型的后面例子我们在介绍 */public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//System.out.println("服务器读取到客户端请求...");//ByteBuf buf = (ByteBuf) msg;//byte[] req = new byte[buf.readableBytes()];//buf.readBytes(req);//String body = new String(req, "UTF-8");//System.out.println("the time server receive order:" + body);ByteBuf buf = (ByteBuf) msg;byte[] req = new byte[buf.readableBytes()];buf.readBytes(req);BaseMsg bm = (BaseMsg) AppTool.ByteToObject(req);System.out.println(bm.getMsgId());System.out.println(bm.getMsgType());System.out.println(bm.getMsgContent());String str = "我收到了。";ByteBuf resp = Unpooled.copiedBuffer(str.getBytes("UTF-8"));ctx.write(resp);System.out.println("服务器做出了响应");}/* * channelReadComplete channel 通道 Read 读取 Complete 完成 * 在通道读取完成后会在这个方法里通知,对应可以做刷新操作 ctx.flush() */public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {ctx.flush();}/* * exceptionCaught exception 异常 Caught 抓住 * 抓住异常,当发生异常的时候,可以做一些相应的处理,比如打印日志、关闭链接 */public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close();System.out.println("异常信息:\r\n" + cause.getMessage());}}

服务端弄好了,下面是客户端,这里只写了一个:AppClient.java客户端配置类和渠道监听类:AppClientHandler.java

package com.zyujie.app;import io.netty.bootstrap.Bootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelOption;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;public class AppClient {/** * 连接服务器 * @param port * @param host * @throws Exception */public void connect(int port, String host) throws Exception {// 配置客户端NIO线程组EventLoopGroup group = new NioEventLoopGroup();try {// 客户端辅助启动类 对客户端配置Bootstrap b = new Bootstrap();b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(new AppClientHandler());}});// 异步链接服务器 同步等待链接成功ChannelFuture f = b.connect(host, port).sync();// 等待链接关闭f.channel().closeFuture().sync();} finally {group.shutdownGracefully();System.out.println("释放了线程资源...");}}public static void main(String[] args) throws Exception {new AppClient().connect(8888, "127.0.0.1");}}

package com.zyujie.app;import java.util.logging.Logger;import com.zyujie.app.pojo.BaseMsg;import com.zyujie.app.util.AppTool;import com.zyujie.heartbeat.MyHeartBeatClientHandler;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;public class AppClientHandler extends SimpleChannelInboundHandler<ByteBuf> {private static final Logger logger = Logger.getLogger(MyHeartBeatClientHandler.class.getName());/** * 客户端连接 */public void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println("客户端active");BaseMsg bm = new BaseMsg();        bm.setMsgId("123");        bm.setMsgType("测试");        bm.setMsgContent("测试的内容");        byte[] reqs = AppTool.ObjectToByte(bm);        ctx.writeAndFlush(Unpooled.buffer(reqs.length).writeBytes(reqs));}/** * 客户端读取服务端返回数据 */protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {System.out.println("客户端收到服务器响应数据");ByteBuf buf = (ByteBuf) msg;byte[] req = new byte[buf.readableBytes()];buf.readBytes(req);String body = new String(req, "UTF-8");System.out.println("======>" + body);}public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {ctx.flush();System.out.println("客户端收到服务器响应数据处理完成");//读取服务端返回后,再发送,再返回这样一直循环,长连接Thread.sleep(2000);BaseMsg bm = new BaseMsg();        bm.setMsgId("123");        bm.setMsgType("测试");        bm.setMsgContent("测试的内容");        byte[] reqs = AppTool.ObjectToByte(bm);        ctx.writeAndFlush(Unpooled.buffer(reqs.length).writeBytes(reqs));}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {logger.warning("Unexpected exception from downstream:" + cause.getMessage());ctx.close();System.out.println("客户端异常退出");}}

这样就建立了服务端和客户端的长连接了,如果把数据库连接,或者redis这些做好,客户端就可以一直发送数据给服务端了。当然这只是个简易的,具体的还需要改进。

注:netty5,我也写了一个例子,netty5的handler,不管是服务端还是客户端都是继承:ChannelHandlerAdapter,而netty4的服务端handler是继承:ChannelInboundHandlerAdapter,客户端handler是继承:SimpleChannelInboundHandler<ByteBuf>,这只是一种写法,具体还有其它的,希望大家指正哈。