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

The following examples show how to use org.apache.mina.core.future.ConnectFuture#getSession() . 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: 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 2
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 3
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 4
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 5
Source File: MinaClient.java    From java-study with Apache License 2.0 6 votes vote down vote up
@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 = future.getSession();// 获得session
       
   	bindstart();
   	pushstart();
   }
 
Example 6
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 7
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 8
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 9
Source File: GameClient.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
	 * Connect to remote message server.
	 * @return
	 */
	public boolean connectToServer() {
		try {
			resourceLock.lock();
			
			if ( log.isInfoEnabled() ) {
				log.info("Connect to message server : " + remoteHost + ":" + remotePort);
			}
			connector = new NioSocketConnector();
			connector.getFilterChain().addLast("codec", new GameProtocolCodecFilter());
			connector.setHandler(this.handler);
			int heartBeatSecond = GlobalConfig.getInstance().getIntProperty("message.heartbeat.second");
			if ( log.isDebugEnabled() ) {
				log.debug("heartBeatSecond : " + heartBeatSecond);
			}
			connector.getSessionConfig().setBothIdleTime(heartBeatSecond);
			
			// Make a new connection
	    ConnectFuture connectFuture = connector.connect(new InetSocketAddress(remoteHost, remotePort));
	    // Wait until the connection is make successfully.
	    connectFuture.awaitUninterruptibly(CONNECT_TIMEOUT);
	    try {
	        session = connectFuture.getSession();
	        //Tell caller we can write message.
//	        connectedCond.signal();
	        if ( log.isInfoEnabled() ) {
	        	log.info("connect to " + remoteHost + ":" + remotePort);
	        }
	        return true;
	    }
	    catch (Throwable e) {
	  		disconnectFromServer();
	  		return false;
	    }
		} finally {
			resourceLock.unlock();
		}
	}
 
Example 10
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 11
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 12
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 13
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 14
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 15
Source File: ClientPlayer.java    From jforgame with Apache License 2.0 5 votes vote down vote up
public void buildConnection() {
	NioSocketConnector connector = new NioSocketConnector();
	connector.getFilterChain().addLast("codec",
			new ProtocolCodecFilter(SerializerHelper.getInstance().getCodecFactory()));
	connector.setHandler(new ClientHandler());

	int serverPort = ServerConfig.getInstance().getServerPort();
	System.out.println("开始连接游戏服务器端口" + serverPort);
	ConnectFuture future = connector.connect(new InetSocketAddress(serverPort));
	
	future.awaitUninterruptibly();
	IoSession session = future.getSession();
	this.session = session;
}
 
Example 16
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 17
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 18
Source File: MyClient.java    From jlogstash-input-plugin with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {    
    // 创建一个非组设的客户端客户端     
    IoConnector connector = new NioSocketConnector();    
    // 设置链接超时时间     
    connector.setConnectTimeoutMillis(30000);    
    // 添加过滤器     
    connector.getFilterChain().addLast( // 添加消息过滤器     
            "codec",    
            // Mina自带的根据文本换行符编解码的TextLineCodec过滤器 看到\r\n就认为一个完整的消息结束了  
            new ProtocolCodecFilter(new TextLineCodecFactory(Charset    
                    .forName("UTF-8"), LineDelimiter.MAC.getValue(),    
                    LineDelimiter.MAC.getValue())));    
    // 添加业务逻辑处理器类     
    connector.setHandler(new ClientMessageHandler());    
    IoSession session = null;    
    try {    
        ConnectFuture future = connector.connect(new InetSocketAddress(    
                HOST, PORT));    
        future.awaitUninterruptibly(); // 等待连接创建完成     
        session = future.getSession();
        long t1 = System.currentTimeMillis();
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<200000;i++){
        	System.out.println(i);
        	sb.append("ysqysq nginx_ccc [0050d2bf234311e6ba8cac853da49b78 type=nginx_access_log tag=\"mylog\"] /Users/sishuyss/ysq_access/$2016-04-05T11:12:24.230148+08:00/$100.97.184.152 - - [25/May/2016:01:10:07 +0800] \"GET /index.php?disp=dynamic HTTP/1.0\" 301 278 \"http://log.dtstack.com/\" \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;Alibaba.Security.Heimdall.1142964)\" 121.42.0.85 - - - 0").append(LineDelimiter.UNIX.getValue());
        	if(i%200==0){
                session.write(sb.toString()); 
                sb =  new StringBuffer();
        	}
        }
        session.write(sb.toString()); 
        System.out.println("time:"+(System.currentTimeMillis()-t1));
    } catch (Exception e) {   
    	System.out.println(e.getCause());
        logger.info("客户端链接异常...");    
    }    

    session.getCloseFuture().awaitUninterruptibly();    
    logger.info("Mina要关闭了");    
    connector.dispose();    
}
 
Example 19
Source File: MinaConnectWrapper.java    From JobX with Apache License 2.0 4 votes vote down vote up
public MinaConnectWrapper(ConnectFuture connectFuture) {
    this.connectFuture = connectFuture;
    this.ioSession = connectFuture.getSession();
}
 
Example 20
Source File: LdapNetworkConnection.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * Verify that the connection has been secured, otherwise throw a meaningful exception
 * 
 * @exception LdapException If we weren't able to check that the connection is secured
 */
private void checkSecured( ConnectFuture connectionFuture ) throws LdapException
{
    try
    {
        boolean isSecured = handshakeFuture.get( timeout, TimeUnit.MILLISECONDS );

        if ( !isSecured )
        {
            // check for a specific cause
            Throwable cause = connectionFuture.getException();
            
            if ( cause == null && connectionFuture.getSession() != null )
            {
                cause = ( Throwable ) connectionFuture.getSession().getAttribute( EXCEPTION_KEY );
            }
            
            // Cancel the latch
            connectionCloseFuture.complete( 0 );

            // if there is no cause assume timeout
            if ( cause == null )
            {
                throw new LdapException( TIME_OUT_ERROR );
            }

            throw new LdapTlsHandshakeException( I18n.err( I18n.ERR_04120_TLS_HANDSHAKE_ERROR ), cause );
        }
    }
    catch ( Exception e )
    {
        if ( e instanceof LdapException )
        {
            throw ( LdapException ) e;
        }

        String msg = I18n.err( I18n.ERR_04122_SSL_CONTEXT_INIT_FAILURE );
        LOG.error( msg, e );
        throw new LdapException( msg, e );
    }
}