org.apache.mina.filter.codec.ProtocolCodecFilter Java Examples

The following examples show how to use org.apache.mina.filter.codec.ProtocolCodecFilter. 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: TlsNioConfigTest.java    From cougar with Apache License 2.0 6 votes vote down vote up
@Test
public void insecureClient() throws IOException {
    TlsNioConfig config = new TlsNioConfig();
    config.setNioLogger(logger);
    config.setMbeanServer(mbeanServer);
    config.configureProtocol(minaConfig, false);

    List<Tuple<String, IoFilter>> addedFilters = getAddedFilters();
    assertEquals("slowHandling", addedFilters.get(0).getFirst());
    assertInstanceOf(SessionWriteQueueMonitoring.class, addedFilters.get(0).getSecond());
    assertEquals("codec", addedFilters.get(1).getFirst());
    assertInstanceOf(ProtocolCodecFilter.class, addedFilters.get(1).getSecond());
    assertEquals("protocol", addedFilters.get(2).getFirst());
    assertInstanceOf(CougarProtocol.class, addedFilters.get(2).getSecond());
    CougarProtocol cp = (CougarProtocol) addedFilters.get(2).getSecond();
    assertNull(cp.getSslFilter());
}
 
Example #2
Source File: TestDnsServer.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws IOException {
    InetSocketAddress address = AddressUtils.localAddress(0);
    UdpTransport transport = new UdpTransport(address.getHostString(), address.getPort());
    setTransports(transport);

    DatagramAcceptor acceptor = transport.getAcceptor();

    acceptor.setHandler(new DnsProtocolHandler(this, store) {
        @Override
        public void sessionCreated(IoSession session) {
            // Use our own codec to support AAAA testing
            session.getFilterChain()
                    .addFirst("codec", new ProtocolCodecFilter(new TestDnsProtocolUdpCodecFactory()));
        }
    });

    ((DatagramSessionConfig) acceptor.getSessionConfig()).setReuseAddress(true);

    // Start the listener
    acceptor.bind();
}
 
Example #3
Source File: AbstractMINATCPServer.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Override
protected void internalStart() throws IOException {
    WrapperNioSocketAcceptor tmpAcceptor = new WrapperNioSocketAcceptor(taskExecutor);

    tmpAcceptor.setReuseAddress(true);

    try {
        configureAcceptor(tmpAcceptor);
    } catch (Exception e) {
        throw new ServiceException("Can`t configure server`s acceptor", e);
    }

    CodecFactory codecFactory = new CodecFactory(serviceContext, messageFactory, dictionary, getCodecClass(), getCodecSettings());
    tmpAcceptor.setHandler(this);
    tmpAcceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(codecFactory));
    tmpAcceptor.bind(new InetSocketAddress(getSettings().getHost(), getSettings().getPort()));

    acceptor.set(tmpAcceptor);
    serverSession.set(createServerSession());
}
 
Example #4
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 #5
Source File: CIMNioSocketAcceptor.java    From cim with Apache License 2.0 6 votes vote down vote up
private void bindWebPort() throws IOException {

		/*
		 * 预制websocket握手请求的处理
		 */
		INNER_HANDLER_MAP.put(CIMConstant.CLIENT_WEBSOCKET_HANDSHAKE, new WebsocketHandler());

		webAcceptor = new NioSocketAcceptor();
		((DefaultSocketSessionConfig) webAcceptor.getSessionConfig()).setKeepAlive(true);
		((DefaultSocketSessionConfig) webAcceptor.getSessionConfig()).setTcpNoDelay(true);
		webAcceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new WebMessageCodecFactory()));
		webAcceptor.getFilterChain().addLast("logger", new LoggingFilter());
		webAcceptor.getFilterChain().addLast("executor", new ExecutorFilter(createWorkerExecutor()));
		webAcceptor.setHandler(this);

		webAcceptor.bind(new InetSocketAddress(webPort));
		String logBanner = "\n\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"*                   Websocket Server started on port {}.                         *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n";
		LOGGER.info(logBanner, webPort);
	}
 
Example #6
Source File: Server.java    From oim-fx with MIT License 6 votes vote down vote up
public synchronized boolean startServer(int port) {
    if (running) {
        return running;
    }
    try {

        acceptor = new NioSocketAcceptor();
        acceptor.addListener(new ServerListener());
        acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new DataCodecFactory()));
        acceptor.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));
        acceptor.getSessionConfig().setReadBufferSize(2048); // 设置读取数据的缓冲区大小
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);// 读写通道10秒内无操作进入空闲状态
        acceptor.setHandler(new ServerHandler()); // 绑定逻辑处理起器
        acceptor.bind(new InetSocketAddress(port));// 绑定端口
        acceptor.setReuseAddress(true);
        logger.info("服务器启动成功。。。。端口为:" + port);
        return running = true;
    } catch (IOException e) {
        logger.error("服务器启动异常。。。。", e);
        e.printStackTrace();
        running = false;
    }
    return running = false;
}
 
Example #7
Source File: CrossServer.java    From jforgame with Apache License 2.0 6 votes vote down vote up
/**
 * start Mina serversocket
 * @throws Exception
 */
@Override
public void start() throws Exception {
	final int serverPort = ServerConfig.getInstance().getCrossPort();
	IoBuffer.setUseDirectBuffer(false);
	IoBuffer.setAllocator(new SimpleBufferAllocator());

	acceptor = new NioSocketAcceptor(pool);
	acceptor.setReuseAddress(true);
	acceptor.getSessionConfig().setAll(getSessionConfig());

	logger.info("cross server start at port:{},正在监听服务器点对点的连接...", serverPort);
	DefaultIoFilterChainBuilder filterChain = acceptor.getFilterChain();
	filterChain.addLast("codec",
			new ProtocolCodecFilter(SerializerHelper.getInstance().getCodecFactory()));
	//指定业务逻辑处理器
	acceptor.setHandler(new Game2GameIoHandler(BaseCrossMessageDispatcher.getInstance()));
	//设置端口号
	acceptor.setDefaultLocalAddress(new InetSocketAddress(serverPort));
	//启动监听
	acceptor.bind();
}
 
Example #8
Source File: MinaSocketServer.java    From jforgame with Apache License 2.0 6 votes vote down vote up
/**
 * start Mina serversocket
 * @throws Exception
 */
@Override
public void start() throws Exception {
	int serverPort = ServerConfig.getInstance().getServerPort();
	IoBuffer.setUseDirectBuffer(false);
	IoBuffer.setAllocator(new SimpleBufferAllocator());

	acceptor = new NioSocketAcceptor(pool);
	acceptor.setReuseAddress(true);
	acceptor.getSessionConfig().setAll(getSessionConfig());

	logger.info("mina socket server start at port:{},正在监听客户端的连接...", serverPort);
	DefaultIoFilterChainBuilder filterChain = acceptor.getFilterChain();
	filterChain.addLast("codec",
			new ProtocolCodecFilter(SerializerHelper.getInstance().getCodecFactory()));
	filterChain.addLast("moduleEntrance", new ModuleEntranceFilter());
	filterChain.addLast("msgTrace", new MessageTraceFilter());
	filterChain.addLast("flood", new FloodFilter());
	//指定业务逻辑处理器
	acceptor.setHandler(new ServerSocketIoHandler(new MessageDispatcher()));
	//设置端口号
	acceptor.setDefaultLocalAddress(new InetSocketAddress(serverPort));
	//启动监听
	acceptor.bind();
}
 
Example #9
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 #10
Source File: MinaTimeServer.java    From frameworkAggregate with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {

		IoAcceptor acceptor = new NioSocketAcceptor();
		// 这个过滤器用来记录所有的信息,比如创建session(会话),接收消息,发送消息,关闭会话等
		acceptor.getFilterChain().addLast("logger", new LoggingFilter());
		// 用来转换二进制或协议的专用数据到消息对象中
		acceptor.getFilterChain().addLast("codec",
				new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));

		// 实时处理客户端的连接和请求
		acceptor.setHandler(new TimeServerHandler());
		acceptor.getSessionConfig().setReadBufferSize(2048);
		// 方法将定时调用一次会话,保持空闲状态。来设定时间间隔。
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
		acceptor.bind(new InetSocketAddress(PORT));
	}
 
Example #11
Source File: ArduinoDevice.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public synchronized void start ()
{
    if ( this.started )
    {
        return;
    }

    this.started = true;

    this.executorService = ScheduledExportedExecutorService.newSingleThreadExportedScheduledExecutor ( "ArduninoDevice/" + this.address );

    this.connector = new NioDatagramConnector ();

    this.connector.setHandler ( this );
    if ( this.activateLogger )
    {
        this.connector.getFilterChain ().addLast ( "logger", new LoggingFilter ( this.getClass ().getName () ) );
    }

    final ArduinoCodec codec = new ArduinoCodec ();
    this.connector.getFilterChain ().addLast ( "codec", new ProtocolCodecFilter ( codec, codec ) );

    this.connector.connect ( this.address );
}
 
Example #12
Source File: ModbusMaster.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void configureConnector ( final NioSocketConnector connector )
{
    logger.debug ( "Configuring connector: {}", connector );

    switch ( this.protocolType )
    {
        case TYPE_TCP:
            connector.getFilterChain ().addLast ( "modbusPdu", new ProtocolCodecFilter ( new ModbusTcpEncoder (), new ModbusTcpDecoder () ) );
            connector.getFilterChain ().addLast ( "modbus", new ModbusMasterProtocolFilter () );
            break;
        case TYPE_RTU:
            // convert milliseconds to microseconds to allow more accurate timing
            final ModbusRtuDecoder rtuDecoder = new ModbusRtuDecoder ( getExecutor (), Double.valueOf ( this.interFrameDelay * 1000 ).longValue (), TimeUnit.MICROSECONDS );
            connector.getFilterChain ().addLast ( "modbusPdu", new ModbusRtuProtocolCodecFilter ( new ModbusRtuEncoder (), rtuDecoder ) );
            connector.getFilterChain ().addLast ( "modbus", new ModbusMasterProtocolFilter () );
            break;
        default:
            throw new IllegalArgumentException ( String.format ( "'%s' is not an allowed modbus device type", this.protocolType ) );
    }

    if ( Boolean.getBoolean ( "org.eclipse.scada.da.server.osgi.modbus.trace" ) )
    {
        connector.getFilterChain ().addFirst ( "logger", new LoggingFilter ( ModbusMaster.class.getName () + ".protocol" ) );
    }
}
 
Example #13
Source File: MinaClient.java    From grain with MIT License 6 votes vote down vote up
/**
 * 初始化
 * 
 * @param ipArray
 *            ip地址数组
 * @param portArray
 *            端口数组
 * @param nameArray
 *            名称数组
 * @throws Exception
 */
public MinaClient(String[] ipArray, int[] portArray, String[] nameArray, Class<?> HandlerClass) throws Exception {
	for (int i = 0; i < ipArray.length; i++) {
		String ip = ipArray[i];
		int port = portArray[i];
		String name = nameArray[i];
		IoConnector ioConnector = new NioSocketConnector();

		ioConnector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MinaEncoder(), new MinaDecoder()));
		MinaHandler minaHandler = (MinaHandler) HandlerClass.newInstance();
		minaHandler.ioConnector = ioConnector;
		minaHandler.name = name;
		ioConnector.setHandler(minaHandler);
		ioConnector.setConnectTimeoutMillis(10000);
		InetSocketAddress inetSocketAddress = new InetSocketAddress(ip, port);
		ioConnectorMap.put(ioConnector, inetSocketAddress);
		ioConnectorStateMap.put(ioConnector, false);
	}
	start();
}
 
Example #14
Source File: TestDnsServer.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws IOException {
    InetSocketAddress address = new InetSocketAddress(NetUtil.LOCALHOST4, 0);
    UdpTransport transport = new UdpTransport(address.getHostName(), address.getPort());
    setTransports(transport);

    DatagramAcceptor acceptor = transport.getAcceptor();

    acceptor.setHandler(new DnsProtocolHandler(this, store) {
        @Override
        public void sessionCreated(IoSession session) throws Exception {
            // USe our own codec to support AAAA testing
            session.getFilterChain()
                .addFirst("codec", new ProtocolCodecFilter(new TestDnsProtocolUdpCodecFactory()));
        }
    });

    ((DatagramSessionConfig) acceptor.getSessionConfig()).setReuseAddress(true);

    // Start the listener
    acceptor.bind();
}
 
Example #15
Source File: NioConfig.java    From cougar with Apache License 2.0 6 votes vote down vote up
protected void configureProtocol(BaseIoServiceConfig config, boolean isServer) throws IOException {

        ByteBuffer.setUseDirectBuffers(useDirectBuffersInMina);

        config.getFilterChain().addLast("slowHandling", new SessionWriteQueueMonitoring(nioLogger, maxWriteQueueSize));
        config.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(new CougarProtocolEncoder(nioLogger), new CougarProtocolDecoder(nioLogger)));
        if (isServer) {
            config.getFilterChain().addLast("protocol", CougarProtocol.getServerInstance(nioLogger, keepAliveInterval, keepAliveTimeout, null, false, false));
        }
        else {
            config.getFilterChain().addLast("protocol", CougarProtocol.getClientInstance(nioLogger, keepAliveInterval, keepAliveTimeout, null, false, false, rpcTimeoutMillis));
        }

        config.setThreadModel(ThreadModel.MANUAL);
    }
 
Example #16
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 #17
Source File: MinaRemotingServer.java    From light-task-scheduler with Apache License 2.0 6 votes vote down vote up
@Override
protected void serverStart() throws RemotingException {

    acceptor = new NioSocketAcceptor(); //TCP Acceptor

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

    acceptor.setHandler(new MinaHandler(this));
    IoSessionConfig cfg = acceptor.getSessionConfig();
    cfg.setReaderIdleTime(remotingServerConfig.getReaderIdleTimeSeconds());
    cfg.setWriterIdleTime(remotingServerConfig.getWriterIdleTimeSeconds());
    cfg.setBothIdleTime(remotingServerConfig.getServerChannelMaxIdleTimeSeconds());

    bindAddress = new InetSocketAddress(remotingServerConfig.getListenPort());
    try {
        acceptor.bind(bindAddress);
    } catch (IOException e) {
        throw new RemotingException("Start Mina server error", e);
    }
}
 
Example #18
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 #19
Source File: WebSocketServerTest.java    From red5-websocket with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    acceptor = new NioSocketAcceptor();
    acceptor.getFilterChain().addLast("protocol", new ProtocolCodecFilter(new WebSocketCodecFactory()));
    // close sessions when the acceptor is stopped
    acceptor.setCloseOnDeactivation(true);
    acceptor.setHandler(new WebSocketHandler());
    SocketSessionConfig sessionConf = acceptor.getSessionConfig();
    sessionConf.setReuseAddress(true);
    acceptor.setReuseAddress(true);
    // loop through the addresses and bind
    Set<InetSocketAddress> socketAddresses = new HashSet<InetSocketAddress>();
    socketAddresses.add(new InetSocketAddress("0.0.0.0", 8888));
    //socketAddresses.add(new InetSocketAddress("localhost", 8888));
    log.debug("Binding to {}", socketAddresses.toString());
    acceptor.bind(socketAddresses);
    System.out.println("WS server started listening");
    listening = true;
    while (true) {
        try {
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            System.out.println("WS server stopped listening");
        }
    }
}
 
Example #20
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 #21
Source File: RTMPEIoFilter.java    From red5-client with Apache License 2.0 6 votes vote down vote up
/**
 * Provides connection completion.
 * 
 * @param session
 * @param conn
 * @param rtmp
 * @param handshake
 */
private static void completeConnection(IoSession session, RTMPMinaConnection conn, RTMP rtmp, OutboundHandshake handshake) {
    if (handshake.useEncryption()) {
        // set encryption flag the rtmp state
        rtmp.setEncrypted(true);
        // add the ciphers
        log.debug("Adding ciphers to the session");
        session.setAttribute(RTMPConnection.RTMPE_CIPHER_IN, handshake.getCipherIn());
        session.setAttribute(RTMPConnection.RTMPE_CIPHER_OUT, handshake.getCipherOut());
    }
    // set state to indicate we're connected
    conn.getState().setState(RTMP.STATE_CONNECTED);
    log.debug("Connected, removing handshake data");
    // remove handshake from session now that we are connected
    session.removeAttribute(RTMPConnection.RTMP_HANDSHAKE);
    // add protocol filter as the last one in the chain
    log.debug("Adding RTMP protocol filter");
    session.getFilterChain().addAfter("rtmpeFilter", "protocolFilter", new ProtocolCodecFilter(new RTMPMinaCodecFactory()));
    // get the rtmp handler
    BaseRTMPClientHandler handler = (BaseRTMPClientHandler) session.getAttribute(RTMPConnection.RTMP_HANDLER);
    handler.connectionOpened(conn);
}
 
Example #22
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 #23
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 #24
Source File: MinaTimeServer.java    From java-tutorial with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    // 创建服务器端的监听器对象
    IoAcceptor acceptor = new NioSocketAcceptor();
    // 增加日志过滤器:用于日志存储
    acceptor.getFilterChain().addLast("logger", new LoggingFilter());
    // 增加消息编码过滤器,采用UTF-8编码
    acceptor.getFilterChain().addLast("codec",
            new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
    // 设置具体的事物逻辑处理器
    acceptor.setHandler(new TimeServerHandler());
    // 设置IoSession的一些属性
    acceptor.getSessionConfig().setReadBufferSize(2048);
    acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
    // 设置服务器监听的端口
    acceptor.bind(new InetSocketAddress(PORT));
}
 
Example #25
Source File: ConsoleServer.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void start() throws IOException {
	acceptor = new NioSocketAcceptor();
	acceptor.getFilterChain().addLast("codec",
			new ProtocolCodecFilter(new TextLineCodecFactory(MTGConstants.DEFAULT_ENCODING)));
	acceptor.getSessionConfig().setReadBufferSize(getInt("BUFFER-SIZE"));
	acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, getInt("IDLE-TIME"));
	MTGConsoleHandler handler = new MTGConsoleHandler();
	handler.setWelcomeMessage(getString("STARTUP_MESSAGE"));
	acceptor.setHandler(handler);
	acceptor.bind(new InetSocketAddress(getInt(SERVER_PORT)));
	logger.info("Server started on port " + getString(SERVER_PORT));
}
 
Example #26
Source File: TlsNioConfigTest.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Test
public void secureServerSupportsTlsNoClientAuthKeystoreProvidedSpecifiedCiphers() throws IOException {
    TlsNioConfig config = new TlsNioConfig();
    config.setNioLogger(logger);
    config.setMbeanServer(mbeanServer);
    config.setKeystore(new FileSystemResource(getServerKeystorePath()));
    config.setKeystorePassword("password");
    config.setKeystoreType("JKS");
    config.setWantClientAuth(false);
    config.setNeedClientAuth(false);
    config.setRequiresTls(false);
    config.setSupportsTls(true);
    config.setAllowedCipherSuites("DES,AES");
    config.configureProtocol(minaConfig, true);

    List<Tuple<String, IoFilter>> addedFilters = getAddedFilters();
    assertEquals("slowHandling", addedFilters.get(0).getFirst());
    assertInstanceOf(SessionWriteQueueMonitoring.class, addedFilters.get(0).getSecond());
    assertEquals("codec", addedFilters.get(1).getFirst());
    assertInstanceOf(ProtocolCodecFilter.class, addedFilters.get(1).getSecond());
    assertEquals("protocol", addedFilters.get(2).getFirst());
    assertInstanceOf(CougarProtocol.class, addedFilters.get(2).getSecond());

    CougarProtocol cp = (CougarProtocol) addedFilters.get(2).getSecond();
    assertFalse(cp.isRequiresTls());
    assertTrue(cp.isSupportsTls());
    assertNotNull(cp.getSslFilter());
    SSLFilter sslFilter = cp.getSslFilter();
    assertFalse(sslFilter.isNeedClientAuth());
    assertFalse(sslFilter.isWantClientAuth());
    assertFalse(sslFilter.isUseClientMode());
    assertNotNull(sslFilter.getEnabledCipherSuites());
    assertEquals(2, sslFilter.getEnabledCipherSuites().length);
}
 
Example #27
Source File: ClientTestServer.java    From java-study with Apache License 2.0 5 votes vote down vote up
public IoConnector creatClient(){  
    IoConnector connector=new NioSocketConnector();   
    connector.setConnectTimeoutMillis(30000);   
    connector.getFilterChain().addLast("codec",   
    new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));  
    connector.setHandler(new MinaClientHandler());  
    return connector;  
}
 
Example #28
Source File: LoginServer.java    From mapleLemon with GNU General Public License v2.0 5 votes vote down vote up
public static void run_startup_configurations() {
    userLimit = ServerProperties.getProperty("userlimit", 140);
    serverName = ServerProperties.getProperty("serverName", "MapleStory");
    flag = ServerProperties.getProperty("flag", (byte) 3);
    adminOnly = Boolean.parseBoolean(ServerProperties.getProperty("admin", "false"));
    maxCharacters = ServerProperties.getProperty("maxCharacters", 30);
    autoReg = Boolean.parseBoolean(ServerProperties.getProperty("autoReg", "false"));
    checkMacs = Boolean.parseBoolean(ServerProperties.getProperty("checkMacs", "false"));
    port = Short.parseShort(ServerProperties.getProperty("world.port", String.valueOf(DEFAULT_PORT)));

    IoBuffer.setUseDirectBuffer(false);
    IoBuffer.setAllocator(new SimpleBufferAllocator());

    acceptor = new NioSocketAcceptor();
    acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MapleCodecFactory()));
    acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30);

    try {
        acceptor.setHandler(new MapleServerHandler(MapleServerHandler.LOGIN_SERVER));
        acceptor.bind(new InetSocketAddress(port));
        ((SocketSessionConfig) acceptor.getSessionConfig()).setTcpNoDelay(true);

        FileoutputUtil.log("\"登入\"伺服器正在监听" + port + "端口\r\n");
    } catch (IOException e) {
        System.err.println("无法绑定" + port + "端口: " + e);
    }
}
 
Example #29
Source File: TlsNioConfigTest.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Test
public void secureServerSupportsTlsNoClientAuthKeystoreProvided() throws IOException {
    TlsNioConfig config = new TlsNioConfig();
    config.setNioLogger(logger);
    config.setMbeanServer(mbeanServer);
    config.setKeystore(new FileSystemResource(getServerKeystorePath()));
    config.setKeystorePassword("password");
    config.setKeystoreType("JKS");
    config.setWantClientAuth(false);
    config.setNeedClientAuth(false);
    config.setRequiresTls(false);
    config.setSupportsTls(true);
    config.configureProtocol(minaConfig, true);

    List<Tuple<String, IoFilter>> addedFilters = getAddedFilters();
    assertEquals("slowHandling", addedFilters.get(0).getFirst());
    assertInstanceOf(SessionWriteQueueMonitoring.class, addedFilters.get(0).getSecond());
    assertEquals("codec", addedFilters.get(1).getFirst());
    assertInstanceOf(ProtocolCodecFilter.class, addedFilters.get(1).getSecond());
    assertEquals("protocol", addedFilters.get(2).getFirst());
    assertInstanceOf(CougarProtocol.class, addedFilters.get(2).getSecond());

    CougarProtocol cp = (CougarProtocol) addedFilters.get(2).getSecond();
    assertFalse(cp.isRequiresTls());
    assertTrue(cp.isSupportsTls());
    assertNotNull(cp.getSslFilter());
    SSLFilter sslFilter = cp.getSslFilter();
    assertFalse(sslFilter.isNeedClientAuth());
    assertFalse(sslFilter.isWantClientAuth());
    assertFalse(sslFilter.isUseClientMode());
    assertNull(sslFilter.getEnabledCipherSuites());
}
 
Example #30
Source File: ImageServer.java    From javastruct with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws IOException
{
  ImageServerIoHandler handler = new ImageServerIoHandler();
  SocketAcceptor acceptor = new SocketAcceptor();
  acceptor.getFilterChain().addLast("protocol", new ProtocolCodecFilter(new ImageCodecFactory(false)));
  acceptor.bind(new InetSocketAddress(PORT), handler);
  System.out.println("server is listenig at port " + PORT);
}