xsocket:空闲超时问题。

XSocket是什么? java的nio的封装。

详情:

1. http://xsocket.sourceforge.net/core/apidocs/2_1/index.html

2. http://xsocket.org

开发中要解决的实际问题:如果客户端一定时间内没有操作,则踢客户端下线。


/** * @author 9082046**@qq.com * */ 方案一、 在启动时设置: IServer srv = new Server(Port, IHandler); srv.setConnectionTimeoutMillis(Time_1_ms);// 设置最大连接时间。 srv.setIdleTimeoutMillis(Time_2_ms);// 设置最大空闲时间。 方案二、 在接受到连接时 和 在接受到数据时设置: public class XSocketHandler implements IDataHandler ,IConnectHandler ,IIdleTimeoutHandler ,IConnectionTimeoutHandler,IDisconnectHandler { public boolean onConnect(INonBlockingConnection nbc) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {      nbc.setConnectionTimeoutMillis(Time_1_ms);// 为什么写两次、写两种函数? 目的: 1、举例函数的用法。 2、配合onData() 一定程度上阻止恶意客户端,如果在一定时间内通不过登录验证则会被超时处理。  nbc.setIdleTimeoutMillis(Time_2_ms); return true; } public boolean onDisconnect(INonBlockingConnection nbc) throws IOException { return false; } public boolean onData(INonBlockingConnection nbc) throws IOException, BufferUnderflowException, ClosedChannelException, MaxReadSizeExceededException {
      nbc.setConnectionTimeoutMillis(Time_1_ms);  
      nbc.setIdleTimeoutMillis(Time_2_ms);
return true; } public boolean onIdleTimeout(INonBlockingConnection nbc) throws IOException { return true; } public boolean onConnectionTimeout(INonBlockingConnection nbc) throws IOException { return true; } }

个人注:xsocket的最大空闲时间 和 个人原始理解存在差异,个人原始理解:从最后一次接收到client的数据开始计时, 实际XSocket的定义:从最后一次被使用开始计时,无论是接收到数据 或者 被用来发送数据

如果实际需求中是要求:从客户端最后一次发送数据开始计时,则推荐 在XSocketHandler类中的 IHandler的实现化中使用 setConnectionTimeoutMillis() 方法。

反面举例:世界聊天会使用socket发送数据影响 setIdleTimeoutMillis() 。

如有考虑不周,请指正,请轻喷。欢迎大家留言。

原文地址:https://www.cnblogs.com/ribavnu/p/3716220.html