/**
  * Close and clean-up the IoSession.
  *
  * @param session
  * @param immediately close without waiting for the write queue to flush
  */
 @SuppressWarnings("deprecation")
 private void cleanSession(final IoSession session, boolean immediately) {
   // clean up
   final String sessionId = (String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID);
   if (log.isDebugEnabled()) {
     log.debug("Forcing close on session: {} id: {}", session.getId(), sessionId);
     log.debug("Session closing: {}", session.isClosing());
   }
   // get the write request queue
   final WriteRequestQueue writeQueue = session.getWriteRequestQueue();
   if (writeQueue != null && !writeQueue.isEmpty(session)) {
     log.debug("Clearing write queue");
     try {
       writeQueue.clear(session);
     } catch (Exception ex) {
       // clear seems to cause a write to closed session ex in some cases
       log.warn("Exception clearing write queue for {}", sessionId, ex);
     }
   }
   // force close the session
   final CloseFuture future = immediately ? session.close(false) : session.close(true);
   IoFutureListener<CloseFuture> listener =
       new IoFutureListener<CloseFuture>() {
         @SuppressWarnings({"unchecked", "rawtypes"})
         public void operationComplete(CloseFuture future) {
           // now connection should be closed
           log.debug("Close operation completed {}: {}", sessionId, future.isClosed());
           future.removeListener(this);
           for (Object key : session.getAttributeKeys()) {
             Object obj = session.getAttribute(key);
             log.debug("{}: {}", key, obj);
             if (obj != null) {
               if (log.isTraceEnabled()) {
                 log.trace("Attribute: {}", obj.getClass().getName());
               }
               if (obj instanceof IoProcessor) {
                 log.debug("Flushing session in processor");
                 ((IoProcessor) obj).flush(session);
                 log.debug("Removing session from processor");
                 ((IoProcessor) obj).remove(session);
               } else if (obj instanceof IoBuffer) {
                 log.debug("Clearing session buffer");
                 ((IoBuffer) obj).clear();
                 ((IoBuffer) obj).free();
               }
             }
           }
         }
       };
   future.addListener(listener);
 }
  private void keepAliveFilterForIdleStatus(IdleStatus status) throws Exception {
    NioSocketConnector connector = new NioSocketConnector();
    KeepAliveFilter filter =
        new KeepAliveFilter(new ClientFactory(), status, EXCEPTION, INTERVAL, TIMEOUT);
    filter.setForwardEvent(true);
    connector.getFilterChain().addLast("keep-alive", filter);

    final AtomicBoolean gotException = new AtomicBoolean(false);
    connector.setHandler(
        new IoHandlerAdapter() {
          @Override
          public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
            // cause.printStackTrace();
            gotException.set(true);
          }

          @Override
          public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
            // Do nothing
          }
        });

    ConnectFuture future =
        connector.connect(new InetSocketAddress("127.0.0.1", port)).awaitUninterruptibly();
    IoSession session = future.getSession();
    assertNotNull(session);

    Thread.sleep((INTERVAL + TIMEOUT + 1) * 1000);

    assertFalse("got an exception on the client", gotException.get());

    session.close(true);
    connector.dispose();
  }
  /** Disconnects from the world model. */
  protected void _disconnect() {
    IoSession currentSession = this.session;
    this.session = null;
    this.sentHandshake = null;
    this.receivedHandshake = null;
    this.attributeAliasValues.clear();
    this.originAliasValues.clear();

    if (currentSession != null && !currentSession.isClosing()) {

      log.info(
          "Closing connection to World Model (client) at {} (waiting {}ms).",
          currentSession.getRemoteAddress(),
          Long.valueOf(this.connectionTimeout));
      while (!currentSession.close(false).awaitUninterruptibly(this.connectionTimeout)) {
        log.error("Connection didn't close after {}ms.", Long.valueOf(this.connectionTimeout));
      }
    }

    if (currentSession != null) {
      for (ConnectionListener listener : this.connectionListeners) {
        listener.connectionInterrupted(this);
      }
    }
  }
  protected void maybeDisconnectOnDone(Exchange exchange) {
    if (session == null) {
      return;
    }

    // should session be closed after complete?
    Boolean close;
    if (ExchangeHelper.isOutCapable(exchange)) {
      close =
          exchange
              .getOut()
              .getHeader(Mina2Constants.MINA_CLOSE_SESSION_WHEN_COMPLETE, Boolean.class);
    } else {
      close =
          exchange
              .getIn()
              .getHeader(Mina2Constants.MINA_CLOSE_SESSION_WHEN_COMPLETE, Boolean.class);
    }

    // should we disconnect, the header can override the configuration
    boolean disconnect = getEndpoint().getConfiguration().isDisconnect();
    if (close != null) {
      disconnect = close;
    }
    if (disconnect) {
      LOG.debug("Closing session when complete at address: {}", address);
      session.close(true);
    }
  }
 @Override
 public void exceptionCaught(IoSession session, Throwable cause) {
   cause.printStackTrace(); // (7)
   System.out.println("[Server] Client:" + session.getRemoteAddress() + "异常");
   // 遇到未捕获的异常,则关闭连接
   session.close(true);
 }
Beispiel #6
0
 public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
   System.out.println(cause.getMessage());
   CmdListener cmdListener = (CmdListener) session.getAttribute("CmdListener");
   cmdListener.setClose();
   session.close(true);
   cmdListener.onException(cause);
 }
  private void disconnectSessions() {
    if (!(service instanceof IoAcceptor)) {
      return;
    }

    if (!((IoAcceptor) service).isCloseOnDeactivation()) {
      return;
    }

    Object lock = new Object();
    IoFutureListener<IoFuture> listener = new LockNotifyingListener(lock);

    for (IoSession s : managedSessions.values()) {
      s.close().addListener(listener);
    }

    try {
      synchronized (lock) {
        while (!managedSessions.isEmpty()) {
          lock.wait(500);
        }
      }
    } catch (InterruptedException ie) {
      // Ignored
    }
  }
  private void closeConnection() {
    if (session != null) {
      CloseFuture closeFuture = session.close(true);
      closeFuture.awaitUninterruptibly();
    }

    connector.dispose(true);
  }
 public void keepAliveRequestTimedOut(KeepAliveFilter filter, IoSession session)
     throws Exception {
   LOGGER.warn(
       "Closing the session because a keep-alive response "
           + "message was not received within {} second(s).",
       filter.getRequestTimeout());
   session.close(true);
 }
 /**
  * Handles a packet.
  *
  * @param session The session.
  * @param packet The packet.
  */
 public void handle(IoSession session, Packet packet) {
   try {
     packetHandlers[packet.getOpcode()].handle((Player) session.getAttribute("player"), packet);
   } catch (final Exception ex) {
     logger.log(Level.SEVERE, "Exception handling packet.", ex);
     session.close(false);
   }
 }
Beispiel #11
0
 /*
  * (non-Javadoc)
  *
  * @see
  * org.apache.mina.core.service.IoHandlerAdapter#sessionIdle(org.apache.
  * mina.core.session.IoSession, org.apache.mina.core.session.IdleStatus)
  */
 public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
   if (IdleStatus.BOTH_IDLE.equals(status)) {
     Long l = (Long) session.getAttribute("last");
     if (l != null && System.currentTimeMillis() - l > 60 * 1000) {
       session.close(true);
     }
   }
 }
Beispiel #12
0
  public void exceptionCaught(IoSession session, Throwable throwable) throws Exception {
    if (throwable instanceof ISOException && ignoreISOExceptions) {
      return;
    }

    getLog().error(getName() + ".session" + session.getRemoteAddress(), throwable);
    session.close(true);
  }
 private void closeSession(IoSession session) {
   String room = (String) session.getAttribute(ROOM, null);
   if (room != null) {
     log.info("Closing session [" + room + "]. ");
   } else {
     log.info("Cannot determine session to close.");
   }
   CloseFuture future = session.close(true);
 }
Beispiel #14
0
  @Override
  public void exceptionCaught(IoSession session, Throwable cause) throws Exception {

    logger.error(cause.getMessage());
    cause.printStackTrace();
    if (!(cause instanceof IOException)) {
      session.close(true);
    }
  }
 @Override
 public void sessionClosed(IoSession session) throws Exception {
   if (session.getAttribute(OTHER_IO_SESSION) != null) {
     IoSession sess = (IoSession) session.getAttribute(OTHER_IO_SESSION);
     sess.setAttribute(OTHER_IO_SESSION, null);
     sess.close(false);
     session.setAttribute(OTHER_IO_SESSION, null);
   }
 }
 @Override
 public void disconnect() {
   waitForScheduleMessagesToBeWritten();
   // We cannot call join() on the CloseFuture returned
   // by the following call. We are using a minimal
   // threading model and calling join will prevent the
   // close event from being processed by this thread (if
   // this thread is the MINA IO processor thread.
   ioSession.close(true);
 }
Beispiel #17
0
 @Override
 public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
   logger.error("-客户端与服务端连接空闲---发送心跳--sessionIdle:" + status.toString());
   // 发送心跳
   sendHeartbeat(session);
   if (session != null) {
     logger.error("-客户端与服务端连接空闲---session.close(true)---sessionIdle:" + status.toString());
     session.close(true);
   }
 }
 private void sendNeuroskyMessage(NeuroskyMessage message, IoSession session) {
   if (sendNeuroskyMessages) {
     getSocket().sendMessage(message.getMessage());
   } else {
     log.error(
         "Attempted to send message to Neurosky when functionality disabled, disconnecting: {}",
         message.getMessage());
     session.close(true);
   }
 }
Beispiel #19
0
 public void restart() {
   logger.warn("重新连接mina server");
   IoSession _session = session;
   IoConnector _connector = connector;
   session = null;
   connector = null;
   ok = false;
   if (_session != null) _session.close(false);
   if (_connector != null) _connector.dispose();
   init();
 }
Beispiel #20
0
 public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
   CmdListener cmdListener = (CmdListener) session.getAttribute("CmdListener");
   cmdListener.setClose();
   session.close(true);
   if (status.equals(IdleStatus.WRITER_IDLE)) {
     cmdListener.onException(new Exception("发送超时"));
   } else if (status == IdleStatus.READER_IDLE) {
     cmdListener.onException(new Exception("接收超时"));
   } else {
     cmdListener.onException(new Exception("超时:" + status));
   }
 }
  @Override
  public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
    //        session.write("1");
    //        if(IdleStatus.READER_IDLE.equals(status)){
    //        	LogUtil.w("-客户端与服务端连接[空闲] - " + status.toString());
    session.close(true);
    //        }else if(IdleStatus.WRITER_IDLE.equals(status)){
    //        	LogUtil.w("-客户端与服务端连接[空闲] - " + status.toString());
    //        }else{
    //        	LogUtil.w("-客户端与服务端连接[空闲] - " + status.toString());
    //        }

  }
Beispiel #22
0
  /*
   * (non-Javadoc)
   *
   * @see
   * org.apache.mina.core.service.IoHandlerAdapter#sessionCreated(org.apache
   * .mina.core.session.IoSession)
   */
  public void sessionCreated(IoSession session) throws Exception {
    String remote = session.getRemoteAddress().toString();
    log.info("stub created:" + remote);

    /** check the allow ip */
    if (TConn.ALLOW_IP == null || "*".equals(TConn.ALLOW_IP) || remote.matches(TConn.ALLOW_IP)) {
      TConn d = new TConn(session);
      session.setAttribute("conn", d);
    } else {
      log.warn("deny the connection:" + remote + ", allow ip:" + TConn.ALLOW_IP);
      session.close(true);
    }
  }
 @Override
 public void messageReceived(IoSession session, Object message) throws Exception {
   LOGGER.info("messageReceived");
   IoBuffer buf = (IoBuffer) message;
   while (buf.hasRemaining()) {
     digest.update(buf.get());
     bytesRead++;
   }
   LOGGER.info("messageReceived: bytesRead = {}", bytesRead);
   if (bytesRead >= size) {
     session.close(true);
   }
 }
 @Override
 public void exceptionCaught(IoSession ioSession, Throwable cause) {
   LOG.error(
       "Exception on receiving message from address: "
           + address
           + " using connector: "
           + connector,
       cause);
   this.message = null;
   this.messageReceived = false;
   this.cause = cause;
   if (ioSession != null) {
     ioSession.close(true);
   }
 }
Beispiel #25
0
 @Override
 public final void messageReceived(IoSession session, Object message) {
   if (message instanceof ControllMessage) {
     ControllMessage cm = (ControllMessage) message;
     clientId = cm.getClientId();
     if (cm.getProtocolVersion() != Application.PROTCOL_VERSION) {
       versionMismatch(cm.getProtocolVersion());
       session.close(true);
       return;
     }
     controllMessageReceived(cm);
   } else {
     callMessageReceived((CallMessage) message);
   }
 }
Beispiel #26
0
 /**
  * Title:
  *
  * <p>Desc:初始化客户端信息
  *
  * @param message
  * @throws UnsupportedEncodingException
  */
 public TongbuClient(Object message, String url, int port) {
   chain.addLast("logging", new LoggingFilter()); // 添加日志过滤器
   chain.addLast("myChin", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
   if (message instanceof String) {
     connector.setHandler(new ClientHandler((String) message));
   } else if (message instanceof CommEntity) {
     connector.setHandler(new ClientHandler((CommEntity) message));
   }
   connector.setConnectTimeoutMillis(10000);
   SocketSessionConfig cfg = connector.getSessionConfig();
   cfg.setUseReadOperation(true);
   IoSession session =
       connector.connect(new InetSocketAddress(url, port)).awaitUninterruptibly().getSession();
   ReadFuture readFuture = session.read();
   readFuture.awaitUninterruptibly();
   this.info = (CommResultInfo) readFuture.getMessage();
   session.close(true);
   session.getService().dispose();
 }
Beispiel #27
0
  public void close() {
    synchronized (this) {
      if (isClosed()) {
        return;
      }
      try {
        deliverRawText(flashClient ? "</flash:stream>" : "</stream:stream>", false);
      } catch (Exception e) {
        // Ignore
      }
      if (session != null) {
        session.setStatus(Session.STATUS_CLOSED);
      }
      closed = true;
    }

    // OF-881: Notify any close listeners after the synchronized block has completed.
    notifyCloseListeners(); // clean up session, etc.

    ioSession.close(false); // async via MINA
  }
Beispiel #28
0
 private void blockSession(IoSession session) {
   LOGGER.warn("Remote address in the blacklist; closing.");
   session.close(true);
 }
 @Override
 public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
   logger.error(cause.getMessage(), cause);
   session.close(true);
 }
Beispiel #30
0
 public void sessionIdle(IoSession session, IdleStatus idleStatus) throws Exception {
   if (timeout > 0) {
     session.close(true);
   }
 }