首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 互联网 >

IoHandler的兑现

2012-07-29 
IoHandler的实现IoHandler是对数据的最终处理,它会得到数据的信息和状态,尽管处理是在IoHandler里面,但是

IoHandler的实现

IoHandler是对数据的最终处理,它会得到数据的信息和状态,尽管处理是在IoHandler里面,但是真正执行通讯的是IoSession,它如同一个载体。?

IoHandler的兑现

?

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 attributesession.setAttribute(ADDRESS, address);// 保存sessionsessionMap.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 {// 移除sessionString 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);// 关闭sessionsession.close(false);// 通知异常监听器Exception exception = new Exception("连接异常[" + address + "]", cause);// 调用异常listenerexceptionListener.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 listeneracceptListener.handleMessage(address, msg);}/** * message sent */public void messageSent(IoSession session, Object message) throws Exception {// do nothing}};
?

?

?

?

?

?

?

?

?

热点排行