IoHandler的实现

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
		}
	
	};
 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值