IoHandler是对数据的最终处理,它会得到数据的信息和状态,尽管处理是在IoHandler里面,但是真正执行通讯的是IoSession,它如同一个载体。
private IoHandler handler = new IoHandler() {
/**
* session create
*/
public void sessionCreated(IoSession session) throws Exception {
SocketAddress socketAddress = session.getRemoteAddress();
String address = socketAddress2Str(socketAddress);
// 2.如果地址是127.0.0.1,则转换为真实IP地址
String ip = address.substring(0, address.indexOf(":"));
String port = address.substring(address.indexOf(":") + 1);
if (ip.equals("127.0.0.1")) {
String localAddress = getLocalAddress();
address = localAddress.substring(0, localAddress.indexOf(":")) + ":" + port;
}
// 保存到session attribute
session.setAttribute(ADDRESS, address);
// 保存session
sessionMap.put(address, session);
sessionCreateTime.put(session, System.currentTimeMillis());
}
/**
* session opened
*/
public void sessionOpened(IoSession session) throws Exception {
// do nothing
}
/**
* session closed
*/
public void sessionClosed(IoSession session) throws Exception {
// 移除session
String address = (String) session.getAttribute(ADDRESS);
if (address != null) {
sessionMap.remove(address);
sessionCreateTime.remove(session);
if (logger.isDebugEnabled()) {
logger.debug("当前连接的连接数为:" + sessionMap.size());
}
}
}
/**
* session idle
*/
public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
// 空隙时间大于设置的自动断开时间,断开连接
long idleTime = System.currentTimeMillis() - session.getLastReadTime();
if (idleTime > autoDisconnectTimeout) {
session.close(false);
return;
}
}
/**
* exception caught
*/
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
// 获取远端地址
String address = (String) session.getAttribute(ADDRESS);
// 关闭session
session.close(false);
// 通知异常监听器
Exception exception = new Exception("连接异常[" + address + "]", cause);
// 调用异常listener
exceptionListener.onException(address, exception);
}
/**
* message received
*/
public void messageReceived(IoSession session, Object message) throws Exception {
byte[] msg = (byte[]) message;
// 回应心跳消息
if (msg.length == 1 && msg[0] == HEART_REQUEST_MARK) {
session.write(new byte[] { HEART_RESPONSE_MARK });
return;
}
// 获取session保存的地址
String address = (String) session.getAttribute(ADDRESS);
// 调用accept listener
acceptListener.handleMessage(address, msg);
}
/**
* message sent
*/
public void messageSent(IoSession session, Object message) throws Exception {
// do nothing
}
};