Search in sources :

Example 1 with ConnectFuture

use of org.apache.mina.core.future.ConnectFuture in project camel by apache.

the class Mina2Producer method openConnection.

private void openConnection() {
    if (this.address == null || !this.configuration.isCachedAddress()) {
        setSocketAddress(this.configuration.getProtocol());
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating connector to address: {} using connector: {} timeout: {} millis.", address, connector, timeout);
    }
    // connect and wait until the connection is established
    if (connectorConfig != null) {
        connector.getSessionConfig().setAll(connectorConfig);
    }
    ConnectFuture future = connector.connect(address);
    future.awaitUninterruptibly();
    session = future.getSession();
}
Also used : ConnectFuture(org.apache.mina.core.future.ConnectFuture)

Example 2 with ConnectFuture

use of org.apache.mina.core.future.ConnectFuture in project opennms by OpenNMS.

the class AsyncBasicDetectorMinaImpl method isServiceDetected.

/**
 * {@inheritDoc}
 */
@Override
public final DetectFuture isServiceDetected(final InetAddress address) {
    final DetectFutureMinaImpl detectFuture = new DetectFutureMinaImpl(this);
    try {
        // Set this up here because it can throw an Exception, which we want
        // to throw now, not in initializeSession
        final SSLContext c = createClientSSLContext();
        // Create an IoSessionInitializer that will configure this individual
        // session. Previously, all this was done on a new Connector each time
        // but that was leaking file handles all over the place. This way gives
        // us per-connection settings without the overhead of creating new
        // Connectors each time
        IoSessionInitializer<ConnectFuture> init = new IoSessionInitializer<ConnectFuture>() {

            @Override
            public void initializeSession(IoSession session, ConnectFuture future) {
                // Add filters to the session
                if (isUseSSLFilter()) {
                    final SslFilter filter = new SslFilter(c);
                    filter.setUseClientMode(true);
                    session.getFilterChain().addFirst("SSL", filter);
                }
                session.getFilterChain().addLast("logger", getLoggingFilter() != null ? getLoggingFilter() : new SlightlyMoreVerboseLoggingFilter());
                session.getFilterChain().addLast("codec", getProtocolCodecFilter());
                // Make the minimum idle timeout 1 second
                int idleTimeInSeconds = Math.max(1, Math.round(getIdleTime() / 1000.0f));
                // Set all of the idle time limits. Make sure to specify values in
                // seconds!!!
                session.getConfig().setReaderIdleTime(idleTimeInSeconds);
                session.getConfig().setWriterIdleTime(idleTimeInSeconds);
                session.getConfig().setBothIdleTime(idleTimeInSeconds);
            }
        };
        // Start communication
        final InetSocketAddress socketAddress = new InetSocketAddress(address, getPort());
        final ConnectFuture cf = m_connectionFactory.connect(socketAddress, init, createDetectorHandler(detectFuture));
        cf.addListener(retryAttemptListener(detectFuture, socketAddress, init, getRetries()));
    } catch (KeyManagementException e) {
        detectFuture.setException(e);
    } catch (NoSuchAlgorithmException e) {
        detectFuture.setException(e);
    } catch (Throwable e) {
        detectFuture.setException(e);
    }
    return detectFuture;
}
Also used : SslFilter(org.apache.mina.filter.ssl.SslFilter) InetSocketAddress(java.net.InetSocketAddress) SSLContext(javax.net.ssl.SSLContext) ConnectFuture(org.apache.mina.core.future.ConnectFuture) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) IoSessionInitializer(org.apache.mina.core.session.IoSessionInitializer) IoSession(org.apache.mina.core.session.IoSession)

Example 3 with ConnectFuture

use of org.apache.mina.core.future.ConnectFuture in project opennms by OpenNMS.

the class ConnectionFactoryConnectorPoolImpl method connect.

/**
 * <p>Connect to a remote socket. If org.opennms.netmgt.provision.maxConcurrentConnections
 * is set, this may block until a connection slot is available.</p>
 *
 * <p>You must dispose both the {@link ConnectionFactoryConnectorPoolImpl} and {@link ConnectFuture} when done
 * by calling {@link #dispose(ConnectionFactoryConnectorPoolImpl, ConnectFuture)}.</p>
 *
 * @param remoteAddress
 * 		Destination address
 * @param init
 * 		Initialiser for the IoSession
 * @return
 * 		ConnectFuture from a Mina connect call
 */
@Override
public ConnectFuture connect(SocketAddress remoteAddress, IoSessionInitializer<? extends ConnectFuture> init, IoHandler handler) {
    for (int retries = 0; retries < 3; retries++) {
        synchronized (m_connectorMutex) {
            if (m_connector == null) {
                // Sanity check for null connector instance
                LOG.debug("Found a null NioSocketConnector, creating a new one with timeout {}", getTimeout());
                m_connector = getSocketConnector(getTimeout(), handler);
            }
            try {
                /*
                     * Set the handler each time since we are reusing this connector for every incoming
                     * connect() call.
                     */
                m_connector.setHandler(handler);
                InetSocketAddress localAddress = null;
                synchronized (m_portMutex) {
                    if (m_port == null) {
                        // Fetch a new ephemeral port
                        localAddress = new InetSocketAddress(InetAddressUtils.getLocalHostAddress(), 0);
                        m_port = localAddress.getPort();
                    } else {
                        localAddress = new InetSocketAddress(InetAddressUtils.getLocalHostAddress(), m_port);
                    }
                }
                /*
                     * Use the 3-argument call to connect(). If you use the 2-argument version without
                     * the localhost port, the call will end up doing a name lookup which seems to fail
                     * intermittently in unit tests.
                     *
                     * @see http://issues.opennms.org/browse/NMS-5309
                     */
                ConnectFuture cf = m_connector.connect(remoteAddress, localAddress, init);
                cf.addListener(portSwitcher(m_connector, remoteAddress, init, handler));
                return cf;
            } catch (Throwable e) {
                LOG.debug("Caught exception on factory {}, retrying: {}", this, e);
                m_connector.dispose();
                m_connector = getSocketConnector(getTimeout(), handler);
                continue;
            }
        }
    }
    throw new IllegalStateException("Could not connect to socket because of excessive RejectedExecutionExceptions");
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ConnectFuture(org.apache.mina.core.future.ConnectFuture)

Example 4 with ConnectFuture

use of org.apache.mina.core.future.ConnectFuture in project pancm_project by xuwujing.

the class MinaClient method main.

/**
 * The entry point of application.
 *
 * @param args the input arguments
 */
/*
    * 测试服务端与客户端程序!
    a. 启动服务端,然后再启动客户端(客户端发送的消息是"why are you so diao ")
    b. 服务端接收消息并处理成功;
    */
public static void main(String[] args) {
    // 创建一个非阻塞的客户端程序
    IoConnector connector = new NioSocketConnector();
    // 设置链接超时时间
    connector.setConnectTimeout(30000);
    ProtocolCodecFilter pf = new ProtocolCodecFilter((new MyTextLineCodecFactory(Charset.forName("utf-8"), "\r\n")));
    // 添加过滤器
    connector.getFilterChain().addLast("codec", pf);
    // 添加业务逻辑处理器类
    connector.setHandler(new MinaClientHandler());
    IoSession session = null;
    try {
        ConnectFuture future = connector.connect(new InetSocketAddress(HOST, // 创建连接
        PORT));
        // 等待连接创建完成
        future.awaitUninterruptibly();
        // 获得session
        session = future.getSession();
        String msg = "hello \r\n";
        // 发送消息
        session.write(msg);
        logger.info("客户端与服务端建立连接成功...发送的消息为:" + msg);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("客户端链接异常...", e);
    }
    // 等待连接断开
    session.getCloseFuture().awaitUninterruptibly();
    connector.dispose();
}
Also used : NioSocketConnector(org.apache.mina.transport.socket.nio.NioSocketConnector) InetSocketAddress(java.net.InetSocketAddress) ConnectFuture(org.apache.mina.core.future.ConnectFuture) IoConnector(org.apache.mina.core.service.IoConnector) ProtocolCodecFilter(org.apache.mina.filter.codec.ProtocolCodecFilter) IoSession(org.apache.mina.core.session.IoSession)

Example 5 with ConnectFuture

use of org.apache.mina.core.future.ConnectFuture in project pancm_project by xuwujing.

the class MinaClient method main.

/**
 * The entry point of application.
 *
 * @param args the input arguments
 */
/*
    * 测试服务端与客户端程序!
    a. 启动服务端,然后再启动客户端
    b. 服务端接收消息并处理成功;
    */
@SuppressWarnings("deprecation")
public static void main(String[] args) {
    // 设置链接超时时间
    connector.setConnectTimeout(30000);
    // 添加过滤器  可序列话的对象
    connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
    // 添加业务逻辑处理器类
    connector.setHandler(new MinaClientHandler());
    ConnectFuture future = connector.connect(new InetSocketAddress(HOST, // 创建连接
    PORT));
    // 等待连接创建完成
    future.awaitUninterruptibly();
    // 获得session
    session = future.getSession();
    bindstart();
    pushstart();
}
Also used : ObjectSerializationCodecFactory(org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory) InetSocketAddress(java.net.InetSocketAddress) ConnectFuture(org.apache.mina.core.future.ConnectFuture) ProtocolCodecFilter(org.apache.mina.filter.codec.ProtocolCodecFilter)

Aggregations

ConnectFuture (org.apache.mina.core.future.ConnectFuture)14 InetSocketAddress (java.net.InetSocketAddress)8 IoSession (org.apache.mina.core.session.IoSession)3 IOException (java.io.IOException)2 RuntimeIoException (org.apache.mina.core.RuntimeIoException)2 ProtocolCodecFilter (org.apache.mina.filter.codec.ProtocolCodecFilter)2 NioSocketConnector (org.apache.mina.transport.socket.nio.NioSocketConnector)2 ConnectException (java.net.ConnectException)1 SocketAddress (java.net.SocketAddress)1 URI (java.net.URI)1 UnresolvedAddressException (java.nio.channels.UnresolvedAddressException)1 KeyManagementException (java.security.KeyManagementException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 SSLContext (javax.net.ssl.SSLContext)1 BinaryAttributeDetector (org.apache.directory.api.ldap.codec.api.BinaryAttributeDetector)1 DefaultConfigurableBinaryAttributeDetector (org.apache.directory.api.ldap.codec.api.DefaultConfigurableBinaryAttributeDetector)1 LdapMessageContainer (org.apache.directory.api.ldap.codec.api.LdapMessageContainer)1 MessageDecorator (org.apache.directory.api.ldap.codec.api.MessageDecorator)1 SchemaBinaryAttributeDetector (org.apache.directory.api.ldap.codec.api.SchemaBinaryAttributeDetector)1 LdapOtherException (org.apache.directory.api.ldap.model.exception.LdapOtherException)1