一、服务器启动示例:

public class MySocketServer {
protected static Logger logger = LoggerFactory.getLogger(MySocketServer.class); public void start(int port) {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.childHandler(new SocketServerInitializer()); logger.debug("server side socket start successful on port {}", port); b.bind(port).sync().channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
logger.error("{}", e.getMessage());
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}

二、各种业务Handler:

public class SocketServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast(new IdleStateHandler(10, 0, 0, TimeUnit.SECONDS)) // 构造一个超时event消息
.addLast(new IdleStateTrigger()) // 处理超时event消息
.addLast(new StringDecoder())
.addLast(new StringEncoder())
.addLast(new ServerHandler());
}
}

三、读空闲(超过10s)的事件处理

public class IdleStateTrigger extends ChannelInboundHandlerAdapter {
protected static Logger logger = LoggerFactory.getLogger(IdleStateTrigger.class); @Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleState state = ((IdleStateEvent) evt).state();
logger.debug("state is {}", state.name());
if (state == IdleState.READER_IDLE) {
ctx.close(); // 如果是超过10s没有读到数据,关闭客户端连接
throw new Exception("idle exception");
}
} else {
super.userEventTriggered(ctx, evt);
}
} }

附录、超时功能的快捷实现
使用自带的ReadTimeoutHandler

public class SocketServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast(new StringDecoder())
.addLast(new StringEncoder())
.addLast(new ReadTimeoutHandler(10, TimeUnit.SECONDS))
.addLast(new ServerHandler());
}
}

最新文章

  1. 《中国文明史》系列—外柔 VS 内厉
  2. C语言栈调用机制初探
  3. POJ 3669 Meteor Shower【BFS】
  4. Front End Developer Questions 前端开发人员问题(三)JavaScript部分
  5. Intent属性详解三 data、type和extra
  6. 批量生成clr脚本
  7. Python 之 lamda 函数
  8. 文件上传插件uploadify详解
  9. 用C/C++实现对STORM的执行信息查看和控制
  10. 分享使用NPOI导出Excel树状结构的数据,如部门用户菜单权限
  11. margin的理解
  12. nginx: [warn] conflicting server name &quot;locahost&quot; on 0.0.0.0:80, ignored
  13. C# 对List成员排序的简单方法
  14. Linux指令--df,du
  15. 关于WinSock编程的多线程控制
  16. WebMisCentral-Client 适配MySql数据库
  17. Kaggle(一):房价预测
  18. js检测上传文件大小
  19. 静态链接库(lib)、动态链接库(dll)与动态链接库的导入库(lib)
  20. 谈应用环境下的TIME_WAIT和CLOSE_WAIT[转]

热门文章

  1. html块元素和内联元素
  2. bash if 表达式含义
  3. 微信小程序 - radio/checkbox自定义组件
  4. Linux文件的软链接和硬链接
  5. JavaIO流原理之常用字节流和字符流详解以及Buffered高效的原理
  6. maximum-subarray 序列最大连续和 贪心
  7. C# Linq to Entity Lamda方式分组并求和求平均值
  8. Changing the Language Used in ODI Studio
  9. 查看MySQL的当前日期
  10. django 生成csv文件重要代码