1、心跳机制,在netty3和netty5上面都有。但是写法有些不一样。

  2、心跳机制在服务端和客户端的作用也是不一样的。对于服务端来说:就是定时清除那些因为某种原因在一定时间段内没有做指定操作的客户端连接。对于服务端来说:用来检测是否断开连接,然后尝试重连等问题。游戏上面也可以来监控延时问题。

  3、我这边只写了服务端的心跳用法,客户端基本差不多。

  1)netty3的写法

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import org.jboss.netty.handler.timeout.IdleStateHandler;
import org.jboss.netty.util.HashedWheelTimer; import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class Server { public static void main(String[] args) { //声明服务类
ServerBootstrap serverBootstrap = new ServerBootstrap(); //设定线程池
ExecutorService boss = Executors.newCachedThreadPool();
ExecutorService work = Executors.newCachedThreadPool(); //设置工厂
serverBootstrap.setFactory(new NioServerSocketChannelFactory(boss,work)); //设置管道流
serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline channelPipeline = Channels.pipeline();
//添加处理方式
channelPipeline.addLast("idle",new IdleStateHandler(new HashedWheelTimer(),5,5,10));
channelPipeline.addLast("decode",new StringDecoder());
channelPipeline.addLast("encode",new StringEncoder());
channelPipeline.addLast("server",new ServerHandler());
return channelPipeline;
}
}); //设置端口
serverBootstrap.bind(new InetSocketAddress(9000));
}
}

  备注:这里和之前有变化的就是管道里面多加了一个心跳,实际的处理还是在处理类里面

 channelPipeline.addLast("idle",new IdleStateHandler(new HashedWheelTimer(),5,5,10));
import org.jboss.netty.channel.*;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateEvent; public class ServerHandler extends SimpleChannelHandler { @Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
System.out.println("client:"+e.getMessage());
ctx.getChannel().write(e.getMessage());
super.messageReceived(ctx, e);
} @Override
public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
if (e instanceof IdleStateEvent) {
if (((IdleStateEvent)e).getState() == IdleState.ALL_IDLE) {
ChannelFuture channelFuture = ctx.getChannel().write("Time out,You will close");
channelFuture.addListener(channelFuture1 -> ctx.getChannel().close());
}
} else {
super.handleUpstream(ctx, e);
}
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
super.exceptionCaught(ctx, e);
} @Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelConnected(ctx, e);
} @Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelDisconnected(ctx, e);
} @Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelClosed(ctx, e);
}
}

  说明:这里是用SimpleChannelHandler里面给出的事件处理来实现的。方法为handleUpstream

  2)netty5的写法和netty3差不多

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler; public class Server { public static void main(String[] args) {
//服务类
ServerBootstrap serverBootstrap = new ServerBootstrap();
//声明两个线程池
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup work = new NioEventLoopGroup(); try {
//设置线程组
serverBootstrap.group(boss,work);
//设置服务socket工厂
serverBootstrap.channel(NioServerSocketChannel.class);
//设置管道
serverBootstrap.childHandler(new ChannelInitializer<Channel>() {
protected void initChannel(Channel channel) throws Exception {
channel.pipeline().addLast(new IdleStateHandler(5,5,10));
channel.pipeline().addLast(new StringDecoder());
channel.pipeline().addLast(new StringEncoder());
channel.pipeline().addLast(new ServerHandler());
}
});
//设置服务器连接数
serverBootstrap.option(ChannelOption.SO_BACKLOG,2048);
//设置tcp延迟状态
serverBootstrap.option(ChannelOption.TCP_NODELAY,true);
//设置激活状态,2小时清除
serverBootstrap.option(ChannelOption.SO_KEEPALIVE,true);
//监听端口
ChannelFuture channelFuture = serverBootstrap.bind(9000);
//等待服务器关闭
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭线程池
boss.shutdownGracefully();
work.shutdownGracefully();
} } }
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent; public class ServerHandler extends SimpleChannelInboundHandler<String> { //接收消息并处理
protected void messageReceived(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
System.out.println(s);
channelHandlerContext.writeAndFlush("hello client");
} @Override
public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
if (((IdleStateEvent)evt).state() == IdleState.ALL_IDLE) {
ChannelFuture channelFuture = ctx.writeAndFlush("Time out,You will close");
channelFuture.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture channelFuture) throws Exception {
ctx.channel().close();
}
});
}
} else {
super.userEventTriggered(ctx, evt);
}
}
}

netty之心跳机制的更多相关文章

  1. Netty实现心跳机制

    netty心跳机制示例,使用Netty实现心跳机制,使用netty4,IdleStateHandler 实现.Netty心跳机制,netty心跳检测,netty,心跳 本文假设你已经了解了Netty的 ...

  2. Netty学习(八)-Netty的心跳机制

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/a953713428/article/details/69378412我们知道在TCP长连接或者Web ...

  3. 基于netty的心跳机制实现

    前言:在实现过程查找过许多资料,各种波折,最后综合多篇文章最终实现并上线使用.为了减少大家踩坑的时间,所以写了本文,希望有用.对于实现过程中有用的参考资料直接放上链接,可能有些内容相对冗余,不过时间允 ...

  4. 基于netty实现的长连接,心跳机制及重连机制

    技术:maven3.0.5 + netty4.1.33 + jdk1.8   概述 Netty是由JBOSS提供的一个java开源框架.Netty提供异步的.事件驱动的网络应用程序框架和工具,用以快速 ...

  5. Netty(六):Netty中的连接管理(心跳机制和定时断线重连)

    何为心跳 顾名思义, 所谓心跳, 即在TCP长连接中, 客户端和服务器之间定期发送的一种特殊的数据包, 通知对方自己还在线, 以确保 TCP 连接的有效性. 为什么需要心跳 因为网络的不可靠性, 有可 ...

  6. Netty学习篇④-心跳机制及断线重连

    心跳检测 前言 客户端和服务端的连接属于socket连接,也属于长连接,往往会存在客户端在连接了服务端之后就没有任何操作了,但还是占用了一个连接:当越来越多类似的客户端出现就会浪费很多连接,netty ...

  7. netty心跳机制测试

    netty中有比较完善的心跳机制,(在基础server版本基础上[netty基础--基本收发])添加少量代码即可实现对心跳的监测和处理. 1 server端channel中加入心跳处理机制 // Id ...

  8. Netty(一) SpringBoot 整合长连接心跳机制

    前言 Netty 是一个高性能的 NIO 网络框架,本文基于 SpringBoot 以常见的心跳机制来认识 Netty. 最终能达到的效果: 客户端每隔 N 秒检测是否需要发送心跳. 服务端也每隔 N ...

  9. 连接管理 与 Netty 心跳机制

    一.前言 踏踏实实,动手去做,talk is cheap, show me the code.先介绍下基础知识,然后做个心跳机制的Demo. 二.连接 长连接:在整个通讯过程,客户端和服务端只用一个S ...

随机推荐

  1. 可变对象(immutable)和不可变对象(mutable)

    可变对象(immutable)和不可变对象(mutable) 这个是之前一直忽略的一个知识点,比方说说起String为什么是一个不可变对象,只知道因为它是被final修饰的所以不可变,而没有抓住不可变 ...

  2. 配置tomcat远程debug

    Linux系统中在编辑catalina.sh文件,修改JAVA_OPTS的变量值为如下即可. JAVA_OPTS="$JAVA_OPTS $JSSE_OPTS -Xdebug -Xrunjd ...

  3. [HNOI2007]紧急疏散EVACUATE

    嘟嘟嘟 看数据范围,第一反应觉得爆搜是不是能骗点分,但发现爆搜太难写了,于是就开始想想正解…… 正解大概猜到了是网络流,但是怎么把时间这个条件加入到图的内容中,却困扰了我好半天,总是感觉把这种不同维度 ...

  4. PHP----预定义数组

    预定义数组    超全局数组 <?php  /* 预定义数组:  * 自动全局变量---超全局数组  *  * 1.包含了来自WEB服务器,客户端,运行环境和用户输入的数据  * 2.这些数组比 ...

  5. JDBC(1)简单介绍/数据库的连接

    初识JDBC: JDBC是java连接数据库的一个工具,没有这个工具,java将无法和数据库进行连接. JDBC API: JDBC是个“低级”接口,也就是说,他直接用于调用SQL命令. JDBC驱动 ...

  6. 转-四种方案解决ScrollView嵌套ListView问题

    本人网上用的ID是泡面或安卓泡面,学习一年半之前开始从事Android应用开发,这是我写的第一篇Android技术文章,转载请注明出处和作者,有写的不好的地方还请帮忙指出,谢谢. 在工作中,曾多次碰到 ...

  7. latex 字母上面加符号

    加^号 输入\hat  或 \widehat 加横线 输入 \overline 加波浪线 输入 \widetilde 加一个点 \dot{要加点的字母} 加两个点\ddot{要加点的字母} 加箭头 输 ...

  8. 2018 CVTE 前端校招笔试题整理

    昨天晚上(7.20)做了CVTE的前端笔试,总共三十道题,28道多选题,2道编程题 .做完了之后觉得自己基础还是不够扎实,故在此整理出答案,让自己能从中得到收获,同时给日后的同学一些参考. 首先说一下 ...

  9. Android简单的编写一个txt阅读器(没有处理字符编码),适用于新手学习

    本程序只是使用了一些基本的知识点编写了一个比较简单粗陋的txt文本阅读器,效率不高,只适合新手练习.所以大神勿喷. 其实想到编写这种程序源自本人之前喜欢看小说,而很多小说更新太慢,所以本人就只能找一个 ...

  10. 一台ECS服务器,部署多(两)应用,且应用配置不同域名

    场景 产品环境服务器有两台,前后端各分配一台服务器.现在在不增加机器的情况下,需要增加部署一套服务给台北地区服务. 现有的前端部署方案. 产品环境部署方案详解 实现 配置NAT步骤 ECS配置多网卡, ...