上一章已经讲了如何搭建一个简单的netty server,这一章讲一下netty超时心跳机制。
一般应用场景是client在一定时间未收到server端数据时给server端发送心跳请求,server收到心跳请求后发送一个心跳包给client端,以此维持通信。
发送心跳由client执行,server端反馈心跳就可以了,好了不多说了,上代码:
netty server代码:
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
public class NettyServerBootstrap {
private static Logger logger = Logger.getLogger(NettyServerBootstrap.class);
private int port;
public NettyServerBootstrap(int port) {
this.port = port;
bind();
}
private void bind() {
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup worker = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boss, worker);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel)
throws Exception {
ChannelPipeline p = socketChannel.pipeline();
// 超时处理:参数分别为读超时时间、写超时时间、读和写都超时时间、时间单位
p.addLast(new IdleStateHandler(15, 30, 30, TimeUnit.SECONDS));
p.addLast(new NettyIdleStateHandler());
p.addLast(new NettyServerHandler());
}
});
ChannelFuture f = bootstrap.bind(port).sync();
if (f.isSuccess()) {
logger.debug("启动Netty服务成功,端口号:" + this.port);
}
// 关闭连接
f.channel().closeFuture().sync();
} catch (Exception e) {
logger.error("启动Netty服务异常,异常信息:" + e.getMessage());
e.printStackTrace();
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}
server端NettyIdleStateHandler:
import org.apache.log4j.Logger;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
/**
* 处理超时连接handler
*
* @author Guo Kaixuan
*
*/
public class NettyIdleStateHandler extends ChannelHandlerAdapter {
private static Logger logger = Logger
.getLogger(NettyIdleStateHandler.class);
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state().equals(IdleState.READER_IDLE)) {
logger.warn("Netty服务器在通道" + ctx.channel().id() + "上读超时,已将该通道关闭");
} else if (event.state().equals(IdleState.WRITER_IDLE)) {
logger.warn("Netty服务器在通道" + ctx.channel().id() + "上写超时,已将该通道关闭");
} else if (event.state().equals(IdleState.ALL_IDLE)) {
logger.warn("Netty服务器在通道" + ctx.channel().id()
+ "上读&写超时,已将该通道关闭");
}
super.userEventTriggered(ctx, evt);
}
}
}
server端NettyServerHandler
import java.io.UnsupportedEncodingException;
import org.apache.log4j.Logger;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.SocketChannel;
public class NettyServerHandler extends ChannelHandlerAdapter {
private static Logger logger = Logger.getLogger(NettyServerHandler.class);
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf buf = (ByteBuf) msg;
String recieved = getMessage(buf);
System.out.println("服务器接收到消息:" + recieved);
try {
ctx.writeAndFlush(newPing("服务器已收到心跳包"));
} catch (Exception e) {
ServiceLoggerUtils.error("通信异常");
return;
}
}
/*
* 从ByteBuf中获取信息 使用UTF-8编码返回
*/
private String getMessage(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con, Constant.UTF8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static ByteBuf newPing(String message) {
byte[] mes = message.getBytes();
ByteBuf pingMessage = Unpooled.buffer();
pingMessage.writeBytes(mes);
return pingMessage;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
}
}
client端代码:
import java.util.concurrent.TimeUnit;
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;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
public class NettyClientBootstrap {
/*
* 服务器端口号
*/
private int port;
/*
* 服务器IP
*/
private String host;
@SuppressWarnings("unused")
private SocketChannel socketChannel;
public NettyClientBootstrap(int port, String host)
throws InterruptedException {
this.port = port;
this.host = host;
start();
}
private void start() throws InterruptedException {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.group(eventLoopGroup);
bootstrap.remoteAddress(host, port);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel)
throws Exception {
//超时处理:参数分别为读超时时间、写超时时间、读和写都超时时间、时间单位
socketChannel.pipeline().addLast(new IdleStateHandler(3, 8, 0, TimeUnit.SECONDS));
socketChannel.pipeline().addLast(new NettyIdleStateHandler());
socketChannel.pipeline().addLast(new NettyClientHandler());
}
});
ChannelFuture future = bootstrap.connect(host, port).sync();
if (future.isSuccess()) {
socketChannel = (SocketChannel) future.channel();
System.out.println("----------------connect server success----------------");
}
future.channel().closeFuture().sync();
} finally {
eventLoopGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
NettyClientBootstrap bootstrap = new NettyClientBootstrap(9999,
"localhost");
}
}
client端NettyIdleStateHandler:
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
/**
* 处理超时连接handler
*
* @author
*
*/
public class NettyIdleStateHandler extends ChannelHandlerAdapter {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state().equals(IdleState.READER_IDLE)) {
String message = "心跳包";
byte[] req = message.getBytes();
ByteBuf pingMessage = Unpooled.buffer();
pingMessage.writeBytes(req);
ctx.writeAndFlush(pingMessage);
System.out.println("客户端读超时,已发送心跳");
} else if (event.state().equals(IdleState.WRITER_IDLE)) {
System.out.println("客户端写超时");
} else if (event.state().equals(IdleState.ALL_IDLE)) {
System.out.println("客户端读&写超时");
}
super.userEventTriggered(ctx, evt);
}
}
}
client端NettyClientHandler:
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class NettyClientHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
String result = getMessage((ByteBuf) msg);
System.out.print("客户端收到服务器响应数据:" + result);
}
private String getMessage(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con, Constant.UTF8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
}
以上代码需要引入netty5包和log4j包,netty包上一张有将如何加入,log4j请自行下载或者maven添加。如有问题欢迎留言。
分享到:
相关推荐
Netty5.0jar包带javadoc Netty4.03API文档CHM格式
官方自带的netty5.0案例,非常强大,学习netty必备!
Netty 入门与实战:仿写微信 IM 即时通讯系统
netty5.0架构剖析和源码解读, 很清楚的讲解了netty5.0的架构和源码
Netty5.0架构剖析和源码解读,学习NIO,学习netty,值得学习
采用Netty5.0编的的TCP/IP上传文件的列子,实现了拆包,合并
《Netty进阶之路:跟着案例学Netty》中的案例涵盖了Netty的启动和停止、内存、并发多线程、性能、可靠性、安全等方面,囊括了Netty绝大多数常用的功能及容易让人犯错的地方。在案例的分析过程中,还穿插讲解了Netty...
Netty 5.0.0.Alpha1 版本,包含:Jar包+源代码+API文档。 官网Netty 5.0版本已经废弃,所以发布出来,方便大家下载。 《Netty权威指南》一书使用的就是Netty 5.0
服务器条件NETTY框架编程: 服务器IP:192.168.2.106 端口8810 数据传输的方式:从串口接收到一条完整的协议数据,计算出数据字节长度,打包成HtAlingProtocol类,并发送给服务器; package ...
Netty5.0 架构剖析和源码解读 作者:李林锋 版权所有 email neu_lilinfeng@ © Netty5.0 架构剖析和源码解读1 1. 概述2 1.1. JAVA 的IO演进2 1.1.1. 传统BIO通信的弊端2 1.1.2. Linux 的网络IO模型简介4 1.1.3. IO...
Netty 入门与实战:仿写微信 IM 即时通讯系统
netty5.0通信框架实现客户端和服务器端demo 的数据对象传输,控制的比较完美,里面包括了netty5.0通信框架jar包
Netty 5.0.0.Alpha2 版本,包含:Jar包+源代码+API文档。 官网Netty 5.0版本已经废弃,所以发布出来,方便大家下载。 《Netty权威指南》一书使用的就是Netty 5.0
Netty5.0架构剖析和源码解读.pdf是一本比较全的讲解netty5的书籍,任何对java的nio技术感兴趣的人都值得一看。
Netty5.0架构剖析和源码解读 目录 1. 概述 2. NIO 入门 3. Netty 源码分析 4. Netty 架构 5. 附录
Netty5.0架构剖析和源码解读 李林峰 可编辑文字版.pdf
netty5.0jar包netty-all-5.0.0.Alpha2,用于开发netty服务器
netty5.0.jar 用于java之间的通信 也可以与其他语言通信 利用Handler就行
8.实战:Netty实现客户端登录 15 9.实战:实现客户端与服务端收发消息 16 10.Pipeline与ChannelHandler 17 11.实战:构建客户端与服务端 Pipeline 18 12.实战:拆包粘包理论与解决方案 20 13.ChannelHandler的生命周期 ...