Java Code Examples for org.apache.mina.core.session.IoSession#closeNow()

The following examples show how to use org.apache.mina.core.session.IoSession#closeNow() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UDPDestination.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void sessionOpened(IoSession session) {
    // Set timeouts
    session.getConfig().setWriteTimeout(getWriteTimeout());
    session.getConfig().setIdleTime(IdleStatus.READER_IDLE, getReadTimeout());

    // Create streams
    InputStream in = new IoSessionInputStream();
    OutputStream out = new IoSessionOutputStream(session) {
        @Override
        public void close() throws IOException {
            try {
                flush();
            } finally {
                CloseFuture future = session.closeNow();
                future.awaitUninterruptibly();
            }
        }  
    };
    session.setAttribute(KEY_IN, in);
    session.setAttribute(KEY_OUT, out);
    processStreamIo(session, in, out);
}
 
Example 2
Source File: MinaNetClientHandler.java    From Lealone-Plugins with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(IoSession session, Throwable cause) {
    session.closeNow();
    String msg = "RemoteAddress " + session.getRemoteAddress();
    logger.error(msg + " exception: " + cause.getMessage(), cause);
    logger.info(msg + " closed");
    client.removeConnection(session);
}
 
Example 3
Source File: MinaNetServerHandler.java    From Lealone-Plugins with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(IoSession session, Throwable cause) {
    session.closeNow();
    String msg = "RemoteAddress " + session.getRemoteAddress();
    logger.error(msg + " exception: " + cause.getMessage());
    logger.info(msg + " closed");
}
 
Example 4
Source File: GateUdpUserServerHandler.java    From game-server with MIT License 5 votes vote down vote up
@Override
	public void sessionClosed(IoSession session) {
		super.sessionClosed(session);
//		ScriptManager.getInstance().getBaseScriptEntry().executeScripts(IUserScript.class,
//				script -> script.quit(session, Reason.SessionClosed));
		session.closeNow();	//TODO ?
	}
 
Example 5
Source File: GateUdpUserServerHandler.java    From game-server with MIT License 5 votes vote down vote up
@Override
	public void sessionIdle(IoSession session, IdleStatus idleStatus) {
		super.sessionIdle(session, idleStatus);
//		ScriptManager.getInstance().getBaseScriptEntry().executeScripts(IUserScript.class,
//				script -> script.quit(session, Reason.SessionIdle));
		session.closeNow();	//TODO ?
	}
 
Example 6
Source File: SSLFilterTest.java    From game-server with MIT License 5 votes vote down vote up
@Override
public void messageSent(IoSession session, Object message) throws Exception {
	sentMessages.add(message.toString());

	if (sentMessages.size() >= 2) {
		session.closeNow();
	}
}
 
Example 7
Source File: TestEcho.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
	public void messageReceived(IoSession session, Object message)
	{
		if (_recvCount.getAndIncrement() < TEST_ECHO_COUNT)
		{
//			perf[6].begin();
			write(session, message);
//			perf[6].end();
		}
		else
			session.closeNow();
	}
 
Example 8
Source File: LdapNetworkConnection.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Handle the exception we got.
 *
 * @param session The session we got the exception on
 * @param cause The exception cause
 * @throws Exception If we have had another exception
 */
@Override
public void exceptionCaught( IoSession session, Throwable cause ) throws Exception
{
    if ( LOG.isWarnEnabled() )
    {
        LOG.warn( cause.getMessage(), cause );
    }

    session.setAttribute( EXCEPTION_KEY, cause );

    if ( cause instanceof ProtocolEncoderException )
    {
        Throwable realCause = ( ( ProtocolEncoderException ) cause ).getCause();

        if ( realCause instanceof MessageEncoderException )
        {
            int messageId = ( ( MessageEncoderException ) realCause ).getMessageId();

            ResponseFuture<?> response = futureMap.get( messageId );
            response.cancel( true );
            response.setCause( realCause );
        }
    }

    session.closeNow();
}
 
Example 9
Source File: RTMPSClient.java    From red5-client with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
    log.warn("Exception caught {}", cause.getMessage());
    if (log.isDebugEnabled()) {
        log.error("Exception detail", cause);
    }
    //if there are any errors using ssl, kill the session
    session.closeNow();
}
 
Example 10
Source File: NetManager.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 停止全部相关客户端的连接
 * @param force 是否立即强制关闭(丢弃当前的发送缓存)
 */
public void stopAllClients(boolean force)
{
	NioSocketConnector connector = _connector;
	if (connector != null)
	{
		for (IoSession session : connector.getManagedSessions().values())
		{
			if (force)
				session.closeNow();
			else
				closeOnFlush(session);
		}
	}
}
 
Example 11
Source File: NetManager.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void exceptionCaught(IoSession session, Throwable cause)
{
	if (cause instanceof IOException && cause.getMessage() != null)
		Log.error("{}({},{}): exception: {}: {}", _name, session.getId(), session.getRemoteAddress(), cause.getClass().getSimpleName(), cause.getMessage());
	else
		Log.error(cause, "{}({},{}): exception:", _name, session.getId(), session.getRemoteAddress());
	session.closeNow();
}
 
Example 12
Source File: LdapNetworkConnection.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void inputClosed( IoSession session ) throws Exception 
{
    session.closeNow();
}
 
Example 13
Source File: RTMPMinaProtocolDecoder.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws ProtocolCodecException {
    // get the connection from the session
    String sessionId = (String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID);
    log.trace("Session id: {}", sessionId);
    // connection verification routine
    @SuppressWarnings("unchecked")
    IConnectionManager<RTMPConnection> connManager = (IConnectionManager<RTMPConnection>) ((WeakReference<?>) session.getAttribute(RTMPConnection.RTMP_CONN_MANAGER)).get();
    RTMPConnection conn = (RTMPConnection) connManager.getConnectionBySessionId(sessionId);
    RTMPConnection connLocal = (RTMPConnection) Red5.getConnectionLocal();
    if (connLocal == null || !conn.getSessionId().equals(connLocal.getSessionId())) {
        if (log.isDebugEnabled() && connLocal != null) {
            log.debug("Connection local didn't match session");
        }
    }
    if (conn != null) {
        // set the connection to local if its referred to by this session
        Red5.setConnectionLocal(conn);
        // copy data range from incoming
        if (log.isTraceEnabled()) {
            log.trace("Incoming: in.position {}, in.limit {}, in.remaining {}", new Object[] { in.position(), in.limit(), in.remaining() });
        }
        byte[] arr = new byte[in.remaining()];
        in.get(arr);
        // create a buffer and store it on the session
        IoBuffer buf = (IoBuffer) session.getAttribute("buffer");
        if (buf == null) {
            buf = IoBuffer.allocate(arr.length);
            buf.setAutoExpand(true);
            session.setAttribute("buffer", buf);
        }
        // copy incoming into buffer
        buf.put(arr);
        // flip so we can read
        buf.flip();
        if (log.isTraceEnabled()) {
            //log.trace("Buffer before: {}", Hex.encodeHexString(arr));
            log.trace("Buffers info before: buf.position {}, buf.limit {}, buf.remaining {}", new Object[] { buf.position(), buf.limit(), buf.remaining() });
        }
        // get the connections decoder lock
        final Semaphore lock = conn.getDecoderLock();
        try {
            // acquire the decoder lock
            lock.acquire();
            // construct any objects from the decoded bugger
            List<?> objects = decoder.decodeBuffer(conn, buf);
            log.trace("Decoded: {}", objects);
            if (objects != null) {
                int writeCount = 0;
                for (Object object : objects) {
                    out.write(object);
                    writeCount++;
                }
                log.trace("Wrote {} objects", writeCount);
            }
        } catch (Exception e) {
            log.error("Error during decode", e);
        } finally {
            lock.release();
            // clear local
            Red5.setConnectionLocal(null);
        }
        if (log.isTraceEnabled()) {
            //log.trace("Buffer after: {}", Hex.encodeHexString(Arrays.copyOfRange(buf.array(), buf.position(), buf.limit())));
            log.trace("Buffers info after: buf.position {}, buf.limit {}, buf.remaining {}", new Object[] { buf.position(), buf.limit(), buf.remaining() });
        }
    } else {
        log.debug("Closing and skipping decode for unregistered connection: {}", sessionId);
        session.closeNow();
        log.debug("Session closing: {} reading: {} writing: {}", session.isClosing(), session.isReadSuspended(), session.isWriteSuspended());
    }
}
 
Example 14
Source File: ClientHandler.java    From sumk with Apache License 2.0 4 votes vote down vote up
@Override
public void inputClosed(IoSession session) throws Exception {
	session.closeNow();
}
 
Example 15
Source File: ClientProtocolDecoder.java    From game-server with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
	int readAbleLen = in.remaining();
	if (readAbleLen < 2) {
		return false;
	}
	in.mark(); // 标记阅读位置
	byte[] bs = new byte[2];
	in.get(bs, 0, 2);
	short packageLength = IntUtil.bigEndianByteToShort(bs, 0, 2);
	if (packageLength < 1 || packageLength > maxReadSize) {
		LOGGER.warn("消息包长度为:{}", packageLength);
		in.clear();
		session.closeNow();
		return false;
	}

	if (in.remaining() < packageLength) { // 消息长度不够,重置位置
		in.reset();
		return false;
	}
	// 消息Id(4字节)+protobufLength(4字节)+消息体+时间戳(8字节)+签名数据长度(4字节)+签名数据+截取签名长度(4字节)
	bs = new byte[packageLength];
	in.get(bs);
	int protobufLength = IntUtil.bigEndianByteToInt(bs, 4, 4);
	if (packageLength > protobufLength + 8) {
		LOGGER.debug("消息签名验证");
		if (checkMsgSign(bs, protobufLength)) {
			byte[] datas = new byte[8 + protobufLength];
			System.arraycopy(bs, 0, datas, 0, datas.length);
			out.write(bs);
		} else {
			session.closeNow();
			return false;
		}
	} else {
		out.write(bs);
	}

	// decodeBytes(packageLength, in, out);

	if (!checkMsgFrequency(session)) {
		return false;
	}

	return true;
}
 
Example 16
Source File: EchoProtocolHandler.java    From game-server with MIT License 4 votes vote down vote up
@Override
public void exceptionCaught(IoSession session, Throwable cause) {
    session.closeNow();
}
 
Example 17
Source File: MsgUtil.java    From game-server with MIT License 4 votes vote down vote up
public static void close(IoSession session, String fmt, Object... args) {
	String reason = String.format(fmt, args);
	log.error(String.format("%s -->连接关闭原因 %s", session.toString(), reason));
	session.closeNow();
}
 
Example 18
Source File: NetManager.java    From jane with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void inputClosed(IoSession session)
{
	session.closeNow();
}
 
Example 19
Source File: SslFilter.java    From jane with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
	SslHandler sslHandler = getSslSessionHandler(session);
	synchronized (sslHandler) {
		if (!isSslStarted(session) && sslHandler.isInboundDone()) {
			// The SSL session must be established first before we can push data to the application.
			// Store the incoming data into a queue for a later processing
			sslHandler.scheduleMessageReceived(nextFilter, message);
		} else {
			IoBuffer buf = (IoBuffer)message;
			boolean bufUsed = false;

			try {
				if (sslHandler.isOutboundDone()) {
					sslHandler.destroy();
					throw new SSLException("outbound done");
				}

				// forward read encrypted data to SSL handler
				sslHandler.messageReceived(nextFilter, buf.buf());

				// Handle data to be forwarded to application or written to net
				// LOGGER.debug("{}: Processing the SSL Data ", getSessionInfo(sslHandler.getSession()));

				// Flush any buffered write requests occurred before handshaking.
				if (sslHandler.isHandshakeComplete())
					sslHandler.flushPreHandshakeEvents();

				// Write encrypted data to be written (if any)
				sslHandler.writeNetBuffer(nextFilter, false);

				// handle app. data read (if any)
				IoBuffer readBuffer = sslHandler.fetchAppBuffer(); // forward read app data
				if (readBuffer.hasRemaining())
					sslHandler.scheduleMessageReceived(nextFilter, readBuffer);

				if (sslHandler.isInboundDone()) {
					if (sslHandler.isOutboundDone())
						sslHandler.destroy();
					else
						initiateClosure(nextFilter, session, false);

					if (buf.hasRemaining()) {
						bufUsed = true;
						sslHandler.scheduleMessageReceived(nextFilter, buf); // forward the data received after closure
					}
				}
			} catch (SSLException se) {
				if (!sslHandler.isHandshakeComplete()) {
					SSLException newSe = new SSLHandshakeException("SSL handshake failed");
					newSe.initCause(se);
					se = newSe;
					session.closeNow(); // close the session immediately, the handshake has failed
				} else
					sslHandler.release(); // free the SSL Handler buffers

				throw se;
			} finally {
				if (!bufUsed)
					buf.free();
			}
		}
	}

	sslHandler.flushScheduledEvents();
}
 
Example 20
Source File: DefaultProtocolHandler.java    From game-server with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public void exceptionCaught(IoSession session, Throwable throwable) {
	log.error("连接{}异常:{}", session, throwable);
	session.closeNow();
}