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

The following examples show how to use org.apache.mina.core.session.IoSession#close() . 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: MinaServerHandle.java    From MiniWeChat-Server with MIT License 6 votes vote down vote up
/**
 * 异常捕捉
 * 
 * @author Feng
 */
@Override
public void exceptionCaught(IoSession session, Throwable cause) {
	if (cause.toString().equals("java.io.IOException: Connection reset by peer"))
		return;
	logger.error("throws exception");
	logger.error("session.toString() : " + session.toString());
	logger.error("cause.toString() : " + cause.toString());
	
	if (cause.toString().equals("java.io.IOException: 远程主机强迫关闭了一个现有的连接。")) {
		try {
			session.close();
		} catch (Exception e) {}
		return;
	}
	String exceptionStack = "";
	for (StackTraceElement element : cause.getStackTrace())
		exceptionStack += element.toString() + "\n";
	logger.error("stack : " + exceptionStack);
	logger.error("Report Error Over!!");
}
 
Example 2
Source File: StalledSessionsFilter.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest)
        throws Exception {
    if (!session.isClosing()) {
        // Get number of pending requests
        long pendingBytes = session.getScheduledWriteBytes();
        if (pendingBytes > bytesCap) {
            // Get last time we were able to send something to the connected client
            long writeTime = session.getLastWriteTime();
            int pendingRequests = session.getScheduledWriteMessages();
            Log.debug("About to kill session with pendingBytes: " + pendingBytes + " pendingWrites: " +
                    pendingRequests + " lastWrite: " + new Date(writeTime) + "session: " + session);
            // Close the session and throw an exception
            session.close(false);
            throw new IOException("Closing session that seems to be stalled. Preventing OOM");
        }
    }
    // Call next filter (everything is fine)
    super.filterWrite(nextFilter, session, writeRequest);
}
 
Example 3
Source File: MapleServerHandler.java    From HeavenMS with GNU Affero General Public License v3.0 6 votes vote down vote up
private void closeMapleSession(IoSession session) {
    if (isLoginServerHandler()) {
        MapleSessionCoordinator.getInstance().closeLoginSession(session);
    } else {
        MapleSessionCoordinator.getInstance().closeSession(session, null);
    }
    
    MapleClient client = (MapleClient) session.getAttribute(MapleClient.CLIENT_KEY);
    if (client != null) {
        try {
            // client freeze issues on session transition states found thanks to yolinlin, Omo Oppa, Nozphex
            if (!session.containsAttribute(MapleClient.CLIENT_TRANSITION)) {
                client.disconnect(false, false);
            }
        } catch (Throwable t) {
            FilePrinter.printError(FilePrinter.ACCOUNT_STUCK, t);
        } finally {
            session.close();
            session.removeAttribute(MapleClient.CLIENT_KEY);
            //client.empty();
        }
    }
}
 
Example 4
Source File: MassProtocolDecoder.java    From game-server with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
protected boolean doDecode(IoSession session, IoBuffer ib, ProtocolDecoderOutput out) throws Exception {
    if (ib.remaining() < 4) {
        return false;
    }
    ib.mark();
    int length = ib.getInt();
    if (length < 1 || length > maxReadSize) {
        int id = ib.getInt();
        ib.clear();
        log.warn("消息解析异常:长度{},id {}, 大于长度 maxReadSize {}", length, id, maxReadSize);
        session.close(true);
        return false;
    }

    if (ib.remaining() < length) {
        ib.reset();
        return false;
    }
    decodeBytes(length, ib, out);
    return true;
}
 
Example 5
Source File: HttpConfigHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 * Log the exception and close the session.
 */
@Override
public void exceptionCaught(IoSession session, Throwable cause)
		throws Exception {
	try {
		if ( cause.getClass() == SocketTimeoutException.class ) {
			Stat.getInstance().incHttpTimeouts();
		} else {
			//java.io.IOException: Connection reset by peer
			Stat.getInstance().incHttpReset();
		}
		if ( log.isDebugEnabled() ) {
			log.debug("HTTP exception: ", cause);
		}
		session.close(true);
	} catch (Throwable e) {
		if ( log.isWarnEnabled() ) {
			log.warn("Close session", e);
		}
	}
}
 
Example 6
Source File: GameHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
public void sessionIdle(IoSession session, IdleStatus status)
		throws Exception {
	if ( StatClient.getIntance().isStatEnabled() ) {
		SessionKey userSessionKey = (SessionKey)session.getAttribute(Constant.SESSION_KEY);
		if ( userSessionKey != null ) {
			User user = GameContext.getInstance().findLocalUserBySessionKey(userSessionKey);
			if ( user != null ) {
				GameContext.getInstance().deregisterUserBySessionKey(userSessionKey);
				logger.debug("User {} session is idle too much time. Close it.", user.getRoleName());
				
				StatClient.getIntance().sendDataToStatServer(user, StatAction.LogoutIdle);
			}
		}
	}
	try {
		session.close(false);
		//do cleaning
	} catch (Throwable e) {
	}
}
 
Example 7
Source File: MapleServerHandler.java    From mapleLemon with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void sessionClosed(final IoSession session) throws Exception {
    MapleClient client = (MapleClient) session.getAttribute(MapleClient.CLIENT_KEY);
    if (client != null) {
        try {
            int countRows = ManagerSin.jTable1.getRowCount();//获取当前表格总行数
            for (int i = 0; i < countRows; i++) {
                int AID = (Integer) ManagerSin.jTable1.getValueAt(i, 0);
                if (AID == client.getAccID()) {
                    ((DefaultTableModel) ManagerSin.jTable1.getModel()).removeRow(i);
                    break;
                }
            }
        } catch (Exception e) {
            FileoutputUtil.outputFileError(FileoutputUtil.GUI_Ex_Log, e);
        }

        try {
            client.disconnect(true, (channel == MapleServerHandler.CASH_SHOP_SERVER));
        } finally {
            World.Client.removeClient(client);
            session.close(true);
            session.removeAttribute(MapleClient.CLIENT_KEY);
            session.removeAttribute(MaplePacketDecoder.DECODER_STATE_KEY);
        }
    }
    super.sessionClosed(session);
}
 
Example 8
Source File: ServerBaseHandler.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void sessionOpened ( final IoSession session ) throws Exception
{
    try
    {
        final ServerConnection connection = this.server.createNewConnection ( session );
        session.setAttribute ( "connection", connection );
    }
    catch ( final Exception e )
    {
        session.write ( new CloseMessage ( "Failed to create server side connection: " + e, -1 ) );
        session.close ( false );
    }
}
 
Example 9
Source File: TimeServerHandler.java    From frameworkAggregate with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(IoSession session, Object message) throws Exception {

	String str = message.toString();
	System.out.println("接受到的消息:" + str);
	if (str.trim().equalsIgnoreCase("quit")) {
		session.close(true);
		return;
	}
	Date date = new Date();
	session.write(date.toString());
	System.out.println("Message written...");
}
 
Example 10
Source File: TftpTransferProtocolHandler.java    From tftp4j with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ConnectFuture future) {
    if (!future.isConnected()) {
        connector.dispose(false);
        return;
    }
    final IoSession session = future.getSession();
    try {
        // This does "real" I/O, so can really throw an exception.
        transfer.open(session);
    } catch (Exception e) {
        session.close(true);
    }
}
 
Example 11
Source File: MapleSessionCoordinator.java    From HeavenMS with GNU Affero General Public License v3.0 5 votes vote down vote up
public void closeSession(IoSession session, Boolean immediately) {
    MapleClient client = getSessionClient(session);
    if (client == null) {
        client = fetchInTransitionSessionClient(session);
    }
    
    String hwid = (String) session.removeAttribute(MapleClient.CLIENT_NIBBLEHWID); // making sure to clean up calls to this function on login phase
    onlineRemoteHwids.remove(hwid);
    
    hwid = (String) session.removeAttribute(MapleClient.CLIENT_HWID);
    onlineRemoteHwids.remove(hwid);
    
    if (client != null) {
        if (hwid != null) { // is a game session
            onlineClients.remove(client.getAccID());
        } else {
            MapleClient loggedClient = onlineClients.get(client.getAccID());
            
            // do not remove an online game session here, only login session
            if (loggedClient != null && loggedClient.getSessionId() == client.getSessionId()) {
                onlineClients.remove(client.getAccID());
            }
        }
    }
    
    if (immediately != null) {
        session.close(immediately);
    }
    
    // session.removeAttribute(MapleClient.CLIENT_REMOTE_ADDRESS); No real need for removing String property on closed sessions
}
 
Example 12
Source File: ModbusExport.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
protected void handleSessionIdle ( final IoSession session )
{
    logger.info ( "Closing session due to reader timeout" );
    session.close ( true );
}
 
Example 13
Source File: TftpTransferProtocolHandler.java    From tftp4j with Apache License 2.0 4 votes vote down vote up
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
    LOG.error("Exception caught in session " + session + ": " + cause, cause);
    session.close(true);
}
 
Example 14
Source File: BlacklistFilter.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
private void blockSession(IoSession session) {
    LOGGER.warn("Remote address in the blacklist; closing.");
    session.close(true);
}
 
Example 15
Source File: ExceptionHandler.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public void exceptionCaught(IoSession session, Throwable cause) {
    session.close(true);
}
 
Example 16
Source File: DhcpProtocolHandler.java    From dhcp4j with Apache License 2.0 4 votes vote down vote up
@Override
public void exceptionCaught(IoSession session, Throwable cause) {
    LOG.error("EXCEPTION CAUGHT ", cause);
    cause.printStackTrace(System.out);
    session.close(true);
}
 
Example 17
Source File: ITCHMulticastTCPHandlerAdapter.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
private IMessage onLogout(IMessage iMessage, IoSession session) {
    handleMessage(iMessage, true, true, session.getRemoteAddress().toString());
    session.close(true);
    return null;
}
 
Example 18
Source File: AbstractMINATCPServer.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
/**
 * Method body is copied from {@link IoHandlerAdapter#inputClosed(IoSession)}
 */
@Override
public void inputClosed(IoSession session) {
    logger.debug("Session input closed: {}", session);
    session.close(true);
}
 
Example 19
Source File: AbstractMINAService.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
/**
 * Method body is copied from {@link IoHandlerAdapter#inputClosed(IoSession)}
 */
@Override
public void inputClosed(IoSession session) throws Exception {
    logger.debug("Session input closed: {}", session);
    session.close(true);
}
 
Example 20
Source File: TftpServerProtocolHandler.java    From tftp4j with Apache License 2.0 4 votes vote down vote up
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
    TftpPacket packet = (TftpPacket) message;

    SocketAddress address = session.getRemoteAddress();
    LOG.info("Address is " + address);

    switch (packet.getOpcode()) {
        case RRQ: {
            TftpRequestPacket request = (TftpRequestPacket) packet;
            TftpData source = provider.open(request.getFilename());
            if (source == null) {
                session.write(new TftpErrorPacket(address, TftpErrorCode.FILE_NOT_FOUND), address);
                session.close(false);
            } else {
                final NioDatagramConnector connector = new NioDatagramConnector();
                TftpTransfer transfer = new TftpReadTransfer(address, source, request.getBlockSize());
                TftpTransferProtocolHandler handler = new TftpTransferProtocolHandler(connector, transfer);
                connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TftpProtocolCodecFactory()));
                connector.getFilterChain().addLast("logger-packet", new LoggingFilter("tftp-transfer-packet"));
                connector.setHandler(handler);
                ConnectFuture future = connector.connect(address);
                future.addListener(handler);
            }
            break;
        }
        case WRQ: {
            session.write(new TftpErrorPacket(address, TftpErrorCode.PERMISSION_DENIED), address);
            session.close(false);
            break;
        }
        case ACK: {
            break;
        }
        case DATA: {
            LOG.warn("Unexpected TFTP " + packet.getOpcode() + " packet: " + packet);
            session.write(new TftpErrorPacket(address, TftpErrorCode.ILLEGAL_OPERATION), address);
            session.close(false);
            break;
        }
        case ERROR: {
            TftpErrorPacket error = (TftpErrorPacket) packet;
            LOG.error("Received TFTP error packet: " + error);
            session.close(true);
            break;
        }
    }
}