Java Code Examples for org.apache.mina.core.future.ConnectFuture#isConnected()

The following examples show how to use org.apache.mina.core.future.ConnectFuture#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: AbstractMINAService.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
public void connect(long timeout) throws Exception {
    logger.info("Connecting to - {}:{}", getHostname(), getPort());

    preConnect();

    ConnectFuture connectFuture = getConnectFuture();
    connectFuture.awaitUninterruptibly(timeout);

    if(!connectFuture.isConnected()) {
        handleNotConnected(connectFuture.getException());
        return;
    }
    changeStatus(status -> status == ServiceStatus.WARNING, ServiceStatus.STARTED, "Service connected");

    session = createSession(connectFuture.getSession());
    postConnect();

    logger.info("Connected to - {}:{}", getHostname(), getPort());
}
 
Example 2
Source File: MinaClient.java    From JobX with Apache License 2.0 5 votes vote down vote up
@Override
public Response sentSync(final Request request) throws Exception {
    final ConnectFuture connect = super.getConnect(request);
    if (connect != null && connect.isConnected()) {
        RpcFuture rpcFuture = new RpcFuture(request);
        //写数据
        connect.addListener(new AbstractClient.FutureListener(rpcFuture));
        IoSession session = connect.getSession();
        session.write(request);
        return rpcFuture.get();
    } else {
        throw new IllegalArgumentException("[JobX] MinaRPC channel not active. request id:" + request.getId());
    }
}
 
Example 3
Source File: MinaClient.java    From JobX with Apache License 2.0 5 votes vote down vote up
@Override
public void sentAsync(final Request request, final InvokeCallback callback) throws Exception {
    final ConnectFuture connect = super.getConnect(request);
    if (connect != null && connect.isConnected()) {
        RpcFuture rpcFuture = new RpcFuture(request,callback);
        connect.addListener(new AbstractClient.FutureListener(rpcFuture));
        connect.getSession().write(request);
    } else {
        throw new IllegalArgumentException("[JobX] MinaRPC invokeAsync channel not active. request id:" + request.getId());
    }
}
 
Example 4
Source File: MinaClient.java    From JobX with Apache License 2.0 5 votes vote down vote up
@Override
public void sentOneWay(final Request request) throws Exception {
    ConnectFuture connect = super.getConnect(request);
    if (connect != null && connect.isConnected()) {
        RpcFuture rpcFuture = new RpcFuture(request);
        connect.addListener(new AbstractClient.FutureListener(rpcFuture));
        connect.getSession().write(request);
    } else {
        throw new IllegalArgumentException("[JobX] MinaRPC channel not active. request id:" + request.getId());
    }
}
 
Example 5
Source File: MinaClient.java    From grain with MIT License 5 votes vote down vote up
/**
 * 守护,启动链接、断线重连
 */
@Override
public void run() {
	while (true) {
		Set<IoConnector> keySet = ioConnectorMap.keySet();
		Iterator<IoConnector> iterator = keySet.iterator();
		for (int i = 0; i < keySet.size(); i++) {
			IoConnector ioConnector = iterator.next();
			InetSocketAddress inetSocketAddress = ioConnectorMap.get(ioConnector);
			boolean isConnected = ioConnectorStateMap.get(ioConnector);
			if (!isConnected) {
				ConnectFuture connectFuture = ioConnector.connect(inetSocketAddress);
				connectFuture.awaitUninterruptibly();
				if (!connectFuture.isConnected()) {
					connectFuture.cancel();
					if (MinaConfig.log != null) {
						MinaConfig.log.info("连接" + inetSocketAddress.toString() + "失败");
					}
				} else {
					ioConnectorStateMap.put(ioConnector, true);
					if (MinaConfig.log != null) {
						MinaConfig.log.info("连接" + inetSocketAddress.toString() + "成功");
					}
				}
			}
		}
		try {
			Thread.sleep(MinaClient.MINA_CLIENT_RECONNECT_INTERVAL);
		} catch (InterruptedException e) {
			if (MinaConfig.log != null) {
				MinaConfig.log.error("守护线程minaclient异常", e);
			}
		}
	}
}
 
Example 6
Source File: NetSupport.java    From TestClient with Apache License 2.0 5 votes vote down vote up
public boolean connect(NioSocketConnector connector, SocketAddress address) {
	if(!isSetChain){
		throw new IllegalStateException(
                "please set ConservationChain first !");
	}
    if (session != null && session.isConnected()) {
        throw new IllegalStateException(
                "Already connected. Disconnect first.");
    }

    try {

        IoFilter CODEC_FILTER = new ProtocolCodecFilter(
                new GameProtocolcodecFactory());
        
        connector.getFilterChain().addLast("codec", CODEC_FILTER);

        connector.setHandler(handler);
        ConnectFuture future1 = connector.connect(address);
        future1.awaitUninterruptibly();
        if (!future1.isConnected()) {
            return false;
        }
        session = future1.getSession();
       
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example 7
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 8
Source File: LdapNetworkConnection.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean connect() throws LdapException
{
    if ( isConnected() )
    {
        // No need to connect if we already have a connected session
        return true;
    }
    
    // Create the connector if needed
    if ( connector == null )
    {
        createConnector();
    }

    // And create the connection future
    ConnectFuture connectionFuture = tryConnect();

    // Check if we are good to go
    if ( !connectionFuture.isConnected() )
    {
        // Release the latch
        connectionCloseFuture.cancel( true );
        
        close( connectionFuture );
    }

    // Check if we are secured if requested
    if ( config.isUseSsl() )
    {
        checkSecured( connectionFuture );
    }

    // Add a listener to close the session in the session.
    setCloseListener( connectionFuture );

    // Get back the session
    ioSession = connectionFuture.getSession();

    // Store the container into the session if we don't have one
    setBinaryDetector();

    // Initialize the MessageId
    messageId.set( 0 );
    
    connectionCloseFuture = new CompletableFuture<>();

    // And return
    return true;
}
 
Example 9
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);
        }
    }