Java Code Examples for org.apache.mina.transport.socket.nio.NioSocketConnector#connect()

The following examples show how to use org.apache.mina.transport.socket.nio.NioSocketConnector#connect() . 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: 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 2
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 3
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 4
Source File: Application1.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object start ( final IApplicationContext context ) throws Exception
{
    final NioSocketConnector connector = new NioSocketConnector ();

    connector.setHandler ( new SingleSessionIoHandlerDelegate ( new SingleSessionIoHandlerFactory () {

        @Override
        public SingleSessionIoHandler getHandler ( final IoSession session ) throws Exception
        {
            return new DaveHandler ( session );
        }
    } ) );

    connector.getFilterChain ().addLast ( "logger", new LoggingFilter ( this.getClass ().getName () ) );
    connector.getFilterChain ().addLast ( "tpkt", new TPKTFilter ( 3 ) );
    connector.getFilterChain ().addLast ( "cotp", new COTPFilter ( 0, (byte)3 ) );
    connector.getFilterChain ().addLast ( "dave", new DaveFilter () );

    connector.connect ( new InetSocketAddress ( "192.168.1.83", 102 ) );

    while ( this.running )
    {
        Thread.sleep ( 1000 );
    }

    return null;
}
 
Example 5
Source File: MinaTimeClient.java    From javabase with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	// 创建客户端连接器.
	NioSocketConnector connector = new NioSocketConnector();
	connector.getFilterChain().addLast("logger", new LoggingFilter());
	connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); // 设置编码过滤器
	connector.setConnectTimeout(30);
	connector.setHandler(new TimeClientHandler());// 设置事件处理器
	ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1", 9123));// 建立连接
	cf.awaitUninterruptibly();// 等待连接创建完成
	cf.getSession().write("hello");// 发送消息
	cf.getSession().write("quit");// 发送消息
	cf.getSession().getCloseFuture().awaitUninterruptibly();// 等待连接断开
	connector.dispose();
}
 
Example 6
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 7
Source File: DefaultRedisConnection.java    From Redis-Synyed with Apache License 2.0 5 votes vote down vote up
/**
 * 执行连接操作的方法
 * 
 * @throws RedisProtocolException
 *             当连接出现问题时抛出该异常
 */
private void connect() throws RedisProtocolException {
	connector = new NioSocketConnector();
	connector.setConnectTimeoutMillis(connectionTimeOut);
	connector.getFilterChain().addFirst("redis-protocol", new ProtocolCodecFilter(new RedisProtocolCodecFactory()));
	connector.setHandler(this);
	connector.connect(new InetSocketAddress(address, port));
}
 
Example 8
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 9
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 10
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 11
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();
   	}
   }
}