1.场景

正常的软硬件接口中(网络通信过程中),一般为了保证硬件和服务器连接一直在线,一般都是客户端主动发心跳到服务器,服务器根据收到心跳时间,判断间隔一段时间内,没有收到数据后,就断开连接。而本博客为什么要讲netty tcp空闲设置,这是因为用户很长时间不操作,则我们可以认为这个账号是僵尸账号,可以T下线,从而减少服务器的开销。而类似于王者荣耀,LOL等游戏都是这样处理的。

2.代码

package com.cloudtech.server;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cloudtech.util.Consts;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
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.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.timeout.IdleStateHandler;/***
* @ClassName: Server
* @Description:netty服务端
* @author wude
* @date 2018年9月7日
**/
public class Server {protected static final Logger logger = LoggerFactory.getLogger(Server.class);/*** 启动*/public void start(int port) {// 服务类ServerBootstrap b = new ServerBootstrap();// 创建boss和workerEventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();//业务线程池,实现消息串行化EventLoopGroup busyGroup = new NioEventLoopGroup();try {// 设置循环线程组事例b.group(bossGroup, workerGroup);// 设置channel工厂b.channel(NioServerSocketChannel.class);// 设置管道b.childHandler(new ChannelInitializer<SocketChannel>() {@Overridepublic void initChannel(SocketChannel ch) throws Exception {//第一个参数 读超时//第二个参数 写超时//第三个参数读写超时ch.pipeline().addLast(new IdleStateHandler(5, 5, 120));ByteBuf delimiter = Unpooled.copiedBuffer("\r\n".getBytes());ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Consts.MAX_BUFF_LEN,delimiter));ch.pipeline().addLast(new StringDecoder());ch.pipeline().addLast(busyGroup,new ServerHandler());}});b.option(ChannelOption.SO_BACKLOG, 2048);//serverSocketchannel的设置,链接缓冲池的大小b.childOption(ChannelOption.SO_KEEPALIVE, true);//socketchannel的设置,维持链接的活跃,清除死链接b.childOption(ChannelOption.TCP_NODELAY, true);//socketchannel的设置,关闭延迟发送logger.info("启动AWS420采集成功!port={}",port);//绑定端口ChannelFuture future = b.bind(port);//等待服务端关闭future.channel().closeFuture().sync();} catch (Exception e) {e.printStackTrace();} finally{//释放资源bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();busyGroup.shutdownGracefully();}}}

注意这三个参数很重要

package com.cloudtech.server;import java.net.InetSocketAddress;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import com.cloudtech.server.comm.ModuleId;
import com.cloudtech.server.scanner.Invoker;
import com.cloudtech.server.scanner.InvokerHoler;
import com.cloudtech.server.session.Session;
import com.cloudtech.server.session.SessionImpl;
import com.cloudtech.web.dubbo.BaseDataResult;import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;/*** * @ClassName: SessionManager* @Description: 消息接受处理类* @author wude* @date 2018年9月7日*/
public class ServerHandler extends SimpleChannelInboundHandler<String> {private static Logger LOGGER = LoggerFactory.getLogger(ServerHandler.class);@SuppressWarnings("unused")@Overrideprotected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {try {Session session = new SessionImpl(ctx.channel());InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();String ip = insocket.getAddress().getHostAddress();int port = insocket.getPort();// 获取命令执行器Invoker invoker = InvokerHoler.getInvoker(ModuleId.UPLOAD_DATA);if (invoker != null) {BaseDataResult dataResult = (BaseDataResult) invoker.invoke(session, msg, ip, port);} else {return;}} catch (Exception e) {LOGGER.debug("AWS420 解析代码失败ip:{} port:{} result:{}", e.getMessage());}}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {LOGGER.debug("进入异常方法:", cause.getMessage());ctx.close();}@Overridepublic void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {if (evt instanceof IdleStateEvent) {if (((IdleStateEvent) evt).state().equals(IdleState.READER_IDLE)) {LOGGER.error("Read Idle");ctx.close();}} else {super.userEventTriggered(ctx, evt);}}
}

按上面的配置,5,5,120    假设客户端5秒内没有与服务器进行任何的数据交互,我们则可以认为该账号是僵尸账号,直接强制T下线

netty tcp空闲设置相关推荐

  1. 开源一个自用的Android IM库,基于Netty+TCP+Protobuf实现。

    欢迎转载,转载请注明出处:https://blog.csdn.net/FreddyChen/article/details/89201785 写在前面 一直想写一篇关于im即时通讯分享的文章,无奈工作 ...

  2. C# 的tcp Socket设置自定义超时时间

    简单的c# TCP通讯(TcpListener) C# 的TCP Socket (同步方式) C# 的TCP Socket (异步方式) C# 的tcp Socket设置自定义超时时间 C# TCP ...

  3. NMAP扫描技巧:TCP空闲扫描

    一种更加高级的nmap扫描方式是TCP空闲扫描,这种扫描能让我们冒充网络上另一台主机的IP地址,对目标进行更为隐秘的扫描.进行这种扫描,我们需要在网络上定位一台使用递增IP帧(IP ID:用于跟踪IP ...

  4. 电脑tcp协议设置成服务器,电脑tcp协议设置成服务器

    电脑tcp协议设置成服务器 内容精选 换一换 DNS服务器用于解析弹性文件服务中文件系统的域名.DNS服务器东北区IP地址为100.125.6.250,其它区域详情请参见华为云内网DNS地址.默认情况 ...

  5. linux设置TCP接收缓存,TCP缓存设置及自调节

    工作的原因,同事在单条流的性能测试中出现性能值低的问题,最后的问题点确认为缓存设置不合理.为什么要设置缓存?如何设置缓存? 缓存和带宽时延积 读缓存的上限应该由TCP接收窗口的最大值确定,过大或过小的 ...

  6. Windows NT和2000的TCP/IP设置

    http://www.xhit.cn/html/net/xieyi/jichu/20070702/55169.html TCP/IP是一个广泛使用的广域网协议,在NT和2000系统中,它的一些参数会由 ...

  7. TCP长连接保持连接状态TCP keepalive设置

    出处:http://blog.csdn.net/embedded_sky/article/details/42077321 对于TCP长连接保活是十分必要的,原因如下: 1.系统多在OA网和外网间有防 ...

  8. 电脑tcp协议设置成服务器,更改 TCP/IP 设置及手动指定 IPv4/IPv6设置

    TCP/IP 定义你的电脑与其他电脑的通信方式. 若要使管理 TCP/IP 设置更加简单,我们建议使用自动化动态主机配置协议 (DHCP).DHCP 会自动将 Internet 协议 (IP) 地址分 ...

  9. 汇川AM系列 Modbus TCP通信设置

    一 .概述 单击网络组态中的PLC设备,会显示PLC内部所支持的主/从站的使能窗口,如下图所示,单击窗口中的复选框按钮来使能CPU所支持的主/从站功能,再从视图右侧的"网络设备列表" ...

最新文章

  1. 通过手写Spring MVC来理解其原理
  2. html百度地图中心点不正确,百度地图嵌入弹出层,无法准确正确显示marker标记到中心位置的问题...
  3. Python之web开发(五):WEB开发html语句经典应用
  4. 【Python基础】学习Python 一定要吃透这 5 个内置函数
  5. python编写查询_如何用python脚本编写查询
  6. 要不要出去找一份实习?
  7. Windows系统(cmd)常用命令
  8. linux make项目管理器,Linux中makefile项目管理
  9. 如何编写优质的API文档
  10. AI理论知识整理(4)-期望与方差以及联合概率分布
  11. 2016版Excel加载宏实现加载空间分析库
  12. 计算机找不到WPS云盘,为什么我的电脑里没有WPS网盘入口?开启教程教给你!
  13. EasyAR4.0简单使用说明
  14. 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被
  15. strtok用法详解
  16. 《我是北大旁听生/郑球洋》
  17. Xftp5 安装教程
  18. android设置主题和自定义主题的方法
  19. DFROBOT Mind+ 掌控板 人工智能测温实验
  20. 算法提高——JOE的算数

热门文章

  1. excel数据透视表数据排序及excel表格转成word表
  2. Android之CardView
  3. [c语言]倒置字符串 -牛客网
  4. 【目标跟踪】|单目标跟踪指标
  5. 如何为自己的 CSDN博客设置自定义域名?
  6. listdir() 方法的使用
  7. java 字节转文件_java 文件和byte 互转
  8. 关于向量的点积和叉乘
  9. Android 安卓动画 属性动画 - 移动动画
  10. ARM和neon指令集