Java 类org.apache.mina.filter.codec.ProtocolCodecFilter 实例源码

项目:frameworkAggregate    文件:MinaTimeServer.java   
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));
    }
项目:Pogamut3    文件:TCMinaClient.java   
public void connect() {     
    synchronized(mutex) {
        if (connected.getFlag()) return;
        if (connecting.getFlag()) return;
        log.warning("Connecting to TC at " + getHost() + ":" + getPort() + " ...");
        connecting.setFlag(true);
    }

    try {
        ioConnector = new NioSocketConnector();

        ioConnector.setHandler(this);

        ioConnector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));

        connectFuture = ioConnector.connect(address);

        connectFuture.addListener(connectionListener);
    } catch (Exception e1) {
        try {
            connecting.setFlag(false);
        } catch (Exception e2) {                
        }
    }

}
项目:jforgame    文件:SocketServer.java   
/**
 * start Mina serversocket
 * @throws Exception
 */
public void start() throws Exception {
    IoBuffer.setUseDirectBuffer(false);
    IoBuffer.setAllocator(new SimpleBufferAllocator());

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

    int serverPort = GateServerConfig.serverPort;
    logger.info("socket server start at port:{},正在监听客户端的连接...", serverPort);
    DefaultIoFilterChainBuilder filterChain = acceptor.getFilterChain();
    filterChain.addLast("codec", new ProtocolCodecFilter(MessageCodecFactory.getInstance()));
    acceptor.setHandler( new ServerSocketIoHandler() );//指定业务逻辑处理器
    acceptor.setDefaultLocalAddress(new InetSocketAddress(serverPort) );//设置端口号
    acceptor.bind();//启动监听

}
项目:neoscada    文件:ArduinoDevice.java   
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 );
}
项目:neoscada    文件:ModbusMaster.java   
@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" ) );
    }
}
项目:AeroStory    文件:Channel.java   
public Channel(final int world, final int channel) {
    this.world = world;
    this.channel = channel;
    this.mapFactory = new MapleMapFactory(MapleDataProviderFactory.getDataProvider(new File(System.getProperty("wzpath") + "/Map.wz")), MapleDataProviderFactory.getDataProvider(new File(System.getProperty("wzpath") + "/String.wz")), world, channel);

    try {
        eventSM = new EventScriptManager(this, ServerConstants.EVENTS.split(" "));
        port = 7575 + this.channel - 1;
        port += (world * 100);
        ip = ServerConstants.HOST + ":" + port;
        IoBuffer.setUseDirectBuffer(false);
        IoBuffer.setAllocator(new SimpleBufferAllocator());
        acceptor = new NioSocketAcceptor();
        TimerManager.getInstance().register(new respawnMaps(), 10000);
        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);

        eventSM.init();
        System.out.println("    Channel " + getId() + ": Listening on port " + port);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:java-tutorial    文件:MinaTimeServer.java   
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));
}
项目:Lucid2.0    文件:CashShopServer.java   
public static void run_startup_configurations() {
    ip = ServerConfig.IP_ADDRESS + ":" + PORT;

    ByteBuffer.setUseDirectBuffers(false);
    ByteBuffer.setAllocator(new SimpleByteBufferAllocator());

    acceptor = new SocketAcceptor();
    final SocketAcceptorConfig cfg = new SocketAcceptorConfig();
    cfg.getSessionConfig().setTcpNoDelay(true);
    cfg.setDisconnectOnUnbind(true);
    cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MapleCodecFactory()));
    players = new PlayerStorage(-10);

    try {
        InetSocketadd = new InetSocketAddress(PORT);
        acceptor.bind(InetSocketadd, new MapleServerHandler(), cfg);
        System.out.println("Cash Shop Server is listening on port " + PORT + ".");
    } catch (final IOException e) {
        System.out.println(" Failed!");
        System.err.println("Could not bind to port " + PORT + ".");
        throw new RuntimeException("Binding failed.", e);
    }
}
项目:Lucid2.0    文件:LoginServer.java   
public static final void run_startup_configurations() {
    userLimit = ServerConfig.USER_LIMIT;
    serverName = ServerConfig.SERVER_NAME;
    eventMessage = ServerConfig.EVENT_MSG;
    maxCharacters = ServerConfig.MAX_CHARACTERS;

    ByteBuffer.setUseDirectBuffers(false);
    ByteBuffer.setAllocator(new SimpleByteBufferAllocator());

    acceptor = new SocketAcceptor();
    final SocketAcceptorConfig cfg = new SocketAcceptorConfig();
    cfg.getSessionConfig().setTcpNoDelay(true);
    cfg.setDisconnectOnUnbind(true);
    cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MapleCodecFactory()));

    try {
        InetSocketadd = new InetSocketAddress(8484);
        acceptor.bind(InetSocketadd, new MapleServerHandler(), cfg);
        System.out.println("Login Server is listening on port 8484.");
    } catch (IOException e) {
        System.out.println(" Failed!");
        System.err.println("Could not bind to port 8484: " + e);
    }
}
项目:grain    文件:MinaClient.java   
/**
 * 初始化
 * 
 * @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();
}
项目:mina    文件:CalculatorServer.java   
public static void main(String[] args) throws IOException {
        IoAcceptor acceptor = new NioSocketAcceptor();
//        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, IDELTIMEOUT);

        acceptor.getFilterChain().addLast("logger", new LoggingFilter());
        acceptor.getFilterChain().addLast("myfliter", new MyFilter());
        acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new CommandCodecFactory("UTF-8")));

        KeepAliveMessageFactoryImpl kamfi = new KeepAliveMessageFactoryImpl();
        KeepAliveFilter kaf = new KeepAliveFilter(kamfi, IdleStatus.BOTH_IDLE);
        /** 是否回发 */
        kaf.setForwardEvent(true);
        acceptor.getFilterChain().addLast("heart", kaf);

        acceptor.setHandler(new CalculatorHandler());
        acceptor.bind(new InetSocketAddress(PORT));

        log.debug("socket通信服务端已启动,端口是" + PORT);
    }
项目:java-project    文件:Server.java   
public static void main(String[] args) throws Exception{
    int port=9527;

    final IoAcceptor acceptor=new SocketAcceptor(Runtime.getRuntime().availableProcessors() + 1,
                                           Executors.newCachedThreadPool());
    acceptor.getFilterChain().addLast("stringserialize", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
    IoHandler handler=new IoHandlerAdapter(){

        public void messageReceived(IoSession session, Object message)
                throws Exception {
            if("quit".equalsIgnoreCase(message.toString())){
                acceptor.unbindAll();
                System.out.println("Server has been shutdown!");
                System.exit(0);
            }
            System.out.println("Message from client: "+message);
            session.write("Server response��"+message);
        }

    };
    acceptor.bind(new InetSocketAddress(port), handler);
    System.out.println("Server listen on port: "+port);
}
项目:Mushy    文件:CashShopServer.java   
public static void run_startup_configurations() {
    ip = ServerConfig.IP_ADDRESS + ":" + PORT;

    ByteBuffer.setUseDirectBuffers(false);
    ByteBuffer.setAllocator(new SimpleByteBufferAllocator());

    acceptor = new SocketAcceptor();
    final SocketAcceptorConfig cfg = new SocketAcceptorConfig();
    cfg.getSessionConfig().setTcpNoDelay(true);
    cfg.setDisconnectOnUnbind(true);
    cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MapleCodecFactory()));
    players = new PlayerStorage(-10);

    try {
        InetSocketadd = new InetSocketAddress(PORT);
        acceptor.bind(InetSocketadd, new MapleServerHandler(), cfg);
        System.out.println("Cash Shop Server is listening on port " + PORT + ".");
    } catch (final IOException e) {
        System.out.println(" Failed!");
        System.err.println("Could not bind to port " + PORT + ".");
        throw new RuntimeException("Binding failed.", e);
    }
}
项目:Mushy    文件:LoginServer.java   
public static final void run_startup_configurations() {
    userLimit = ServerConfig.USER_LIMIT;
    serverName = ServerConfig.SERVER_NAME;
    eventMessage = ServerConfig.EVENT_MSG;
    maxCharacters = ServerConfig.MAX_CHARACTERS;

    ByteBuffer.setUseDirectBuffers(false);
    ByteBuffer.setAllocator(new SimpleByteBufferAllocator());

    acceptor = new SocketAcceptor();
    final SocketAcceptorConfig cfg = new SocketAcceptorConfig();
    cfg.getSessionConfig().setTcpNoDelay(true);
    cfg.setDisconnectOnUnbind(true);
    cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MapleCodecFactory()));

    try {
        InetSocketadd = new InetSocketAddress(8484);
        acceptor.bind(InetSocketadd, new MapleServerHandler(), cfg);
        System.out.println("Login Server is listening on port 8484.");
    } catch (IOException e) {
        System.out.println(" Failed!");
        System.err.println("Could not bind to port 8484: " + e);
    }
}
项目:light-task-scheduler    文件:MinaRemotingServer.java   
@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);
    }
}
项目:light-task-scheduler    文件:MinaRemotingClient.java   
@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);
    }
}
项目:Halo-Turbo    文件:MinaTcpServerSocket.java   
private void init(Config config) {
    address = new InetSocketAddress(config.sourcePort);
    acceptor = new NioSocketAcceptor();
    if (acceptor.getFilterChain().get(LOGGER) == null) {
        acceptor.getFilterChain().addLast(LOGGER, new LoggingFilter());
    }
    if (acceptor.getFilterChain().get(CODEC) == null) {
        ProtocolCodecFactory codecFactory = config.codec == null ?
                MinaUtil.getTextLineCodecFactory() : (ProtocolCodecFactory) config.codec;
        acceptor.getFilterChain().addLast(CODEC, new ProtocolCodecFilter(codecFactory));
    }
    acceptor.setHandler(new MinaServerHandler());
    acceptor.getSessionConfig().setReadBufferSize(config.bufferSize);
    acceptor.getSessionConfig().setIdleTime(IdleStatus.WRITER_IDLE, 10);
    acceptor.setReuseAddress(true); //避免重启时提示地址被占用
    //设置主服务监听端口的监听队列的最大值为50,如果当前已经有50个连接,新的连接将被服务器拒绝
    acceptor.setBacklog(50);

    KeepAliveFilter keepAliveFilter = MinaUtil.initServerKeepAlive(config, this);
    if (keepAliveFilter != null) {
        acceptor.getFilterChain().addLast(HEARTBEAT, keepAliveFilter);
    }
}
项目:Halo-Turbo    文件:MinaUdpClientSocket.java   
private void init(Config config) {
    connector = new NioDatagramConnector();
    connector.setHandler(new MinaClientHandler());
    DefaultIoFilterChainBuilder chain = connector.getFilterChain();
    if (connector.getFilterChain().get(LOGGER) == null) {
        chain.addLast(LOGGER, new LoggingFilter());
    }
    if (connector.getFilterChain().get(CODEC) == null) {
        ProtocolCodecFactory codecFactory = config.codec == null ?
                MinaUtil.getTextLineCodecFactory() : (ProtocolCodecFactory) config.codec;
        chain.addLast(CODEC, new ProtocolCodecFilter(codecFactory));
    }
    connector.getSessionConfig().setReadBufferSize(config.bufferSize);
    connector.getSessionConfig().setIdleTime(IdleStatus.WRITER_IDLE, 10);
    connector.getSessionConfig().setBroadcast(true);
    KeepAliveFilter keepAliveFilter = MinaUtil.initClientKeepAlive(config, this);
    if (keepAliveFilter != null) {
        connector.getFilterChain().addLast(HEARTBEAT, keepAliveFilter);
    }
}
项目:Halo-Turbo    文件:MinaTcpClientSocket.java   
private void init(Config config) {
    address = new InetSocketAddress(config.targetIP, config.targetPort);
    connector = new NioSocketConnector();
    connector.setDefaultRemoteAddress(address);
    if (connector.getFilterChain().get(LOGGER) == null) {
        connector.getFilterChain().addLast(LOGGER, new LoggingFilter());
    }
    if (connector.getFilterChain().get(CODEC) == null) {
        ProtocolCodecFactory codecFactory = config.codec == null ?
                MinaUtil.getTextLineCodecFactory() : (ProtocolCodecFactory) config.codec;
        connector.getFilterChain().addLast(CODEC, new ProtocolCodecFilter(codecFactory));
    }
    connector.setHandler(new MinaClientHandler());
    connector.getSessionConfig().setReadBufferSize(config.bufferSize);
    connector.getSessionConfig().setIdleTime(IdleStatus.WRITER_IDLE, 10);
    KeepAliveFilter keepAliveFilter = MinaUtil.initClientKeepAlive(config, this);
    if (keepAliveFilter != null) {
        connector.getFilterChain().addLast(HEARTBEAT, keepAliveFilter);
    }
}
项目:Halo-Turbo    文件:MinaUdpServerSocket.java   
private void init(Config config) {
    address = new InetSocketAddress(config.sourcePort);

    acceptor = new NioDatagramAcceptor();
    acceptor.setHandler(new MinaServerHandler());
    DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
    if (acceptor.getFilterChain().get(LOGGER) == null) {
        chain.addLast(LOGGER, new LoggingFilter());
    }
    if (acceptor.getFilterChain().get(CODEC) == null) {
        ProtocolCodecFactory codecFactory = config.codec == null ?
                MinaUtil.getTextLineCodecFactory() : (ProtocolCodecFactory) config.codec;
        chain.addLast(CODEC, new ProtocolCodecFilter(codecFactory));
    }
    DatagramSessionConfig dcfg = acceptor.getSessionConfig();
    dcfg.setReuseAddress(true);
    dcfg.setReadBufferSize(config.bufferSize);
    dcfg.setIdleTime(IdleStatus.WRITER_IDLE, 10);
    dcfg.setBroadcast(true);

    KeepAliveFilter keepAliveFilter = MinaUtil.initServerKeepAlive(config, this);
    if (keepAliveFilter != null) {
        acceptor.getFilterChain().addLast(HEARTBEAT, keepAliveFilter);
    }
}
项目:My-ChatSystem    文件:Server.java   
/**
 * �������
 * @param args
 * @throws IOException 
 */
public  void startServer()  {
     server = new NioSocketAcceptor();
    //�������ݹ�����
    DefaultIoFilterChainBuilder  filterChain = server.getFilterChain();
    filterChain.addLast("myChin", new ProtocolCodecFilter(  
               new ObjectSerializationCodecFactory()));

    //filterChain.addLast("textCode",new ProtocolCodecFilter(
    //          new TextLineCodecFactory(Charset.forName("UTF-8"))));

    serverIOHandler = new ServerIOHandler(severFrame);
    server.setHandler(serverIOHandler);
    //�����������˿� --- ����������
    try {
        server.bind(new InetSocketAddress(port));
    } catch (IOException e) {
        Tools.show(severFrame, "�˿��Ѿ�ռ�ã��뻻���˿ڣ�");
    }
}
项目:GameServerFramework    文件:FrontendServer.java   
/**
 * 创建 Mina2 Core 服务核心并启动
 *
 * @return
 */
private boolean startupMinaCore() {
    _acceptor = new NioSocketAcceptor();
    // 禁用算法
    _acceptor.getSessionConfig().setTcpNoDelay(true);
    // 添加过滤链处理项
    _acceptor.getFilterChain().addLast("codec",
            new ProtocolCodecFilter(new CodecFactory()));
    // 设置处理器
    _acceptor.setHandler(new FrontendServerHandler(this));
    try {
        _acceptor.bind(new InetSocketAddress(getServerConfig()
                .getFrontendPort()));
    } catch (IOException e) {
        logger.error("启动 Mina Core 监听失败:", e);
        return false;
    }
    logger.error("Mina Core Startup Success On Port:"
            + getServerConfig().getFrontendPort());
    return true;
}
项目:STAFF    文件:TcpServer.java   
public void open() throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("Start logger.");
    }

    SocketAcceptorConfig cfg = new SocketAcceptorConfig();
    cfg.setReuseAddress(true);

    if(useFixCodec) {
        cfg.getFilterChain().addLast("codec",
            new ProtocolCodecFilter(new ServerProtocolCodecFactory()));
    } else {
        cfg.getFilterChain().addLast("codec",
            new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
    }

    cfg.getFilterChain().addLast("logger", new LoggingFilter());

    acceptor.bind(new InetSocketAddress(port), this, cfg);

    System.out.println("Listening on port " + port);
}
项目:maker    文件:BeatServer.java   
public static void main(String[] args) {
    int port = U.getInt("cleaner.server.port");
    int idleTime = U.getInt("cleaner.server.time");
    NioSocketAcceptor clientAcceptor = new NioSocketAcceptor();
    clientAcceptor.setReuseAddress(true);

    DefaultIoFilterChainBuilder chain = clientAcceptor.getFilterChain();
    SocketSessionConfig config = clientAcceptor.getSessionConfig();
    config.setIdleTime(IdleStatus.READER_IDLE, idleTime);// 读空闲 10秒
    config.setReuseAddress(true);
    config.setReadBufferSize(4096);// 默认2048
    config.setKeepAlive(true);
    config.setTcpNoDelay(true);// 开启nagle算法
    // 编解码
    chain.addLast("coder", new ProtocolCodecFilter(new TextLineCodecFactory(U.UTF8)));
    clientAcceptor.setHandler(new CleanerHandler());
    try {
        clientAcceptor.bind(new InetSocketAddress(port));
        log.info("心跳模块启动..");
    } catch (IOException e) {
        log.error("心跳模块启动失败", e);
    }
}
项目:maker    文件:TcpServer.java   
public void initialize() {
    idleTime = U.getInt("chat.server.idleTime");
    System.out.println(idleTime);

    clientAcceptor = new NioSocketAcceptor();
    clientAcceptor.setReuseAddress(true);

    DefaultIoFilterChainBuilder chain = clientAcceptor.getFilterChain();
    SocketSessionConfig config = clientAcceptor.getSessionConfig();
    config.setReuseAddress(true);
    config.setIdleTime(IdleStatus.READER_IDLE, idleTime);// 读空闲 20秒
    config.setReadBufferSize(4096);// 默认2048
    config.setKeepAlive(true);
    config.setTcpNoDelay(true);// 禁用/开启nagle算法
    // 编解码
    chain.addLast("coder", new ProtocolCodecFilter(new MessageCodecFactory()));
    // 日志
    chain.addLast("logger", new LoggingFilter());
    // 业务逻辑处理线程池
    chain.addLast("threadPool", new ExecutorFilter());
}
项目:subetha    文件:PostfixTcpTableService.java   
/** */
@PostConstruct
public void start() throws IOException
{
    if (this.acceptor != null)
        throw new IllegalStateException("TcpTableService already running");

    InetAddress binding = null;

    String bindAddress = System.getProperty("jboss.bind.address");
    if (bindAddress != null && !"0.0.0.0".equals(bindAddress))
        binding = InetAddress.getByName(bindAddress);

    log.log(Level.INFO,"Starting TcpTableService: {0}:{1}", new Object[]{(binding==null ? "*" : binding),port});

    this.acceptor = new SocketAcceptor();
    this.acceptor.getFilterChain().addLast(
            "codec",
            new ProtocolCodecFilter(
                    new TextLineCodecFactory(Charset.forName("UTF-8"))));

    this.acceptor.bind(new InetSocketAddress(binding, this.port), new Handler());
}
项目:mapleLemon    文件:CashShopServer.java   
public static void run_startup_configurations() {
    autoPaoDian = Integer.parseInt(ServerProperties.getProperty("autoPaoDian", "1"));
    port = Short.parseShort(ServerProperties.getProperty("cashshop.port", String.valueOf(DEFAULT_PORT)));
    ip = ServerProperties.getProperty("world.host", ServerConstants.IP) + ":" + 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);
    players = new PlayerStorage(MapleServerHandler.CASH_SHOP_SERVER);
    try {
        acceptor.setHandler(new MapleServerHandler(MapleServerHandler.CASH_SHOP_SERVER));
        acceptor.bind(new InetSocketAddress(port));
        ((SocketSessionConfig) acceptor.getSessionConfig()).setTcpNoDelay(true);

        FileoutputUtil.log("完成!");
        FileoutputUtil.log("商城伺服器正在监听" + port + "端口\r\n");
    } catch (IOException e) {
        FileoutputUtil.log("失败!");
        System.err.println("无法绑定" + port + "端口");
        throw new RuntimeException("绑定端口失败.", e);
    }
}
项目:GameServer    文件:NetManager.java   
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));
}
项目:GameServer_demo    文件:TestClient.java   
public Work(){
            NioSocketConnector connector = new NioSocketConnector(); 
            connector.getFilterChain().addLast( "logger", new LoggingFilter() ); 
            connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new MessageCodecFactory())); //设置编码过滤器 
            connector.setConnectTimeoutMillis(30000); 
            connector.setHandler(new ClientMessageHandler());//设置事件处理器 
            ConnectFuture cf = connector.connect( 
                    new InetSocketAddress("127.0.0.1", 50000));//建立连接 
            cf.awaitUninterruptibly();//等待连接创建完成 
            ByteArray ba = new ByteArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("parseId", 1);
            jsonObject.put("command", 1);
            jsonObject.put("text", "涂鸦");
            ba.writeUTF(jsonObject.toJSONString());
            cf.getSession().write(ba.toArray());
//          cf.getSession().write("涂鸦");//发送消息 
//          cf.getSession().write("quit");//发送消息 
//          cf.getSession().getCloseFuture().awaitUninterruptibly();//等待连接断开 
//          connector.dispose();
        }
项目:GameServer_demo    文件:HttpServer.java   
/**
 * 启动HTTP服务端箭筒HTTP请求
 * 
 * @param port要监听的端口号
 * @throws IOException
 */
public void run(int port) throws IOException {
    synchronized (this) {
        if (isRunning) {
            System.out.println("Server is already running.");
            return;
        }
        acceptor = new NioSocketAcceptor();
        acceptor.getFilterChain().addLast(
                "protocolFilter",
                new ProtocolCodecFilter(
                        new HttpServerProtocolCodecFactory()));
        // acceptor.getFilterChain().addLast("logger", new LoggingFilter());
        ServerHandler handler = new ServerHandler();
        handler.setHandler(httpHandler);
        acceptor.setHandler(handler);
        acceptor.bind(new InetSocketAddress(port));
        isRunning = true;
        System.out.println("Server now listening on port " + port);
    }
}
项目:PearlHarbor    文件:TCPConnectionClasser_mina.java   
public void start()
{
    mAcceptor = new NioSocketAcceptor();
    LoggingFilter loggingFilter = new LoggingFilter();
    loggingFilter.setSessionClosedLogLevel(LogLevel.NONE);
    loggingFilter.setSessionCreatedLogLevel(LogLevel.NONE);
    loggingFilter.setSessionOpenedLogLevel(LogLevel.NONE);
    loggingFilter.setMessageSentLogLevel(LogLevel.NONE);
    mAcceptor.getFilterChain().addLast("logger", loggingFilter);

    mAcceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MinaCodec.Encoder(), new MinaCodec.Decoder()));
    mAcceptor.getSessionConfig().setReadBufferSize(4096);
    // macceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
    mServerHandler = new MinaServerHandler();
    mAcceptor.setHandler(mServerHandler);

    try {
        mAcceptor.bind(new InetSocketAddress(ServerConfig.NET_TCP_IP, ServerConfig.NET_TCP_PORT));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
项目:red5-websocket    文件:WebSocketServerTest.java   
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");
        }
    }
}
项目:opencraft    文件:OCClient.java   
/**
 * Attempt to connect to the info server.
 */
public void connect()
{
    try
    {
        ConnectFuture future = connector.connect(new InetSocketAddress(IP, PORT));
        future.awaitUninterruptibly(AWAIT_TIME);

        IoSession session = future.getSession();
        session.getFilterChain().addFirst("protocol", new ProtocolCodecFilter(factory));
        state = State.READY;
        this.onConnect(session);
    }
    catch(RuntimeIoException e)
    {
        this.onFailure(e);
    }
}
项目:mina-examples    文件:HelloTcpClient.java   
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();
}
项目:oliot-fc    文件:LLRPConnector.java   
/**
 * connects to a LLRP device at the host address and port specified. the connect method waits
 * for the timeperiod specified (in ms) for a response. If the READER_NOTIFICATION does not arrive 
 * or the ConnectionAttemptEventStatus 
 * is not set to 'Success', a LLRPConnectionAttemptFailedException is thrown.
 * 
 * @param timeout time in ms
 * @throws LLRPConnectionAttemptFailedException
 */

public void connect(long timeout) throws LLRPConnectionAttemptFailedException{
    connector = new NioSocketConnector();
    connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new LLRPProtocolCodecFactory(LLRPProtocolCodecFactory.BINARY_ENCODING)));
    // MINA 2.0 method 
    connector.setHandler(handler);
    remoteAddress = new InetSocketAddress(host, port);
    ConnectFuture future = connector.connect(remoteAddress);//.connect(remoteAddress,handler);
    future.join();// Wait until the connection attempt is finished.

    if(future.isConnected()){
        session = future.getSession();
    }else{
        String msg = "failed to connect";
        throw new LLRPConnectionAttemptFailedException(msg);
    }
    // MINA 2.0
    //future.awaitUninterruptibly();

    //check if llrp reader reply with a status report to indicate connection success.
    //the client shall not send any information to the reader until this status report message is received
    checkLLRPConnectionAttemptStatus(timeout);

}
项目:dynamicpool    文件:NIOSocketServerController.java   
public NIOSocketServerController(SocketServerConfig config) {
    this.setConfig(config);
    this.acceptor = new NioSocketAcceptor();

    acceptor.getFilterChain().addLast("logger", new LoggingFilter());
    acceptor.getFilterChain().addLast(
            "codec",
            new ProtocolCodecFilter(new TextLineCodecFactory(Charset
                    .forName("UTF-8"))));

    acceptor.setHandler(this);

    acceptor.getSessionConfig().setReadBufferSize(2048);
    acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

    json = new JSON();
    this.processorManager = new ProcessorManager();
}
项目:dynamicpool    文件:NIOSocketServerController.java   
public NIOSocketServerController(SocketServerConfig config) {
    this.setConfig(config);
    this.acceptor = new NioSocketAcceptor();

    acceptor.getFilterChain().addLast("logger", new LoggingFilter());
    acceptor.getFilterChain().addLast(
            "codec",
            new ProtocolCodecFilter(new TextLineCodecFactory(Charset
                    .forName("UTF-8"))));

    acceptor.setHandler(this);

    acceptor.getSessionConfig().setReadBufferSize(2048);
    acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

    json = new JSON();
    this.processorManager = new ProcessorManager();
}
项目:g3server    文件:ConnectionManagerImpl.java   
private void createConnectionManagerListener() {
    // Start multiplexers socket unless it's been disabled.
    if (isConnectionManagerListenerEnabled()) {
        // Create SocketAcceptor with correct number of processors
        multiplexerSocketAcceptor = buildSocketAcceptor();
        // Customize Executor that will be used by processors to process incoming stanzas
        ExecutorThreadModel threadModel = ExecutorThreadModel.getInstance("connectionManager");
        int eventThreads = JiveGlobals.getIntProperty("xmpp.multiplex.processing.threads", 16);
        ThreadPoolExecutor eventExecutor = (ThreadPoolExecutor) threadModel.getExecutor();
        eventExecutor.setCorePoolSize(eventThreads + 1);
        eventExecutor.setMaximumPoolSize(eventThreads + 1);
        eventExecutor.setKeepAliveTime(60, TimeUnit.SECONDS);
        multiplexerSocketAcceptor.getDefaultConfig().setThreadModel(threadModel);
        // Add the XMPP codec filter
        multiplexerSocketAcceptor.getFilterChain().addFirst("xmpp", new ProtocolCodecFilter(new XMPPCodecFactory()));

    }
}
项目:g3server    文件:ConnectionManagerImpl.java   
private void createComponentListener() {
    // Start components socket unless it's been disabled.
    if (isComponentListenerEnabled() && componentAcceptor == null) {
        // Create SocketAcceptor with correct number of processors
        componentAcceptor = buildSocketAcceptor();
        // Customize Executor that will be used by processors to process incoming stanzas
        ExecutorThreadModel threadModel = ExecutorThreadModel.getInstance("component");
        int eventThreads = JiveGlobals.getIntProperty("xmpp.component.processing.threads", 16);
        ThreadPoolExecutor eventExecutor = (ThreadPoolExecutor)threadModel.getExecutor();
        eventExecutor.setCorePoolSize(eventThreads + 1);
        eventExecutor.setMaximumPoolSize(eventThreads + 1);
        eventExecutor.setKeepAliveTime(60, TimeUnit.SECONDS);

        componentAcceptor.getDefaultConfig().setThreadModel(threadModel);
        // Add the XMPP codec filter
        componentAcceptor.getFilterChain().addFirst("xmpp", new ProtocolCodecFilter(new XMPPCodecFactory()));
    }
}
项目:g3server    文件:ConnectionManagerImpl.java   
private void createClientListeners() {
    // Start clients plain socket unless it's been disabled.
    if (isClientListenerEnabled()) {
        // Create SocketAcceptor with correct number of processors
        socketAcceptor = buildSocketAcceptor();
        // Customize Executor that will be used by processors to process incoming stanzas
        ExecutorThreadModel threadModel = ExecutorThreadModel.getInstance("client");
        int eventThreads = JiveGlobals.getIntProperty("xmpp.client.processing.threads", 16);
        ThreadPoolExecutor eventExecutor = (ThreadPoolExecutor)threadModel.getExecutor();
        eventExecutor.setCorePoolSize(eventThreads + 1);
        eventExecutor.setMaximumPoolSize(eventThreads + 1);
        eventExecutor.setKeepAliveTime(60, TimeUnit.SECONDS);

        socketAcceptor.getDefaultConfig().setThreadModel(threadModel);
        // Add the XMPP codec filter
        socketAcceptor.getFilterChain().addFirst("xmpp", new ProtocolCodecFilter(new XMPPCodecFactory()));
        // Kill sessions whose outgoing queues keep growing and fail to send traffic
        socketAcceptor.getFilterChain().addAfter("xmpp", "outCap", new StalledSessionsFilter());
    }
}