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

The following examples show how to use org.apache.mina.core.session.IoSession#isConnected() . 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: MassProtocolEncoder.java    From game-server with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * 编码,格式:数据长度|数据部分
 */
@Override
public void encode(IoSession session, Object obj, ProtocolEncoderOutput out)
        throws Exception {
    if (getOverScheduledWriteBytesHandler() != null && session.getScheduledWriteMessages() > getMaxScheduledWriteMessages() && getOverScheduledWriteBytesHandler().test(session)) {
        return;
    }
    IoBuffer buf = null;
    if (obj instanceof MassMessage) {
        buf = MsgUtil.toIobuffer((MassMessage) obj);
    } else {
        log.warn("未知的数据类型");
        return;
    }
    if (buf != null && session.isConnected()) {
        buf.rewind();
        out.write(buf);
        out.flush();
    }
}
 
Example 2
Source File: ServerInfo.java    From game-server with MIT License 6 votes vote down vote up
/**
 * 获取连接列表中最空闲的有效的连接
 *
 * @return
 */
@JSONField(serialize = false)
public IoSession getMostIdleIoSession() {
	if (sessions == null) {
		return null;
	}
	IoSession session = null;
	sessions.stream().sorted(MsgUtil.sessionIdleComparator);
	while (session == null && !sessions.isEmpty()) {
		session = sessions.poll();
		log.debug("空闲session {}", session.getId());
		if (session != null && session.isConnected()) {
			sessions.offer(session);
			break;
		}
	}
	return session;
}
 
Example 3
Source File: SimpleClient.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 * Invoked when any exception is thrown by user IoHandler implementation or by MINA. 
 * If cause is an instance of IOException, MINA will close the connection automatically.
 * 
 */
@Override
public void exceptionCaught(IoSession session, Throwable cause)
		throws Exception {

	if ( this.ioHandler != null ) {
		this.ioHandler.exceptionCaught(session, cause);
	}
	if ( logger.isDebugEnabled() ) {
		logger.debug(cause.getMessage(), cause);
	}
	if ( !session.isConnected() ) {
		if ( logger.isInfoEnabled() ) {
			logger.info("reconnect to server due to closed session");
		}
		try {
			resourceLock.lock();
			connectToServer();
		} finally {
			resourceLock.unlock();
		}
	}
}
 
Example 4
Source File: StatClient.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 * Invoked when any exception is thrown by user IoHandler implementation or
 * by MINA. If cause is an instance of IOException, MINA will close the
 * connection automatically.
 * 
 */
@Override
public void exceptionCaught(IoSession session, Throwable cause)
		throws Exception {
	try {
		Stat.getInstance().messageClientSentFail++;
		if (logger.isDebugEnabled()) {
			logger.debug("Caught Exception: {}", cause.getMessage());
		}
		if (!session.isConnected()) {
			if (logger.isInfoEnabled()) {
				logger.info("reconnect to stat server due to closed session");
			}
			disconnectFromServer();
			connectToServer();
		}
	} finally {
	}
}
 
Example 5
Source File: GameProxyClient.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 * Invoked when any exception is thrown by user IoHandler implementation or
 * by MINA. If cause is an instance of IOException, MINA will close the
 * connection automatically.
 * 
 */
@Override
public void exceptionCaught(IoSession session, Throwable cause)
		throws Exception {
	try {
		Stat.getInstance().gameClientSentFail++;
		if (logger.isDebugEnabled()) {
			logger.debug("Proxy Caught Exception: {}", cause.getMessage());
		}
		if (!session.isConnected()) {
			if (logger.isInfoEnabled()) {
				logger.info("Proxy reconnect to server due to closed session");
			}
			disconnectFromServer();
			connectToServer();
		}
	} finally {
	}
}
 
Example 6
Source File: MessageClient.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 * Invoked when any exception is thrown by user IoHandler implementation or
 * by MINA. If cause is an instance of IOException, MINA will close the
 * connection automatically.
 * 
 */
@Override
public void exceptionCaught(IoSession session, Throwable cause)
		throws Exception {
	try {
		Stat.getInstance().messageClientSentFail++;
		if (logger.isDebugEnabled()) {
			logger.debug("Caught Exception: {}", cause.getMessage());
		}
		if (!session.isConnected()) {
			if (logger.isInfoEnabled()) {
				logger.info("reconnect to server due to closed session");
			}
			disconnectFromServer();
			connectToServer();
		}
	} finally {
	}
}
 
Example 7
Source File: SslFilter.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
	SslHandler sslHandler = getSslSessionHandler(session);

	try {
		boolean needsFlush = true;
		synchronized (sslHandler) {
			if (!isSslStarted(session))
				sslHandler.scheduleFilterWrite(nextFilter, writeRequest);
			else if (session.containsAttribute(DISABLE_ENCRYPTION_ONCE)) { // don't encrypt the data if encryption is disabled
				session.removeAttribute(DISABLE_ENCRYPTION_ONCE); // remove the marker attribute because it is temporary
				sslHandler.scheduleFilterWrite(nextFilter, writeRequest);
			} else { // otherwise, encrypt the buffer
				if (sslHandler.isWritingEncryptedData())
					sslHandler.scheduleFilterWrite(nextFilter, writeRequest); // data already encrypted; simply return buffer
				else if (sslHandler.isHandshakeComplete()) { // SSL encrypt
					sslHandler.encrypt(((IoBuffer)writeRequest.writeRequestMessage()).buf());
					IoBuffer encryptedBuffer = sslHandler.fetchOutNetBuffer();
					sslHandler.scheduleFilterWrite(nextFilter, new EncryptedWriteRequest(writeRequest, encryptedBuffer));
				} else {
					if (session.isConnected())
						sslHandler.schedulePreHandshakeWriteRequest(nextFilter, writeRequest); // handshake not complete yet
					needsFlush = false;
				}
			}
		}

		if (needsFlush)
			sslHandler.flushScheduledEvents();
	} catch (SSLException se) {
		sslHandler.release();
		throw se;
	}
}
 
Example 8
Source File: MessageUtil.java    From CXTouch with GNU General Public License v3.0 5 votes vote down vote up
public static void sendMessage(IoSession session, Message message) throws MessageException {
    if (session == null || !session.isConnected()) {
        throw new MessageException("Connection is invalid!");
    }

    IoBuffer buffer = message.getBinary();
    buffer.flip();
    int size = buffer.remaining();
    WriteFuture future = session.write(buffer);

}
 
Example 9
Source File: HelloServerHandler.java    From mina-examples with MIT License 5 votes vote down vote up
/**
 * 广播到所有的会话
 * @param message
 */
public void broadCast(String message) {
       synchronized (sessions) {
           for (IoSession session : sessions) {
               if (session.isConnected()) {
                   session.write(message);
               }
           }
       }
   }
 
Example 10
Source File: ProxyFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Actually write data. Queues the data up unless it relates to the handshake or the 
 * handshake is done.
 * 
 * @param nextFilter the next filter in filter chain
 * @param session the session object
 * @param writeRequest the data to write
 * @param isHandshakeData true if writeRequest is written by the proxy classes.
 */
public void writeData(final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest,
        final boolean isHandshakeData) {
    ProxyLogicHandler handler = getProxyHandler(session);

    synchronized (handler) {
        if (handler.isHandshakeComplete()) {
            // Handshake is done - write data as normal
            nextFilter.filterWrite(session, writeRequest);
        } else if (isHandshakeData) {
            LOGGER.debug("   handshake data: {}", writeRequest.getMessage());

            // Writing handshake data
            nextFilter.filterWrite(session, writeRequest);
        } else {
            // Writing non-handshake data before the handshake finished
            if (!session.isConnected()) {
                // Not even connected - ignore
                LOGGER.debug(" Write request on closed session. Request ignored.");
            } else {
                // Queue the data to be sent as soon as the handshake completes
                LOGGER.debug(" Handshaking is not complete yet. Buffering write request.");
                handler.enqueueWriteRequest(nextFilter, writeRequest);
            }
        }
    }
}
 
Example 11
Source File: MimaTimeClient.java    From frameworkAggregate with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	IoConnector connector = new NioSocketConnector();
	connector.getFilterChain().addLast("logger", new LoggingFilter());
	connector.getFilterChain().addLast("codec",
			new ProtocolCodecFilter(new PrefixedStringCodecFactory(Charset.forName("UTF-8"))));
	connector.setHandler(new TimeClientHander());
	ConnectFuture connectFuture = connector.connect(new InetSocketAddress("127.0.0.1", PORT));
	// 等待建立连接
	connectFuture.awaitUninterruptibly();
	System.out.println("连接成功");
	IoSession session = connectFuture.getSession();
	Scanner sc = new Scanner(System.in);
	boolean quit = false;
	while (!quit) {
		String str = sc.next();
		if (str.equalsIgnoreCase("quit")) {
			quit = true;
		}
		session.write(str);
	}

	// 关闭
	if (session != null) {
		if (session.isConnected()) {
			session.getCloseFuture().awaitUninterruptibly();
		}
		connector.dispose(true);
	}

}
 
Example 12
Source File: MsgUtil.java    From game-server with MIT License 5 votes vote down vote up
/**
 * 获取IP地址
 *
 * @param session
 * @return
 */
   public static String getIp(IoSession session) {
	try {
		if (session != null && session.isConnected()) {
			String clientIP = ((InetSocketAddress) session.getRemoteAddress()).getAddress().getHostAddress();
			return clientIP;
		}
	} catch (Exception e) {
	}
	return "0.0.0.0";
}
 
Example 13
Source File: MinaClientService.java    From game-server with MIT License 5 votes vote down vote up
/**
 * 获取连接列表中最空闲的有效的连接
 *
 * @return a {@link org.apache.mina.core.session.IoSession} object.
 */
public IoSession getMostIdleIoSession() {
	IoSession session = null;
	while (session == null && !sessions.isEmpty()) {
		session = sessions.peek();
		if (session != null && session.isConnected()) {
			break;
		} else {
			sessions.poll();
		}
	}
	return session;
}
 
Example 14
Source File: CalculatorClient.java    From mina with Apache License 2.0 4 votes vote down vote up
@Override
    public void run() {
        IoConnector connector = new NioSocketConnector();
        connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);//设置连接超时时间(毫秒数)
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new CommandCodecFactory("UTF-8")));

        KeepAliveMessageFactoryImpl kamfi = new KeepAliveMessageFactoryImpl();
        KeepAliveFilter kaf = new KeepAliveFilter(kamfi, IdleStatus.READER_IDLE, KeepAliveRequestTimeoutHandler.CLOSE);
        /** 是否回发 */
        kaf.setForwardEvent(true);
        connector.getFilterChain().addLast("heart", kaf);

        connector.setHandler(new CalculatorClientHander());
        ConnectFuture connectFuture = connector.connect(new InetSocketAddress(IP, PORT));
        //等待建立连接
        connectFuture.awaitUninterruptibly();

        if(!connectFuture.isConnected()){
            log.debug("连接失败");
            return ;
        }
        log.debug("连接成功");

        IoSession session = connectFuture.getSession();

//        try {
//            Cmd1003 cmd1003 = (Cmd1003) CommandFactory.createCommand(CidConst.C1003);
//            cmd1003.getReqMsg().setCpu(0.3f);
//            cmd1003.getReqMsg().setDisk(0.24f);
//            cmd1003.getReqMsg().setMemory(0.41f);
//            session.write(cmd1003);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }


        //关闭
        if (session != null) {
            if (session.isConnected()) {
                session.getCloseFuture().awaitUninterruptibly();
            }
            connector.dispose(true);
        }
    }
 
Example 15
Source File: ReqSession.java    From sumk with Apache License 2.0 4 votes vote down vote up
public void close() {
	IoSession s = this.session;
	if (s != null && s.isConnected()) {
		this.session.closeNow();
	}
}
 
Example 16
Source File: SslFilter.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws SSLException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("{}: Writing Message : {}", getSessionInfo(session), writeRequest);
    }

    boolean needsFlush = true;
    SslHandler handler = getSslSessionHandler(session);
    synchronized (handler) {
        if (!isSslStarted(session)) {
            handler.scheduleFilterWrite(nextFilter, writeRequest);
        }
        // Don't encrypt the data if encryption is disabled.
        else if (session.containsAttribute(DISABLE_ENCRYPTION_ONCE)) {
            // Remove the marker attribute because it is temporary.
            session.removeAttribute(DISABLE_ENCRYPTION_ONCE);
            handler.scheduleFilterWrite(nextFilter, writeRequest);
        } else {
            // Otherwise, encrypt the buffer.
            IoBuffer buf = (IoBuffer) writeRequest.getMessage();

            if (handler.isWritingEncryptedData()) {
                // data already encrypted; simply return buffer
                handler.scheduleFilterWrite(nextFilter, writeRequest);
            } else if (handler.isHandshakeComplete()) {
                // SSL encrypt
                int pos = buf.position();
                handler.encrypt(buf.buf());
                buf.position(pos);
                IoBuffer encryptedBuffer = handler.fetchOutNetBuffer();
                handler.scheduleFilterWrite(nextFilter, new EncryptedWriteRequest(writeRequest, encryptedBuffer));
            } else {
                if (session.isConnected()) {
                    // Handshake not complete yet.
                    handler.schedulePreHandshakeWriteRequest(nextFilter, writeRequest);
                }
                needsFlush = false;
            }
        }
    }

    if (needsFlush) {
        handler.flushScheduledEvents();
    }
}
 
Example 17
Source File: MessageTransferHandler.java    From gameserver with Apache License 2.0 4 votes vote down vote up
/**
 * This will be called when a message delivered from other GameServers.
 */
@Override
public void messageReceived(IoSession session, Object message)
		throws Exception {
	/**
	 * Process the RawMessage protocol
	 */
	if ( message instanceof SessionRawMessage ) {
		SessionRawMessage rawMessage = (SessionRawMessage)message;
		SessionKey sessionKey = rawMessage.getSessionkey();
		
		if ( sessionKey.getRawKey() != null && sessionKey.getRawKey().length > 0 &&
				sessionKey.getRawKey()[0] == 0 ) {
			//It is a heart-beat messge. ignore it.
			if ( logger.isDebugEnabled() ) {
				logger.debug("Heartbeat message received from {}", session.getRemoteAddress());
			}
			Stat.getInstance().messageHearbeatReceived++;
			return;
		}
		
		IoSession userSession = null;
		try {
			userSession = messageQueue.findSession(sessionKey);
		} catch (Throwable t) {
			logger.warn("Exception: {}", t.getMessage());
			if ( logger.isDebugEnabled() ) {
				logger.debug(t.getMessage(), t);
			}
		}
		if ( userSession != null && userSession.isConnected() ) {
			byte[] rawMessageBytes = rawMessage.getRawMessage();
			if ( rawMessageBytes != null && rawMessageBytes.length > 0 ) {
				IoBuffer buf = IoBuffer.wrap(rawMessageBytes);
				messageQueue.sessionWrite(sessionKey, buf);
			} else {
				if ( logger.isDebugEnabled() ) {
					logger.debug("rawMessageBytes is null." + userSession);
				}
			}
		} else {
			if ( logger.isDebugEnabled() ) {
				logger.debug("User's IoSession is not connected." + userSession);
			}
		}
		Stat.getInstance().messageServerReceived++;
	}
}
 
Example 18
Source File: ClientProtocolEncoder.java    From game-server with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public void encode(IoSession session, Object obj, ProtocolEncoderOutput out) throws Exception {
	if (getOverScheduledWriteBytesHandler() != null
			&& session.getScheduledWriteMessages() > getMaxScheduledWriteMessages()
			&& getOverScheduledWriteBytesHandler().test(session)) {
		LOGGER.warn("{}消息{}大于最大累积{}",MsgUtil.getIp(session), session.getScheduledWriteMessages(),getMaxScheduledWriteMessages());
		return;
	}

	IoBuffer buf = null;
	if (obj instanceof Message) {
		buf = MsgUtil.toGameClientIobuffer((Message) obj);
	} else if (obj instanceof byte[]) {
		byte[] data = (byte[]) obj; // 消息ID(4字节)+protobuf
		buf = IoBuffer.allocate(data.length + 6);
		// 消息长度
		byte[] lengthBytes = IntUtil.short2Bytes((short) (data.length + 4), ByteOrder.LITTLE_ENDIAN);
		buf.put(lengthBytes);

		// 消息ID ,将顺序改变为前端客户端顺序
		byte[] idBytes = new byte[4];
		idBytes[0] = data[3];
		idBytes[1] = data[2];
		idBytes[2] = data[1];
		idBytes[3] = data[0];
		buf.put(idBytes);
		// protobuf长度
		int protobufLength = data.length - 4; // 移除消息ID长度
		buf.put(IntUtil.writeIntToBytesLittleEnding(protobufLength));
		// 数据
		buf.put(data, 4, protobufLength);

	}

	if (buf != null && session.isConnected()) {
		buf.rewind();
		out.write(buf);
		out.flush();
	}
}