org.apache.mina.core.filterchain.IoFilter Java Examples

The following examples show how to use org.apache.mina.core.filterchain.IoFilter. 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: TCPTestServer.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the MINA server.
 */
public TCPTestServer(int port, boolean loopback, IoHandler handler) throws Exception {

    acceptor = new NioSocketAcceptor();

    IoFilter tupleEncoder = new ProtocolCodecFilter(new TestTupleEncoder(),
            new TestTupleDecoder());

    acceptor.getFilterChain().addLast("testtuples", tupleEncoder);

    acceptor.setHandler(handler);

    // Get the bind address now so the majority of
    // errors are caught at initialization time.
    bindAddress = new InetSocketAddress(
            loopback ? InetAddress.getLoopbackAddress() : InetAddress.getLocalHost(), port);
}
 
Example #2
Source File: NetManager.java    From GameServer with Apache License 2.0 6 votes vote down vote up
public  void startListner(IoHandler iohandler,int listenPort) throws Exception{
	acceptor = new NioSocketAcceptor();
	acceptor.setBacklog(100);
	acceptor.setReuseAddress(true);
	acceptor.setHandler(iohandler);
	
       DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
       IoFilter protocol = new ProtocolCodecFilter(new GameProtocolcodecFactory());
       chain.addLast("codec", protocol);
	threadpool = new OrderedThreadPoolExecutor(500);
	threadpool.setThreadFactory(new ServerThreadFactory("OrderedThreadPool"));
	chain.addLast("threadPool", new ExecutorFilter(threadpool));
	
	int recsize = 5120;
	int sendsize = 40480;                                                                                         
	int timeout = 10;
	SocketSessionConfig sc = acceptor.getSessionConfig();
	sc.setReuseAddress(true);// 设置每一个非主监听连接的端口可以重用
	sc.setReceiveBufferSize(recsize);// 设置输入缓冲区的大小
	sc.setSendBufferSize(sendsize);// 设置输出缓冲区的大小
	sc.setTcpNoDelay(true);// flush函数的调用 设置为非延迟发送,为true则不组装成大包发送,收到东西马上发出   
	sc.setSoLinger(0);
	sc.setIdleTime(IdleStatus.READER_IDLE, timeout);
	acceptor.bind(new InetSocketAddress(listenPort));
}
 
Example #3
Source File: FilterChainBuilder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void buildFilterChain ( final IoFilterChain chain )
{
    for ( final Entry entry : this.filters )
    {
        final IoFilter filter = entry.getFactory ().create ();
        if ( filter != null )
        {
            chain.addLast ( entry.getName (), filter );
        }
    }

}
 
Example #4
Source File: NetManager.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void sessionCreated(IoSession session) throws Exception
{
	Supplier<IoFilter> codecFactory = _codecFactory;
	if (codecFactory != null)
	{
		IoFilter codec = codecFactory.get();
		if (codec != null)
			session.getFilterChain().addLast("codec", codec);
	}
}
 
Example #5
Source File: SimpleClientTest.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public void testConnectToServerTimeout() throws Exception {
	IoFilter filter = createNiceMock(IoFilter.class);
	SimpleClient client = new SimpleClient(filter, "10.0.0.1", 3000);
	client.sendMessageToServer(new Object());
	Jedis jedis = JedisFactory.getJedis();
	Thread.sleep(3000);
	assertTrue(jedis.exists("client_timeout_map:10.0.0.1:3000"));
	Thread.sleep(2000);
	assertFalse(jedis.exists("client_timeout_map:10.0.0.1:3000"));
}
 
Example #6
Source File: ReloadProtocolCodecFilter.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * Reload the internal instances.
 */
public void reload() {
	try {
		this.classLoader = ReloadClassLoader.newClassloader(this.classLoader.getClasspathURLs());
		Class ioFilterClass = this.classLoader.loadClass(ioFilterClassName);
		Class ioHandlerClass = this.classLoader.loadClass(ioHandlerClassName);
		this.ioFilter = (IoFilter)ioFilterClass.newInstance();
		this.ioHandler = (IoHandler)ioHandlerClass.newInstance();
	} catch (Throwable e) {
		log.error("Reload error", e);
	}
}
 
Example #7
Source File: ReloadProtocolCodecFilter.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public ReloadProtocolCodecFilter(String ioFilterClassName, String ioHandlerClassName){
	try {
		this.ioFilterClassName = ioFilterClassName;
		this.ioHandlerClassName = ioHandlerClassName;
		this.classLoader = ReloadClassLoader.currentClassLoader();
		Class ioFilterClass = this.classLoader.loadClass(ioFilterClassName);
		Class ioHandlerClass = this.classLoader.loadClass(ioHandlerClassName);
		this.ioFilter = (IoFilter)ioFilterClass.newInstance();
		this.ioHandler = (IoHandler)ioHandlerClass.newInstance();
	} catch (Throwable e) {
		log.error("Failed to create ReloadProtocolCodecFilter", e);
	}
}
 
Example #8
Source File: SimpleClient.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new Client
 * @param filter
 * @param handler
 * @param remoteHost
 * @param remotePort
 */
public SimpleClient(IoFilter filter, IoHandler handler, 
		String remoteHost, int remotePort) {
	this.ioFilter = filter;
	this.ioHandler = handler;
	this.remoteHost = remoteHost;
	this.remotePort = remotePort;
	this.connectKey = StringUtil.concat(remoteHost, Constant.COLON, remotePort);
	this.clientNo = SimpleClient.totalClientNo++;
}
 
Example #9
Source File: TCPTestClient.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
public TCPTestClient(InetSocketAddress addr) {
    this.addr = addr;
    connector.setConnectTimeoutMillis(5000);

    IoFilter tupleEncoder = new ProtocolCodecFilter(new TestTupleEncoder(),
            new TestTupleDecoder());

    connector.getFilterChain().addLast("tuples", tupleEncoder);

    connector.setHandler(new IoHandlerAdapter());
}
 
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: ChainConfigurator.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Replace an IOFilter that as pre-registered as {@link NoopFilter} with the
 * ".marker" suffix
 * 
 * @param name
 *            the name, without the ".marker" suffix
 * @param filter
 *            the filter replacement
 */
protected void replaceMarker ( final String name, final IoFilter filter )
{
    final Entry entry = this.session.getFilterChain ().getEntry ( name + ".marker" );
    if ( entry == null )
    {
        throw new IllegalStateException ( String.format ( "Filter with name '%s.marker' is missing", name ) );
    }
    entry.addAfter ( name, filter );
    entry.remove ();
}
 
Example #12
Source File: FilterChainBuilder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public FilterChainBuilder ( final boolean clientMode )
{
    if ( !Boolean.getBoolean ( "org.eclipse.scada.protocol.ngp.common.disableStats" ) )
    {
        this.filters.add ( new Entry ( StatisticsFilter.DEFAULT_NAME, new StatisticsFilter () ) );
    }

    this.filters.add ( new Entry ( "logger.raw", new LoggerFilterFactory ( "raw" ) ) );

    this.filters.add ( new Entry ( "ssl" ) );
    this.filters.add ( new Entry ( "streamCompression" ) );

    this.filters.add ( new Entry ( "logger", new LoggerFilterFactory ( "pre" ) ) );

    this.filters.add ( new Entry ( "sync", new ExecutorFilter ( Integer.getInteger ( "org.eclipse.scada.protocol.ngp.common.coreSessionThreads", 0 ), Integer.getInteger ( "org.eclipse.scada.protocol.ngp.common.maxSessionThreads", 1 ), 1, TimeUnit.MINUTES, new NamedThreadFactory ( "org.eclipse.scada.protocol.ngp.common.FilterChainSync", false, true, THREAD_COUNTER ), IoEventType.WRITE ) ) );
    this.filters.add ( new Entry ( "frameCodec", new ProtocolCodecFilter ( new FrameEncoder (), new FrameDecoder () ) ) );

    this.filters.add ( new Entry ( "keepalive" ) );

    this.filters.add ( new Entry ( "messageChannelCodec", new MessageChannelCodecFilter () ) );
    this.filters.add ( new Entry ( "messageChannel", new IoFilterFactoryAdapter () {

        @Override
        public IoFilter create ()
        {
            // we need new instances of MessageChannelFilter
            return new MessageChannelFilter ( clientMode );
        }
    } ) );
}
 
Example #13
Source File: FilterChainBuilder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public IoFilter create ()
{
    if ( FilterChainBuilder.this.loggerName != null && Boolean.getBoolean ( "org.eclipse.scada.protocol.ngp.common.logger" ) )
    {
        return new LoggingFilterExtension ( this.suffix != null ? FilterChainBuilder.this.loggerName + "." + this.suffix : FilterChainBuilder.this.loggerName );
    }
    else
    {
        return null;
    }
}
 
Example #14
Source File: MinaTcpClient.java    From game-server with MIT License 5 votes vote down vote up
/**
 * <p>Constructor for MinaTcpClient.</p>
 *
 * @param service a {@link com.jzy.game.engine.mina.service.MinaClientService} object.
 * @param minaClientConfig a {@link com.jzy.game.engine.mina.config.MinaClientConfig} object.
 * @param clientProtocolHandler a {@link org.apache.mina.core.service.IoHandler} object.
 * @param factory a {@link com.jzy.game.engine.mina.code.ProtocolCodecFactoryImpl} object.
 * @param filters a {@link java.util.Map} object.
 */
public MinaTcpClient(MinaClientService service, MinaClientConfig minaClientConfig, IoHandler clientProtocolHandler, ProtocolCodecFactoryImpl factory,Map<String, IoFilter> filters) {
    this.factory=factory;
    codecFilter = new ProtocolCodecFilter(factory);
    this.service = service;
    this.clientProtocolHandler = clientProtocolHandler;
    this.filters=filters;
    init(clientProtocolHandler);
    setMinaClientConfig(minaClientConfig);
}
 
Example #15
Source File: HttpServerCodecImpl.java    From game-server with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void sessionClosed(IoFilter.NextFilter nextFilter, IoSession session) throws Exception {
	super.sessionClosed(nextFilter, session);
	session.removeAttribute(DECODER_STATE_ATT);
	session.removeAttribute(PARTIAL_HEAD_ATT);
}
 
Example #16
Source File: FilterChainBuilder.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public Entry ( final String name, final IoFilter filter )
{
    this ( name, new StaticIoFilterFactory ( filter ) );
}
 
Example #17
Source File: MinaComponentConfiguration.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
public void setFilters(List<IoFilter> filters) {
    this.filters = filters;
}
 
Example #18
Source File: Channel.java    From HeavenMS with GNU Affero General Public License v3.0 4 votes vote down vote up
public Channel(final int world, final int channel, long startTime) {
    this.world = world;
    this.channel = channel;
    
    this.ongoingStartTime = startTime + 10000;  // rude approach to a world's last channel boot time, placeholder for the 1st wedding reservation ever
    this.mapManager = new MapleMapManager(null, world, channel);
    try {
        port = 7575 + this.channel - 1;
        port += (world * 100);
        ip = YamlConfig.config.server.HOST + ":" + port;
        IoBuffer.setUseDirectBuffer(false);
        IoBuffer.setAllocator(new SimpleBufferAllocator());
        acceptor = new NioSocketAcceptor();
        acceptor.setHandler(new MapleServerHandler(world, channel));
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30);
        acceptor.getFilterChain().addLast("codec", (IoFilter) new ProtocolCodecFilter(new MapleCodecFactory()));
        acceptor.bind(new InetSocketAddress(port));
        ((SocketSessionConfig) acceptor.getSessionConfig()).setTcpNoDelay(true);
        for (MapleExpeditionType exped : MapleExpeditionType.values()) {
        	expedType.add(exped);
        }
        
        if (Server.getInstance().isOnline()) {  // postpone event loading to improve boot time... thanks Riizade, daronhudson for noticing slow startup times
            eventSM = new EventScriptManager(this, getEvents());
            eventSM.init();
        } else {
            String[] ev = {"0_EXAMPLE"};
            eventSM = new EventScriptManager(this, ev);
        }
        
        dojoStage = new int[20];
        dojoFinishTime = new long[20];
        dojoTask = new ScheduledFuture<?>[20];
        for(int i = 0; i < 20; i++) {
            dojoStage[i] = 0;
            dojoFinishTime[i] = 0;
            dojoTask[i] = null;
        }
        
        services = new ServicesManager(ChannelServices.OVERALL);
        
        System.out.println("    Channel " + getId() + ": Listening on port " + port);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #19
Source File: PressureClientTool.java    From game-server with MIT License 4 votes vote down vote up
public PressureClientTool(int clientNum, String userNamePrefix, String password, String clusterIp,JTextArea logTextArea) {
        this.clientNum = clientNum;
        this.clusterIp = clusterIp;
        this.userNamePrefix = userNamePrefix;
        initConfigPath();
        ScriptManager.getInstance().init(null);

        //循环初始化客户端
        try {
            for (int i = 0; i < clientNum; i++) {
                PressureClientHandler pressureClientHandler = new PressureClientHandler();
                MinaClientConfig minaClientConfig = getMinaClientConfig();
                String userName = userNamePrefix + userNameNo.incrementAndGet();

                // TCP
                // 添加ssl
                Map<String, IoFilter> filters = new HashMap<>();
                SslFilter sslFilter = new SslFilter(ClientSslContextFactory.getInstance(false));
                sslFilter.setUseClientMode(true);
//		filters.put("ssl", sslFilter);
                SingleMinaTcpClientService service = new SingleMinaTcpClientService(minaClientConfig,
                        new ClientProtocolCodecFactory(), pressureClientHandler, filters);
                pressureClientHandler.setService(service);
                new Thread(service).start();

                // UDP
                MinaClientConfig minaClientConfig2 = new MinaClientConfig();
                MinaClienConnToConfig connTo = new MinaClienConnToConfig();
                connTo.setHost(minaClientConfig.getConnTo().getHost());
                connTo.setPort(8004);
                minaClientConfig2.setConnTo(connTo);
                MinaUdpClient udpClient = new MinaUdpClient(minaClientConfig2, pressureClientHandler,
                        new ClientProtocolCodecFactory());
                new Thread(udpClient).start();

                while (udpClient.getSession() == null) {
                    Thread.sleep(MathUtil.random(500, 3000));
                }
                Player player = new Player();
                player.setUserName(userName);
                player.setPassword(password);
                player.setUdpSession(udpClient.getSession());
                player.setTcpSession(service.getMostIdleIoSession());
                player.setLogTextArea(logTextArea);
                if(player.getTcpSession()==null||player.getUdpSession()==null){
                    LOGGER.warn("用户{}连接服务器失败",userName);
                    logTextArea.append(String.format("用户%s连接服务器失败\n",userName));
                    continue;
                }
                player.loginInit();
                players.put(userName, player);

                new PressureServiceThread(player).start();

            }
        } catch (Exception e) {
            LOGGER.error("PressureClientTool", e);
        }

    }
 
Example #20
Source File: ReferenceCountingFilter.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public ReferenceCountingFilter(IoFilter filter) {
    this.filter = filter;
}
 
Example #21
Source File: FilterChainBuilder.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public StaticIoFilterFactory ( final IoFilter filter )
{
    this.filter = filter;
}
 
Example #22
Source File: MinaComponentConfiguration.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
public List<IoFilter> getFilters() {
    return filters;
}
 
Example #23
Source File: FilterChainBuilder.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public IoFilter create ()
{
    return this.filter;
}
 
Example #24
Source File: FilterChainBuilder.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public IoFilter create ()
{
    return new NoopFilter ();
}
 
Example #25
Source File: ClientServerService.java    From game-server with MIT License 3 votes vote down vote up
/**
 * <p>Constructor for ClientServerService.</p>
 *
 * @param threadExcutorConfig 线程池配置
 * @param minaServerConfig 服务器配置
 * @param clientProtocolHandler 消息处理器
 * @param filters a {@link java.util.Map} object.
 */
public ClientServerService(ThreadPoolExecutorConfig threadExcutorConfig, MinaServerConfig minaServerConfig,
                           ClientProtocolHandler clientProtocolHandler, Map<String, IoFilter> filters) {
    super(threadExcutorConfig);
    this.minaServerConfig = minaServerConfig;
    this.clientProtocolHandler = clientProtocolHandler;
    tcpServer = new TcpServer(minaServerConfig, clientProtocolHandler, new ClientProtocolCodecFactory(), filters);
}
 
Example #26
Source File: ClientPool.java    From gameserver with Apache License 2.0 3 votes vote down vote up
/**
 * Create a pool with the number of 'count' connections underhood.
 * To avoid multi-thread access, I suggest provide a distinguish 
 * IoHandler for each client. So the constructor contains an array
 * of IoHandlers. They should be not null and has the same
 * number with count. The IoFilter is usually thread-safe.
 * 
 * @param filters
 * @param handlers
 * @param remoteHost
 * @param remotePort
 * @param count
 */
public ClientPool(IoFilter filter, IoHandler[] handlers, 
		String remoteHost, int remotePort, int count) {
	
	this.count = count;
	for ( int i=0; i<count; i++ ) {
		SimpleClient client = new SimpleClient(filter, handlers[i], remoteHost,
				remotePort);
		clientQueue.offer(client);
	}
}
 
Example #27
Source File: TcpServer.java    From game-server with MIT License 2 votes vote down vote up
/**
 * <p>Constructor for TcpServer.</p>
 *
 * @param minaServerConfig a {@link com.jzy.game.engine.mina.config.MinaServerConfig} object.
 * @param ioHandler a {@link org.apache.mina.core.service.IoHandler} object.
 * @param factory a {@link org.apache.mina.filter.codec.ProtocolCodecFactory} object.
 * @param filters 不要包含消息解码、线程池过滤器,已默认添加
 */
public TcpServer(MinaServerConfig minaServerConfig, IoHandler ioHandler, ProtocolCodecFactory factory,
                 Map<String, IoFilter> filters) {
    this(minaServerConfig, ioHandler, factory);
    this.filters = filters;
}
 
Example #28
Source File: SimpleClient.java    From gameserver with Apache License 2.0 2 votes vote down vote up
/**
 * Create a new SimpleClient without handler.
 * @param filter
 * @param remoteHost
 * @param remotePort
 */
public SimpleClient(IoFilter filter, String remoteHost, int remotePort) {
	this(filter, null, remoteHost, remotePort);
}
 
Example #29
Source File: SingleMinaTcpClientService.java    From game-server with MIT License 2 votes vote down vote up
/**
 * <p>Constructor for SingleMinaTcpClientService.</p>
 *
 * @param minaClientConfig a {@link com.jzy.game.engine.mina.config.MinaClientConfig} object.
 * @param factory a {@link com.jzy.game.engine.mina.code.ProtocolCodecFactoryImpl} object.
 * @param ioHandler a {@link org.apache.mina.core.service.IoHandler} object.
 * @param filters a {@link java.util.Map} object.
 */
public SingleMinaTcpClientService(MinaClientConfig minaClientConfig,ProtocolCodecFactoryImpl factory, IoHandler ioHandler,Map<String, IoFilter> filters) {
	super(minaClientConfig);
	tcpClient = new MinaTcpClient(this,  minaClientConfig, ioHandler,factory,filters);
}
 
Example #30
Source File: UdpServer.java    From game-server with MIT License 2 votes vote down vote up
/**
 * <p>Constructor for UdpServer.</p>
 *
 * @param minaServerConfig a {@link com.jzy.game.engine.mina.config.MinaServerConfig} object.
 * @param ioHandler a {@link org.apache.mina.core.service.IoHandler} object.
 * @param factory a {@link com.jzy.game.engine.mina.code.ProtocolCodecFactoryImpl} object.
 * @param filters a {@link java.util.Map} object.
 */
public UdpServer(MinaServerConfig minaServerConfig, IoHandler ioHandler, ProtocolCodecFactoryImpl factory,Map<String, IoFilter> filters) {
	this(minaServerConfig, ioHandler, factory);
	this.filters=filters;
}