netty3心跳:

package com.heart;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; 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;
/**
* netty服务端入门
*/
public class Server { public static void main(String[] args) {
//服务类
ServerBootstrap bootstrap = new ServerBootstrap(); //boss线程监听端口,worker线程负责数据读写
ExecutorService boss = Executors.newCachedThreadPool();
ExecutorService worker = Executors.newCachedThreadPool(); //设置niosocket工厂
bootstrap.setFactory(new NioServerSocketChannelFactory(boss, worker)); final HashedWheelTimer hashedWheelTimer = new HashedWheelTimer();
//设置管道的工厂
bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override
public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("idle", new IdleStateHandler(hashedWheelTimer, 5, 5, 10));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("helloHandler", new HelloHandler());
return pipeline;
}
});
bootstrap.bind(new InetSocketAddress(10101));
System.out.println("start!!!");
}
}
package com.heart;

import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateEvent; /*
心跳
idleStateHandler:用来检测会话状态。一个用户长时间没有发数据,会话一直空闲,就要把会话断掉,强制下线。
可以写定时器定时去检测。
5秒没有读,5秒没有写,10秒没有读也没有写,就抛出事件。 客户端突然断电,tcp是来不及发送断开数据包的,否则就会一直存在僵尸的会话。
客户端定时发送请求,长时间不发送,就断开连接。
*/ public class HelloHandler extends SimpleChannelHandler /*,IdleStateAwareChannelHandle*/{ @Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
System.out.println(e.getMessage());
} //时间过长没有收到客户端数据,就会抛出IdleStateEvent。
@Override
public void handleUpstream(final ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
if (e instanceof IdleStateEvent) {//如果事件是IdleStateEvent
if(((IdleStateEvent)e).getState() == IdleState.ALL_IDLE){
System.out.println("提玩家下线");
//关闭会话,整个socket就断了
//ctx.getChannel().close();
ChannelFuture write = ctx.getChannel().write("超时, you will close");
write.addListener(new ChannelFutureListener() {//写完数据之后要做的事情
@Override
public void operationComplete(ChannelFuture future) throws Exception {
ctx.getChannel().close();
}
});
}
} else {//不是这个事件,就继续向下传递,
super.handleUpstream(ctx, e);
}
}
}

netty5心跳:

package com.heart;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
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.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler; /**
* netty5服务端
*/
public class Server { public static void main(String[] args) {
//服务类
ServerBootstrap bootstrap = new ServerBootstrap();
//boss和worker
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup worker = new NioEventLoopGroup(); try {
//设置线程池
bootstrap.group(boss, worker);
//设置socket工厂、
bootstrap.channel(NioServerSocketChannel.class);
//设置管道工厂
bootstrap.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new IdleStateHandler(5, 5, 10));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new StringEncoder());
ch.pipeline().addLast(new ServerHandler());
}
}); //netty3中对应设置如下
//bootstrap.setOption("backlog", 1024);
//bootstrap.setOption("tcpNoDelay", true);
//bootstrap.setOption("keepAlive", true);
//设置参数,TCP参数
bootstrap.option(ChannelOption.SO_BACKLOG, 2048);//serverSocketchannel的设置,链接缓冲池的大小
bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);//socketchannel的设置,维持链接的活跃,清除死链接
bootstrap.childOption(ChannelOption.TCP_NODELAY, true);//socketchannel的设置,关闭延迟发送
//绑定端口
ChannelFuture future = bootstrap.bind(10101);
System.out.println("start");
//等待服务端关闭
future.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally{
//释放资源
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}
package com.heart;

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> { @Override
protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg);
ctx.channel().writeAndFlush("hi");
ctx.writeAndFlush("hi");
} @Override
public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception {
if(evt instanceof IdleStateEvent){
IdleStateEvent event = (IdleStateEvent)evt;
if(event.state() == IdleState.ALL_IDLE){
//清除超时会话
ChannelFuture writeAndFlush = ctx.writeAndFlush("超时,you will close");
writeAndFlush.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
ctx.channel().close();
}
});
}
}else{
super.userEventTriggered(ctx, evt);
}
} /**
* 新客户端接入
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelActive");
} /**
* 客户端断开
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelInactive");
} /**
* 异常
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
}
}

netty5----心跳的更多相关文章

  1. netty5心跳与阻塞性业务消息分发实例

    继续之前的例子(netty5心跳与业务消息分发实例),我们在NettyClientHandler把业务消息改为阻塞性的: package com.wlf.netty.nettyclient.handl ...

  2. netty5心跳与业务消息分发实例

    继续基于我们之前的例子(参见netty5自定义私有协议实例),这次我们加上连接校验和心跳机制: 只要校验通过,客户端发送心跳和业务消息是两个不同的事件发送的,彼此互不干扰.针对以上流程,我们需要增加4 ...

  3. netty5服务端检测心跳超时断连

    客户端每5秒发送一次心跳给服务端,服务端记录最后一次心跳时间,通过定时任务每10秒检测一下,如果当前时间与最后一次收到的心跳时间之差超过某个阈值,断开与客户端的连接.基于之前的例子(netty5心跳与 ...

  4. netty5客户端监测服务端断连后重连

    服务端挂了或者主动拒绝客户端的连接后,客户端不死心,每15秒重连试试,3次都不行就算了.修改下之前的客户端引导类(NettyClient,参见netty5心跳与业务消息分发实例),新增两个成员变量,在 ...

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

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

  6. Netty5 + WebSocket 练习

    1. 了解WebSocket知识 略2. websocket实现系统简单反馈时间 WebSocketServerHandler.java package com.jieli.nettytest.web ...

  7. Netty实现服务端客户端长连接通讯及心跳检测

    通过netty实现服务端与客户端的长连接通讯,及心跳检测.        基本思路:netty服务端通过一个Map保存所有连接上来的客户端SocketChannel,客户端的Id作为Map的key.每 ...

  8. 通过netty实现服务端与客户端的长连接通讯,及心跳检测。

    基本思路:netty服务端通过一个Map保存所有连接上来的客户端SocketChannel,客户端的Id作为Map的key.每次服务器端如果要向某个客户端发送消息,只需根据ClientId取出对应的S ...

  9. netty之心跳机制

    1.心跳机制,在netty3和netty5上面都有.但是写法有些不一样. 2.心跳机制在服务端和客户端的作用也是不一样的.对于服务端来说:就是定时清除那些因为某种原因在一定时间段内没有做指定操作的客户 ...

随机推荐

  1. python笔记3 - 文件操作

    file 对象使用 open 函数来创建,下面说一下对文件的操作分三步: 1.打开文件获取文件的句柄,句柄就理解为这个文件 2.通过文件句柄操作文件,读取/写入文件内容 3.关闭文件. 注意: 文件打 ...

  2. 第二百一十九节,jQuery EasyUI,DateTimeBox(日期时间输入框)组件

    jQuery EasyUI,DateTimeBox(日期时间输入框)组件 学习要点: 1.加载方式 2.属性列表 3.方法列表 本节课重点了解 EasyUI 中 DateTimeBox(日期时间输入框 ...

  3. 那些年我读过的Blog(Ⅰ)

    序 近期发现自己已经很久很久没有写过文章,其中包括公开的和非公开的Blog,于是自己去翻了以前很多关注的人的Blog,发现也已经有很大一部分没有更新了,遂有了本文,梳理一下自己那些年关注过并且现在已经 ...

  4. cobbler setting dnsmasq

    Currently cobbler can help generate a ISC DHCP configuration (package name: dhcpd) it can also alter ...

  5. 使用Array的原型使对象具有length,和数组的内容

    var elems = { length: , add: function (elem) { Array.prototype.push.call(this, elem); }, gather: fun ...

  6. (转)ThreadLocal

    转自:http://blog.csdn.net/lufeng20/article/details/24314381 Thread同步机制的比较 ThreadLocal和线程同步机制相比有什么优势呢?T ...

  7. 学习笔记:Vue+Node+Mongodb 构建简单商城系统(二)

    前面几个月工作有点忙,导致构建简单商城系统的计划搁置近三个月.现在终于有时间重新回过头来继续本计划.本篇主要记录自己在阿里云服务器上搭建node运行环境的整个过程,以及对其中遇到的一些问题的思考. 一 ...

  8. 将MathType公式粘贴到文档中的步骤

    MathType这款数学公式编辑器,常常是辅助于各种文档使用的.由于其编辑的公式与数学符号等都符号国际期刊的出版标准,并且上手容易,根本就不需要一个学习的过程,只要安装打开后就能直接上手使用.所以非常 ...

  9. AsyncTaskLoader设计原理大揭秘

    简介 在Android异步处理之AsyncTaskLoader简单使用中我简单的介绍了一下AsyncTaskLoader的基本用法和使用场景,对AsyncTaskLoader还不是很熟悉的小伙伴可以先 ...

  10. 解决scalac Error: bad option -make:transitive

    关闭idea 打开项目所在位置并cd .idea 修改scala_compiler.xml文件 删除掉参数行包含-make:transitive 保存后退出编辑并重启idea打开项目