private IoAcceptor createAcceptor(final IoHandler ioHandler) throws IOException {
    IoAcceptor acceptor = null;

    final SocketImpl socketImpl =
        SocketImpl.fromName(this.connectionInformation.getProperties().get("socketImpl"));

    // create the acceptor
    acceptor = socketImpl.createAcceptor();

    // set up the filter chain
    ConnectionHelper.setupFilterChain(this.connectionInformation, acceptor.getFilterChain(), false);

    // set the session handler
    acceptor.setHandler(ioHandler);

    // check if the primary target is the wildcard target
    String host = this.connectionInformation.getTarget();
    if (host != null && (host.length() == 0 || "*".equals(host))) {
      host = null;
    }

    // bind
    if (host != null) {
      acceptor.bind(socketImpl.doLookup(host, this.connectionInformation.getSecondaryTarget()));
    } else {
      acceptor.bind(new InetSocketAddress(this.connectionInformation.getSecondaryTarget()));
    }

    return acceptor;
  }
 @Override
 protected void serverShutdown() throws RemotingException {
   if (acceptor != null) {
     acceptor.unbind(bindAddress);
     acceptor.dispose();
   }
 }
  public void testAcceptorFilterChain() throws Exception {
    int port = AvailablePortFinder.getNextAvailable(1024 + 1000);
    IoFilter mockFilter = new MockFilter();
    IoHandler mockHandler = new MockHandler();

    acceptor.getFilterChain().addLast("mock", mockFilter);
    acceptor.setHandler(mockHandler);
    acceptor.bind(new InetSocketAddress(port));

    try {
      connector.setHandler(new IoHandlerAdapter());
      ConnectFuture future = connector.connect(new InetSocketAddress("127.0.0.1", port));
      future.awaitUninterruptibly();

      WriteFuture writeFuture = future.getSession().write(IoBuffer.allocate(16).putInt(0).flip());
      writeFuture.awaitUninterruptibly();
      Assert.assertTrue(writeFuture.isWritten());

      future.getSession().close(true);

      for (int i = 0; i < 30; i++) {
        if (result.length() == 2) {
          break;
        }
        Thread.sleep(100);
      }

      Assert.assertEquals("FH", result);
    } finally {
      acceptor.unbind();
    }
  }
  private void sshSummary() {
    IoAcceptor acceptor = daemon.getIoAcceptor();
    if (acceptor == null) {
      return;
    }

    long now = System.currentTimeMillis();
    Collection<IoSession> list = acceptor.getManagedSessions().values();
    long oldest = now;
    for (IoSession s : list) {
      oldest = Math.min(oldest, s.getCreationTime());
    }

    stdout.format(
        "SSH:   %4d  users, oldest session started %s ago\n", list.size(), uptime(now - oldest));
  }
Exemple #5
0
  public static void main(String args[]) {

    RailManager3.init();

    HibernateModel.createMap();

    IoAcceptor acceptor;
    acceptor = new NioSocketAcceptor();
    acceptor.getFilterChain().addLast("logger", new LoggingFilter());
    acceptor
        .getFilterChain()
        .addLast("codec", new ProtocolCodecFilter(new MyProtocalCodecFactory()));
    acceptor
        .getFilterChain()
        .addLast("threadPool", new ExecutorFilter(new OrderedThreadPoolExecutor()));
    acceptor.getSessionConfig().setReadBufferSize(1024);
    acceptor.getSessionConfig().setBothIdleTime(60 * 5); // Ãë
    acceptor.setHandler(new MyHandler());
    try {
      acceptor.bind(new InetSocketAddress(9000));
      System.out.println("Server Start!");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  public void bind() throws IOException {
    acceptor = new NioSocketAcceptor();
    acceptor.getSessionConfig().setReadBufferSize(1024);
    ((DefaultSocketSessionConfig) acceptor.getSessionConfig()).setTcpNoDelay(true);
    acceptor.getFilterChain().addLast("executor", new ExecutorFilter());
    acceptor.getFilterChain().addLast("logger", new LoggingFilter());
    acceptor
        .getFilterChain()
        .addLast(
            "codec",
            new ProtocolCodecFilter(
                new com.farsunset.cim.server.filter.ServerMessageCodecFactory()));
    KeepAliveMessageFactory heartBeatFactory = new ServerKeepAliveFactoryImpl();
    KeepAliveFilter keepAliveFilter =
        new KeepAliveFilter(
            heartBeatFactory,
            IdleStatus.BOTH_IDLE,
            KeepAliveRequestTimeoutHandler.CLOSE,
            IDLE_TIME,
            TIME_OUT);
    keepAliveFilter.setForwardEvent(true);
    acceptor.getFilterChain().addLast("heartbeat", keepAliveFilter);
    acceptor.setHandler(ioHandler);

    acceptor.bind(new InetSocketAddress(port));
  }
 public static void main(String[] args) throws Exception {
   XmlGatewayServerManager manager = new XmlGatewayServerManager();
   manager.initializeConfiguration("conf/server.xml");
   ServerConfiguration configuration = manager.getServerConfiguration();
   Connector connector = configuration.getConnectors().get(0);
   IoAcceptor acceptor = new NioSocketAcceptor();
   //        acceptor.getFilterChain().addLast("logger", new LoggingFilter());
   HutCodecFactory factory = new HutCodecFactory(Charset.forName("UTF-8"));
   acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(factory));
   acceptor.setHandler(new HutSimulator());
   acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
   acceptor.bind(
       new InetSocketAddress(connector.getOutbound().getIp(), connector.getOutbound().getPort()));
   LOGGER.info(
       "HUT simulator "
           + connector.getId()
           + " started at "
           + connector.getOutbound().getIp()
           + "@"
           + connector.getOutbound().getPort());
 }
  @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);
    }
  }
Exemple #9
0
  public static void main(String[] args) throws IOException {
    IoAcceptor acceptor = new NioSocketAcceptor();
    acceptor.getFilterChain().addLast("logger", new LoggingFilter());
    acceptor
        .getFilterChain()
        .addLast(
            "codec",
            new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); // 指定编码过滤器
    acceptor.setHandler(new TimeServerHandler()); // 指定业务逻辑处理器

    // 读写 通道均在3 秒内无任何操作就进入空闲状态
    acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 3);

    acceptor.setDefaultLocalAddress(new InetSocketAddress(PORT)); // 设置端口号
    acceptor.bind(); // 启动监听
  }
  public static void main(String[] args) throws IOException {

    IoAcceptor acceptor = new NioSocketAcceptor();

    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));
  }
 public MainSever() {
   IoAcceptor acceptor = new NioSocketAcceptor();
   LoggingFilter lf = new LoggingFilter("testLog");
   acceptor.getFilterChain().addLast("logger", lf);
   // 增加一个按行进行处理文本的编解码过滤器,并且指定按GBK的方法进行编解码
   acceptor
       .getFilterChain()
       .addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
   // 进行配置信息的设置
   acceptor.getSessionConfig().setReadBufferSize(2048 * 5000); // 发送缓冲区10M
   // acceptor.getSessionConfig().setReceiveBufferSize(2048*5000);
   // acceptor.getSessionConfig().setReadBufferSize(10);
   acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
   // 添加一个数据处理器,对接收或发送的数据进行处理
   acceptor.setHandler(new MainSeverHandler());
   // 把IoAccepter绑定到指定的8888端口
   try {
     acceptor.bind(new InetSocketAddress(PORT));
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   System.out.println("start server ...");
 }
 public Map<Long, IoSession> getManagedSessions() {
   return acceptor.getManagedSessions();
 }
 public void unbind() {
   acceptor.unbind();
 }
Exemple #14
0
 public void shutdown() {
   TimerManager.getInstance().stop();
   acceptor.unbind();
   System.out.println("Server offline.");
   System.exit(0); // BOEIEND :D
 }
 /**
  * Crea un nuevo acceptor para las conexiones entrantes por socket
  *
  * @return El aceptor creado para las conexioens entrantes
  */
 protected IoAcceptor newIoAcceptor() {
   final IoAcceptor ioAcceptor = componentsFactory.createIoAcceptor();
   final DefaultIoFilterChainBuilder filterChain = ioAcceptor.getFilterChain();
   configureFilterChain(filterChain);
   return ioAcceptor;
 }
Exemple #16
0
 /** Stop. */
 public void stop() {
   acceptor.unbind();
 }
 @Override
 protected void tearDown() throws Exception {
   acceptor.dispose();
   connector.dispose();
 }
Exemple #18
0
  @Override
  public void run() {
    Properties p = new Properties();
    try {
      p.load(new FileInputStream("moople.ini"));
    } catch (Exception e) {
      System.out.println("Please start create_server.bat");
      System.exit(0);
    }

    System.out.println("MoopleDEV v" + ServerConstants.VERSION + " starting up.\r\n");

    Runtime.getRuntime().addShutdownHook(new Thread(shutdown(false)));
    DatabaseConnection.getConnection();
    Connection c = DatabaseConnection.getConnection();
    try {
      PreparedStatement ps = c.prepareStatement("UPDATE accounts SET loggedin = 0");
      ps.executeUpdate();
      ps.close();
      ps = c.prepareStatement("UPDATE characters SET HasMerchant = 0");
      ps.executeUpdate();
      ps.close();
    } catch (SQLException sqle) {
    }
    IoBuffer.setUseDirectBuffer(false);
    IoBuffer.setAllocator(new SimpleBufferAllocator());
    acceptor = new NioSocketAcceptor();
    acceptor
        .getFilterChain()
        .addLast("codec", (IoFilter) new ProtocolCodecFilter(new MapleCodecFactory()));
    TimerManager tMan = TimerManager.getInstance();
    tMan.start();
    tMan.register(tMan.purge(), 300000); // Purging ftw...
    tMan.register(new RankingWorker(), ServerConstants.RANKING_INTERVAL);

    long timeToTake = System.currentTimeMillis();
    System.out.println("Loading Skills");
    SkillFactory.loadAllSkills();
    System.out.println(
        "Skills loaded in " + ((System.currentTimeMillis() - timeToTake) / 1000.0) + " seconds");

    timeToTake = System.currentTimeMillis();
    System.out.println("Loading Items");
    MapleItemInformationProvider.getInstance().getAllItems();

    CashItemFactory.getSpecialCashItems();
    System.out.println(
        "Items loaded in " + ((System.currentTimeMillis() - timeToTake) / 1000.0) + " seconds");
    try {
      for (int i = 0; i < Integer.parseInt(p.getProperty("worlds")); i++) {
        System.out.println("Starting world " + i);
        World world =
            new World(
                i,
                Integer.parseInt(p.getProperty("flag" + i)),
                p.getProperty("eventmessage" + i),
                Integer.parseInt(p.getProperty("exprate" + i)),
                Integer.parseInt(p.getProperty("droprate" + i)),
                Integer.parseInt(p.getProperty("mesorate" + i)),
                Integer.parseInt(p.getProperty("bossdroprate" + i))); // ohlol

        worldRecommendedList.add(new Pair<>(i, p.getProperty("whyamirecommended" + i)));
        worlds.add(world);
        channels.add(new LinkedHashMap<Integer, String>());
        for (int j = 0; j < Integer.parseInt(p.getProperty("channels" + i)); j++) {
          int channelid = j + 1;
          Channel channel = new Channel(i, channelid);
          world.addChannel(channel);
          channels.get(i).put(channelid, channel.getIP());
        }
        world.setServerMessage(p.getProperty("servermessage" + i));
        System.out.println("Finished loading world " + i + "\r\n");
      }
    } catch (Exception e) {
      System.out.println("Error in moople.ini, start CreateINI.bat to re-make the file.");
      e.printStackTrace(); // For those who get errors
      System.exit(0);
    }

    acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30);
    acceptor.setHandler(new MapleServerHandler());
    try {
      acceptor.bind(new InetSocketAddress(8484));
    } catch (IOException ex) {
    }

    System.out.println("Listening on port 8484\r\n\r\n");

    if (Boolean.parseBoolean(p.getProperty("gmserver"))) {
      GMServer.startGMServer();
    }
    System.out.println("Server is now online.");
    online = true;
  }
  @Test
  public void testDisconnectOnUnbind() throws Exception {
    IoAcceptor acceptor = EasyMock.createStrictMock(IoAcceptor.class);

    final IoServiceListenerSupport support = new IoServiceListenerSupport(acceptor);

    final DummySession session = new DummySession();
    session.setService(acceptor);
    session.setLocalAddress(ADDRESS);

    IoHandler handler = EasyMock.createStrictMock(IoHandler.class);
    session.setHandler(handler);

    final IoServiceListener listener = EasyMock.createStrictMock(IoServiceListener.class);

    // Activate a service and create a session.
    listener.serviceActivated(acceptor);
    listener.sessionCreated(session);
    handler.sessionCreated(session);
    handler.sessionOpened(session);

    EasyMock.replay(listener);
    EasyMock.replay(handler);

    support.add(listener);
    support.fireServiceActivated();
    support.fireSessionCreated(session);

    EasyMock.verify(listener);
    EasyMock.verify(handler);

    // Deactivate a service and make sure the session is closed & destroyed.
    EasyMock.reset(listener);
    EasyMock.reset(handler);

    listener.serviceDeactivated(acceptor);
    EasyMock.expect(acceptor.isCloseOnDeactivation()).andReturn(true);
    listener.sessionDestroyed(session);
    handler.sessionClosed(session);

    EasyMock.replay(listener);
    EasyMock.replay(acceptor);
    EasyMock.replay(handler);

    new Thread() {
      // Emulate I/O service
      @Override
      public void run() {
        try {
          Thread.sleep(500);
        } catch (InterruptedException e) {
          // e.printStackTrace();
        }
        // This synchronization block is a workaround for
        // the visibility problem of simultaneous EasyMock
        // state update. (not sure if it fixes the failing test yet.)
        synchronized (listener) {
          support.fireSessionDestroyed(session);
        }
      }
    }.start();
    support.fireServiceDeactivated();

    synchronized (listener) {
      EasyMock.verify(listener);
    }
    EasyMock.verify(acceptor);
    EasyMock.verify(handler);

    assertTrue(session.isClosing());
    assertEquals(0, support.getManagedSessions().size());
    assertNull(support.getManagedSessions().get(session.getId()));
  }