org.apache.mina.core.future.ConnectFuture Java Examples

The following examples show how to use org.apache.mina.core.future.ConnectFuture. 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: NioSession.java    From jane with GNU Lesser General Public License v3.0 6 votes vote down vote up
NioSession(AbstractIoService service, SocketChannel channel, ConnectFuture future) {
	this.service = service;
	this.channel = channel;
	config = new SessionConfigImpl(service);
	IoSessionDataStructureFactory factory = service.getSessionDataStructureFactory();
	attributes = factory.getAttributeMap(this);
	writeRequestQueue = factory.getWriteRequestQueue(this);
	if (future != null) {
		// DefaultIoFilterChain will notify the future. (We support ConnectFuture only for now).
		setAttribute(DefaultIoFilterChain.SESSION_CREATED_FUTURE, future);
		// In case that ConnectFuture.cancel() is invoked before setSession() is invoked,
		// add a listener that closes the connection immediately on cancellation.
		future.addListener((ConnectFuture cf) -> {
			if (cf.isCanceled())
				closeNow();
		});
	}
}
 
Example #2
Source File: ReqSession.java    From sumk with Apache License 2.0 6 votes vote down vote up
private void connect(SocketConnector connector) throws InterruptedException {

		if (session == null || session.isClosing()) {
			Logs.rpc().debug("create session for {}", addr);
			ConnectFuture cf = connector.connect(addr.toInetSocketAddress());

			cf.await(connector.getConnectTimeoutMillis() + 1);
			IoSession se = cf.getSession();
			if (se != null) {
				this.session = se;
				return;
			}
			cf.cancel();

		}
	}
 
Example #3
Source File: MinaNetClient.java    From Lealone-Plugins with Apache License 2.0 6 votes vote down vote up
@Override
protected void createConnectionInternal(NetNode node, AsyncConnectionManager connectionManager,
        AsyncCallback<AsyncConnection> ac) {
    InetSocketAddress inetSocketAddress = node.getInetSocketAddress();
    ConnectFuture future = connector.connect(inetSocketAddress);
    future.addListener(f -> {
        if (f.isDone()) {
            IoSession session = future.getSession();
            MinaWritableChannel writableChannel = new MinaWritableChannel(session);
            AsyncConnection conn;
            if (connectionManager != null) {
                conn = connectionManager.createConnection(writableChannel, false);
            } else {
                conn = new TcpClientConnection(writableChannel, this);
            }
            conn.setInetSocketAddress(inetSocketAddress);
            conn = addConnection(inetSocketAddress, conn);
            ac.setAsyncResult(conn);
        }
    });
}
 
Example #4
Source File: TCPTestClient.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
public synchronized void connect() throws InterruptedException {
    for (int i = 0; i < 5; i++) {
        try {
            TRACE.info("Attempting to connect to test collector: " + addr);
            ConnectFuture future = connector.connect(addr);
            future.awaitUninterruptibly();
            session = future.getSession();
            TRACE.info("Connected to test collector: " + addr);
            return;
        } catch (RuntimeIoException e) {
            e.printStackTrace(System.err);
            if (i < 4) {
                TRACE.warning("Failed to connect to test collector - retrying: " + addr);
                Thread.sleep(1000);
            } else {
                TRACE.severe("Failed to connect to test collector: " + addr);
                throw e;
            }
        }
    }
    
}
 
Example #5
Source File: Robot.java    From jforgame with Apache License 2.0 6 votes vote down vote up
public void doConnection() {
	NioSocketConnector connector = new NioSocketConnector();
	connector.getFilterChain().addLast("codec",
			new ProtocolCodecFilter(SerializerHelper.getInstance().getCodecFactory()));
	connector.setHandler(new ClientHandler());

	System.out.println("开始连接socket服务端");
	int serverPort = ServerConfig.getInstance().getServerPort();
	ConnectFuture future = connector.connect(new InetSocketAddress(serverPort));

	future.awaitUninterruptibly();

	IoSession session = future.getSession();
	this.session = new RobotSession(this, session);

	this.session.registerMessageHandler();

	this.login();
}
 
Example #6
Source File: HelloTcpClient.java    From mina-examples with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	NioSocketConnector connector = new NioSocketConnector(); //TCP Connector
	connector.getFilterChain().addLast("logging", new LoggingFilter());
	connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
    connector.getFilterChain().addLast("mdc", new MdcInjectionFilter());
	connector.setHandler(new HelloClientHandler());
    IoSession session;

    for (;;) {
        try {
            ConnectFuture future = connector.connect(new InetSocketAddress(HOSTNAME, PORT));
            future.awaitUninterruptibly();
            session = future.getSession();
            break;
        } catch (RuntimeIoException e) {
            System.err.println("Failed to connect.");
            e.printStackTrace();
        }
    }
    session.getCloseFuture().awaitUninterruptibly();
    connector.dispose();
}
 
Example #7
Source File: UDPConduit.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void close(Message msg) throws IOException {
    super.close(msg);
    if (msg.getExchange().isOneWay()
        || msg.getExchange().getInMessage() == msg
        || msg.getExchange().getInFaultMessage() == msg) {
        String s = (String)msg.getExchange().get(HOST_PORT);
        ConnectFuture c = msg.getExchange().get(ConnectFuture.class);
        if (s != null && c != null) {
            c.getSession().removeAttribute(CXF_MESSAGE_ATTR);

            Queue<ConnectFuture> q = connections.get(s);
            if (q == null) {
                connections.putIfAbsent(s, new ArrayBlockingQueue<ConnectFuture>(10));
                q = connections.get(s);
            }
            if (!q.offer(c)) {
                c.getSession().closeOnFlush();
            }
        }
    }
}
 
Example #8
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 #9
Source File: ClientBaseConnection.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private synchronized void startConnect ( final InetAddress address )
{
    logger.debug ( "Start connection to {}", address );

    setState ( ConnectionState.CONNECTING, null );
    this.connectFuture = this.connector.connect ( new InetSocketAddress ( address, this.connectionInformation.getSecondaryTarget () ) );
    logger.trace ( "Returned from connect call" );
    this.connectFuture.addListener ( new IoFutureListener<ConnectFuture> () {

        @Override
        public void operationComplete ( final ConnectFuture future )
        {
            handleConnectComplete ( future );
        }
    } );
    logger.trace ( "Future listener registered" );
}
 
Example #10
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private void callNextExceptionCaught(Entry entry, IoSession session, Throwable cause) {
    // Notify the related future.
    ConnectFuture future = (ConnectFuture) session.removeAttribute(SESSION_CREATED_FUTURE);
    if (future == null) {
        try {
            IoFilter filter = entry.getFilter();
            NextFilter nextFilter = entry.getNextFilter();
            filter.exceptionCaught(nextFilter, session, cause);
        } catch (Throwable e) {
            LOGGER.warn("Unexpected exception from exceptionCaught handler.", e);
        }
    } else {
        // Please note that this place is not the only place that
        // calls ConnectFuture.setException().
        session.close(true);
        future.setException(cause);
    }
}
 
Example #11
Source File: MinaClient.java    From java-study with Apache License 2.0 6 votes vote down vote up
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 = future.getSession();// 获得session
        String msg="hello \r\n";
        session.write(msg);// 发送消息
        logger.info("客户端与服务端建立连接成功...发送的消息为:"+msg);
    } catch (Exception e) {
    	e.printStackTrace();
        logger.error("客户端链接异常...", e);
    }
    session.getCloseFuture().awaitUninterruptibly();// 等待连接断开
    connector.dispose();
}
 
Example #12
Source File: MinaClient.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
public MinaClient(String server, int port) {

		p = new Player();
		connector = new NioSocketConnector();
		connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
		connector.setHandler(adapter);

		ConnectFuture connFuture = connector.connect(new InetSocketAddress(server, port));
		connFuture.awaitUninterruptibly();
		session = connFuture.getSession();
	}
 
Example #13
Source File: AbstractTcpClient.java    From util with Apache License 2.0 5 votes vote down vote up
/**
 * Create the UdpClient's instance
 */
public AbstractTcpClient() {
    connector = new NioSocketConnector();
    connector.setHandler(this);
    ConnectFuture connFuture = connector.connect(new InetSocketAddress(getServerIp(), getServerPort()));
    connFuture.awaitUninterruptibly();
    session = connFuture.getSession();
}
 
Example #14
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 #15
Source File: TestReloadClassLoader.java    From gameserver with Apache License 2.0 5 votes vote down vote up
@Test
	public void testClassLoaderLeak2() throws Exception {
		int max = 10000;
		File sourceFile = new File(reloadSourceDir);
		URL[] urls = new URL[]{sourceFile.toURL()};
//		ReloadProtocolCodecFilter filter = ReloadProtocolCodecFilter.getInstance(
//				GameServer.PROTOCOL_CODEC, GameServer.PROTOCOL_HANDLER, urls);
		SocketConnector connector = new NioSocketConnector();
//		connector.getFilterChain().addLast("codec", filter);
		connector.setHandler(new ClientHandler());
    //Send 1000 connections.
    try {
			for ( int i=0; i<Integer.MAX_VALUE; i++ ) {
				ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 3443));
				future.awaitUninterruptibly();
				IoSession session = future.getSession();
				IoBuffer buffer = IoBuffer.allocate(8);
				buffer.putShort((short)8);
				buffer.putShort((short)0);
				buffer.putInt(i);
				WriteFuture wfuture = session.write(buffer);
				wfuture.awaitUninterruptibly();
			}
		} catch (Exception e) {
			e.printStackTrace();
			fail();
		}
	}
 
Example #16
Source File: UDPConduit.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void close() {
    super.close();
    for (Queue<ConnectFuture> f : connections.values()) {
        for (ConnectFuture cf : f) {
            cf.getSession().closeOnFlush();
        }
    }
    connections.clear();
    connector.dispose();
    connector = null;
}
 
Example #17
Source File: TestClient.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected int onConnectFailed(ConnectFuture future, InetSocketAddress address, int count, Object ctx)
{
	Log.error("{}: onConnectFailed: addr={},count={}", getName(), address, count);
	int sec = 1 << count;
	return (sec < MAX_CONNECT_DELAY_SEC ? sec : MAX_CONNECT_DELAY_SEC) * 1000;
}
 
Example #18
Source File: TestEcho.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public synchronized ConnectFuture startClient(InetSocketAddress addr)
{
	// setIoThreadCount(TEST_THREAD_COUNT / 2);
	getConnector().setSessionDataStructureFactory(_dsFactory);
	getClientConfig().setTcpNoDelay(true);
	return super.startClient(addr);
}
 
Example #19
Source File: NioSocketConnector.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public ConnectFuture connect(InetSocketAddress remoteAddress, InetSocketAddress localAddress) {
	if (isDisposing())
		throw new IllegalStateException("disposed connector");
	if (remoteAddress == null)
		throw new IllegalArgumentException("null remoteAddress");
	if (getHandler() == null)
		throw new IllegalStateException("null handler");

	SocketChannel channel = null;
	try {
		channel = SocketChannel.open();

		int receiveBufferSize = getSessionConfig().getReceiveBufferSize();
		if (receiveBufferSize > 65535)
			channel.socket().setReceiveBufferSize(receiveBufferSize);

		if (localAddress != null) {
			try {
				channel.socket().bind(localAddress);
			} catch (IOException ioe) {
				// Add some info regarding the address we try to bind to the message
				throw new IOException("error while binding on " + localAddress + "\noriginal message: " + ioe.getMessage(), ioe);
			}
		}

		channel.configureBlocking(false);
		if (channel.connect(remoteAddress)) {
			ConnectFuture future = new DefaultConnectFuture();
			processor.add(new NioSession(this, channel, future));
			return future;
		}
	} catch (Exception e) {
		close(channel);
		return DefaultConnectFuture.newFailedFuture(e);
	}

  		return connect0(channel, true);
}
 
Example #20
Source File: Client.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public Client(ArrayList<Class> testCases, String host, int port, boolean longRunning) 
			throws Exception {
	
	// Set up
	this.longRunning = longRunning;
	this.testcaseClasses = testCases;
	this.testcases = new ArrayList(this.testcaseClasses.size());
	for ( int i=0; i<this.testcaseClasses.size(); i++ ) {
		this.testcases.add(this.testcaseClasses.get(i).newInstance());
		logger.info("testcase: " + this.testcaseClasses.get(i));
	}
	this.context = new EnumMap<ContextKey, Object>(ContextKey.class);
	
	connector = new NioSocketConnector();
	connector.getFilterChain().addLast("codec", 
			new ProtocolCodecFilter(new ProtobufEncoder(), new ProtobufDecoder()));
	connector.setHandler(this);
	
	// Make a new connection
   ConnectFuture connectFuture = connector.connect(new InetSocketAddress(host, port));
   // Wait until the connection is make successfully.
   connectFuture.awaitUninterruptibly(CONNECT_TIMEOUT);
   try {
       session = connectFuture.getSession();
       logger.info("client connected");
   }
   catch (RuntimeIoException e) {
   	e.printStackTrace();
   	if ( session != null ) {
   		session.close();
   	}
   }
}
 
Example #21
Source File: AbstractPollingIoConnector.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public ConnectionRequest(H handle, IoSessionInitializer<? extends ConnectFuture> callback) {
    this.handle = handle;
    long timeout = getConnectTimeoutMillis();
    if (timeout <= 0L) {
        this.deadline = Long.MAX_VALUE;
    } else {
        this.deadline = System.currentTimeMillis() + timeout;
    }
    this.sessionInitializer = callback;
}
 
Example #22
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 #23
Source File: AbstractClient.java    From JobX with Apache License 2.0 5 votes vote down vote up
public ConnectFuture getConnect(Request request) {
    connectLock.lock();
    try {
        MinaConnectWrapper minaConnectWrapper = (MinaConnectWrapper) this.channelTable.get(request.getAddress());
        if (minaConnectWrapper != null && minaConnectWrapper.isActive()) {
            return minaConnectWrapper.getConnectFuture();
        }
        this.doConnect(request);
        ConnectFuture connectFuture = connector.connect(HttpUtils.parseSocketAddress(request.getAddress()));
        minaConnectWrapper = new MinaConnectWrapper(connectFuture);
        if (connectFuture.awaitUninterruptibly(Constants.RPC_TIMEOUT)) {
            if (minaConnectWrapper.isActive()) {
                if (logger.isInfoEnabled()) {
                    logger.info("[JobX] MinaRPC getConnect: connect remote host[{}] success, {}", request.getAddress(), connectFuture.toString());
                }
                this.channelTable.put(request.getAddress(), minaConnectWrapper);
                return connectFuture;
            } else {
                if (logger.isWarnEnabled()) {
                    logger.warn("[JobX] MinaRPC getConnect: connect remote host[" + request.getAddress() + "] failed, " + connectFuture.toString(), connectFuture.getException());
                }
            }
        } else {
            if (logger.isWarnEnabled()) {
                logger.warn("[JobX] MinaRPC getConnect: connect remote host[{}] timeout {}ms, {}", request.getAddress(), Constants.RPC_TIMEOUT, connectFuture);
            }
        }
    }finally {
        connectLock.unlock();
    }
    return null;
}
 
Example #24
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 #25
Source File: ClientTestServer.java    From java-study with Apache License 2.0 5 votes vote down vote up
public IoSession getIOSession(IoConnector connector){  
    ConnectFuture future = connector.connect(new InetSocketAddress("192.168.2.55", 1255));   
    // 等待是否连接成功,相当于是转异步执行为同步执行。   
    future.awaitUninterruptibly();   
    // 连接成功后获取会话对象。 如果没有上面的等待, 由于connect()方法是异步的, session可能会无法获取。   
    IoSession session = null;  
    try{  
        session = future.getSession();  
    }catch(Exception e){  
        e.printStackTrace();  
    }  
    return session;  
}
 
Example #26
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 #27
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 #28
Source File: StreamBaseDevice.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public synchronized void connect ()
{
    if ( isConnected () )
    {
        logger.info ( "Already connected" );
        return;
    }

    if ( this.connector == null )
    {
        this.connector = new NioSocketConnector ();
        this.connector.setHandler ( this );
        if ( Boolean.getBoolean ( "org.eclipse.scada.da.server.io.common.trace" ) )
        {
            this.connector.getFilterChain ().addLast ( "logger", new LoggingFilter () );
        }
        setupConnector ( this.connector );
    }

    final ConnectFuture cu = this.connector.connect ( this.address );
    cu.addListener ( new IoFutureListener<ConnectFuture> () {

        @Override
        public void operationComplete ( final ConnectFuture future )
        {
            try
            {
                future.getSession ();
            }
            catch ( final Throwable e )
            {
                StreamBaseDevice.this.fireConnectionFailed ( e );
            }
        }
    } );
}
 
Example #29
Source File: ClientBaseConnection.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected synchronized void handleConnectComplete ( final ConnectFuture future )
{
    logger.debug ( "Connection attempt complete: {}", future );

    if ( this.connectFuture != future )
    {
        logger.warn ( "handleConnectComplete got called with wrong future - current: {}, called: {}", this.connectFuture, future );
        return;
    }

    this.connectFuture = null;

    final Throwable error = future.getException ();
    if ( error != null )
    {
        setState ( ConnectionState.CLOSED, error );
        return;
    }

    try
    {
        setSession ( future.getSession () );
    }
    catch ( final Throwable e )
    {
        setState ( ConnectionState.CLOSED, e );
    }

    logger.debug ( "Connection established" );
}
 
Example #30
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception {
    try {
        session.getHandler().sessionCreated(session);
    } finally {
        // Notify the related future.
        ConnectFuture future = (ConnectFuture) session.removeAttribute(SESSION_CREATED_FUTURE);
        if (future != null) {
            future.setSession(session);
        }
    }
}