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

The following examples show how to use org.apache.mina.transport.socket.nio.NioSocketConnector#setHandler() . 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: 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 2
Source File: MinaTcpClient.java    From game-server with MIT License 6 votes vote down vote up
/**
   * 初始化tcp连接
   * @param clientProtocolHandler
   */
  private void init(IoHandler clientProtocolHandler) {
      connector = new NioSocketConnector();
      DefaultIoFilterChainBuilder chain = connector.getFilterChain();
      chain.addLast("codec", codecFilter);
      if(filters != null){
          filters.forEach((key, filter)->{
		if("ssl".equalsIgnoreCase(key) || "tls".equalsIgnoreCase(key)){	//ssl过滤器必须添加到首部
			chain.addFirst(key, filter);
		}else{
			chain.addLast(key, filter);
		}
	});
}
      connector.setHandler(clientProtocolHandler);
      connector.setConnectTimeoutMillis(60000L);
      connector.setConnectTimeoutCheckInterval(10000);
  }
 
Example 3
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 4
Source File: SocketConnectorSupplier.java    From sumk with Apache License 2.0 6 votes vote down vote up
private synchronized SocketConnector create() {
	if (connector != null && !connector.isDisposing() && !connector.isDisposed()) {
		return connector;
	}
	try {
		NioSocketConnector con = new NioSocketConnector(
				AppInfo.getInt("sumk.rpc.client.poolsize", Runtime.getRuntime().availableProcessors() + 1));
		con.setConnectTimeoutMillis(AppInfo.getInt("sumk.rpc.connect.timeout", 5000));
		con.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, AppInfo.getInt(Const.SOA_SESSION_IDLE, 600));
		con.setHandler(createClientHandler());
		con.getFilterChain().addLast("codec", new ProtocolCodecFilter(IOC.get(SumkCodecFactory.class)));
		if (AppInfo.getBoolean("sumk.rpc.client.threadpool.enable", true)) {
			con.getFilterChain().addLast("threadpool", new ExecutorFilter(SoaExcutors.getClientThreadPool()));
		}
		this.connector = con;
		return con;
	} catch (Exception e) {
		Logs.rpc().error(e.getMessage(), e);
		throw new SumkException(5423654, "create connector error", e);
	}
}
 
Example 5
Source File: MinaRemotingClient.java    From light-task-scheduler with Apache License 2.0 6 votes vote down vote up
@Override
protected void clientStart() throws RemotingException {
    try {
        connector = new NioSocketConnector(); //TCP Connector

        // connector.getFilterChain().addFirst("logging", new MinaLoggingFilter());
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MinaCodecFactory(getCodec())));
        connector.getFilterChain().addLast("mdc", new MdcInjectionFilter());

        connector.setHandler(new MinaHandler(this));
        IoSessionConfig cfg = connector.getSessionConfig();
        cfg.setReaderIdleTime(remotingClientConfig.getReaderIdleTimeSeconds());
        cfg.setWriterIdleTime(remotingClientConfig.getWriterIdleTimeSeconds());
        cfg.setBothIdleTime(remotingClientConfig.getClientChannelMaxIdleTimeSeconds());
    } catch (Exception e) {
        throw new RemotingException("Mina Client start error", e);
    }
}
 
Example 6
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 7
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 8
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 9
Source File: WebSocketServerTest.java    From red5-websocket with Apache License 2.0 5 votes vote down vote up
public WSClient(String host, int port, int cookieLength) {
    this.cookie = RandomStringUtils.randomAscii(cookieLength);
    log.debug("Cookie length: {}", cookie.length());
    this.host = host;
    this.port = port;
    connector = new NioSocketConnector();
    connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new WebSocketCodecFactory()));
    connector.setHandler(this);
    SocketSessionConfig sessionConf = connector.getSessionConfig();
    sessionConf.setReuseAddress(true);
    connector.setConnectTimeout(3);
}
 
Example 10
Source File: WebSocketServerTest.java    From red5-websocket with Apache License 2.0 5 votes vote down vote up
public WSClient(String host, int port) {
    this.host = host;
    this.port = port;
    connector = new NioSocketConnector();
    connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new WebSocketCodecFactory()));
    connector.setHandler(this);
    SocketSessionConfig sessionConf = connector.getSessionConfig();
    sessionConf.setReuseAddress(true);
    connector.setConnectTimeout(3);
}
 
Example 11
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 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: 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 15
Source File: LdapNetworkConnection.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Create the connector
 * 
 * @throws LdapException If the connector can't be created
 */
private void createConnector() throws LdapException
{
    // Use only one thread inside the connector
    connector = new NioSocketConnector( 1 );
    
    if ( socketSessionConfig != null )
    {
        ( ( SocketSessionConfig ) connector.getSessionConfig() ).setAll( socketSessionConfig );
    }
    else
    {
        ( ( SocketSessionConfig ) connector.getSessionConfig() ).setReuseAddress( true );
    }

    // Add the codec to the chain
    connector.getFilterChain().addLast( "ldapCodec", ldapProtocolFilter );

    // If we use SSL, we have to add the SslFilter to the chain
    if ( config.isUseSsl() )
    {
        addSslFilter();
    }

    // Inject the protocolHandler
    connector.setHandler( this );
}
 
Example 16
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 17
Source File: NetConnector.java    From oim-fx with MIT License 4 votes vote down vote up
private void initConnector() {
    ioConnector = new NioSocketConnector();
    ioConnector.getFilterChain().addLast("mis", new ProtocolCodecFilter(new DataCodecFactory()));// 添加过滤器
    ioConnector.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));
    ioConnector.setHandler(handler);// 添加业务逻辑处理类
}
 
Example 18
Source File: Application.java    From CXTouch with GNU General Public License v3.0 4 votes vote down vote up
private void createDeviceConnector() {
    NioSocketConnector connector = new NioSocketConnector();

    connector.setHandler(new DeviceIoHandlerAdapter(this));
    connector.getFilterChain().addLast("codec", new ProtocolCodecFilter( new DSCodecFactory()));
    connector.getFilterChain().addLast("threadModel", new ExecutorFilter(executors));

    deviceConnector = connector;

    NioSocketConnector scriptConnector = new NioSocketConnector();

    scriptConnector.setHandler(new ScriptDeviceIoHandlerAdapter(this));
    scriptConnector.getFilterChain().addLast("codec", new ProtocolCodecFilter( new DSCodecFactory()));
    scriptConnector.getFilterChain().addLast("threadModel", new ExecutorFilter(executors));

    scriptDeviceConnector = scriptConnector;


}
 
Example 19
Source File: RemoteConnector.java    From oim-fx with MIT License 4 votes vote down vote up
private void initConnector() {
	ioConnector = new NioSocketConnector();
	ioConnector.getFilterChain().addLast("mis", new ProtocolCodecFilter(new BytesDataFactory()));// 添加过滤器
	ioConnector.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));
	ioConnector.setHandler(handler);// 添加业务逻辑处理类
}
 
Example 20
Source File: SocketConnector.java    From oim-fx with MIT License 4 votes vote down vote up
private void initConnector() {
	ioConnector = new NioSocketConnector();
	ioConnector.getFilterChain().addLast("mis", new ProtocolCodecFilter(new DataCodecFactory()));// 添加过滤器
	ioConnector.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));
	ioConnector.setHandler(handler);// 添加业务逻辑处理类
}