Ejemplo n.º 1
0
  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();
    }
  }
Ejemplo n.º 2
0
  protected void setupDatagramProtocol(String uri) {
    boolean minaLogger = configuration.isMinaLogger();
    boolean transferExchange = configuration.isTransferExchange();
    List<IoFilter> filters = configuration.getFilters();

    if (transferExchange) {
      throw new IllegalArgumentException(
          "transferExchange=true is not supported for datagram protocol");
    }

    address = new InetSocketAddress(configuration.getHost(), configuration.getPort());
    final int processorCount = Runtime.getRuntime().availableProcessors() + 1;
    connector = new NioDatagramConnector(processorCount);

    if (configuration.isOrderedThreadPoolExecutor()) {
      workerPool = new OrderedThreadPoolExecutor(configuration.getMaximumPoolSize());
    } else {
      workerPool = new UnorderedThreadPoolExecutor(configuration.getMaximumPoolSize());
    }
    connectorConfig = connector.getSessionConfig();
    connector.getFilterChain().addLast("threadPool", new ExecutorFilter(workerPool));
    if (minaLogger) {
      connector.getFilterChain().addLast("logger", new LoggingFilter());
    }
    appendIoFiltersToChain(filters, connector.getFilterChain());
    if (configuration.getSslContextParameters() != null) {
      LOG.warn(
          "Using datagram protocol, "
              + configuration.getProtocol()
              + ", but an SSLContextParameters instance was provided.  SSLContextParameters is only supported on the TCP protocol.");
    }
    configureDataGramCodecFactory("Mina2Producer", connector, configuration);
    // set connect timeout to mina in seconds
    connector.setConnectTimeoutMillis(timeout);
  }
Ejemplo n.º 3
0
 public void restart() {
   logger.warn("重新连接mina server");
   IoSession _session = session;
   IoConnector _connector = connector;
   session = null;
   connector = null;
   ok = false;
   if (_session != null) _session.close(false);
   if (_connector != null) _connector.dispose();
   init();
 }
Ejemplo n.º 4
0
  private void openConnection() {
    if (LOG.isDebugEnabled()) {
      LOG.debug(
          "Creating connector to address: {} using connector: {} timeout: {} millis.",
          new Object[] {address, connector, timeout});
    }
    // connect and wait until the connection is established
    if (connectorConfig != null) {
      connector.getSessionConfig().setAll(connectorConfig);
    }

    connector.setHandler(new ResponseHandler());
    ConnectFuture future = connector.connect(address);
    future.awaitUninterruptibly();
    session = future.getSession();
  }
Ejemplo n.º 5
0
 private void init() {
   connector = new NioSocketConnector();
   connector.setConnectTimeoutMillis(15000);
   connector.setHandler(this);
   JsonProtocalCodecFactory factory = new JsonProtocalCodecFactory(Charset.forName("UTF-8"));
   connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(factory));
   ConnectFuture connectFuture = connector.connect(new InetSocketAddress(host, port));
   connectFuture.awaitUninterruptibly(); // 同步,等待,直到连接完成
   if (connectFuture.isDone()) {
     if (!connectFuture.isConnected()) { // 若在指定时间内没连接成功,则抛出异常
       connector.dispose(); // 不关闭的话会运行一段时间后抛出,too many open
       connector = null;
     }
   }
   lastTime = System.currentTimeMillis();
 }
Ejemplo n.º 6
0
  private void closeConnection() {
    if (session != null) {
      CloseFuture closeFuture = session.close(true);
      closeFuture.awaitUninterruptibly();
    }

    connector.dispose(true);
  }
Ejemplo n.º 7
0
  // Implementation methods
  // -------------------------------------------------------------------------
  protected void setupVmProtocol(String uri) {
    boolean minaLogger = configuration.isMinaLogger();
    List<IoFilter> filters = configuration.getFilters();

    address = new VmPipeAddress(configuration.getPort());
    connector = new VmPipeConnector();

    // connector config
    if (minaLogger) {
      connector.getFilterChain().addLast("logger", new LoggingFilter());
    }
    appendIoFiltersToChain(filters, connector.getFilterChain());
    if (configuration.getSslContextParameters() != null) {
      LOG.warn(
          "Using vm protocol"
              + ", but an SSLContextParameters instance was provided.  SSLContextParameters is only supported on the TCP protocol.");
    }
    configureCodecFactory("Mina2Producer", connector);
  }
  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer();
    // TEARDOWN
    sb.append("TEARDOWN rtsp://192.168.14.14/ RTSP/1.0\r\n");
    sb.append("CSeq: 5\r\n");
    sb.append("Session: 1330505201\r\n");
    sb.append("Connection: close\r\n");
    sb.append("\r\n");

    logger.debug(sb.toString());

    IoConnector connector = new NioSocketConnector();
    connector.setConnectTimeoutMillis(30000);
    ProtocolCodecFilter myFilter = new ProtocolCodecFilter(new MessageCodecFactory());
    connector.getFilterChain().addLast("codec", myFilter);

    connector.setHandler(new ClientHandler(sb.toString()));

    connector.connect(new InetSocketAddress("192.168.14.14", 554));
  }
Ejemplo n.º 9
0
  protected void setupSocketProtocol(String uri) throws Exception {
    boolean minaLogger = configuration.isMinaLogger();
    long timeout = configuration.getTimeout();
    List<IoFilter> filters = configuration.getFilters();

    address = new InetSocketAddress(configuration.getHost(), configuration.getPort());

    final int processorCount = Runtime.getRuntime().availableProcessors() + 1;
    connector = new NioSocketConnector(processorCount);

    // connector config
    connectorConfig = connector.getSessionConfig();

    if (configuration.isOrderedThreadPoolExecutor()) {
      workerPool = new OrderedThreadPoolExecutor(configuration.getMaximumPoolSize());
    } else {
      workerPool = new UnorderedThreadPoolExecutor(configuration.getMaximumPoolSize());
    }
    connector.getFilterChain().addLast("threadPool", new ExecutorFilter(workerPool));
    if (minaLogger) {
      connector.getFilterChain().addLast("logger", new LoggingFilter());
    }
    appendIoFiltersToChain(filters, connector.getFilterChain());
    if (configuration.getSslContextParameters() != null) {
      connector
          .getFilterChain()
          .addFirst(
              "sslFilter",
              new SslFilter(
                  configuration.getSslContextParameters().createSSLContext(),
                  configuration.isAutoStartTls()));
    }
    configureCodecFactory("Mina2Producer", connector);
    connector.setConnectTimeoutMillis(timeout);
  }
Ejemplo n.º 10
0
  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer();
    // PAUSE
    sb.append("PLAY rtsp://192.168.14.14/NovelSupertv:BAAA0000000000018389 RTSP/1.0\r\n");
    sb.append("CSeq: 3\r\n");
    sb.append("Range: npt=beginning-\r\n");
    sb.append("Scale: 1.000000\r\n");
    sb.append("Session: 1330505200\r\n");
    sb.append("Require:com.comcase.ngod.r2\r\n");
    sb.append("User-Agent: Dilife 20090303\r\n");
    sb.append("\r\n");

    logger.debug(sb.toString());

    IoConnector connector = new NioSocketConnector();
    connector.setConnectTimeoutMillis(30000);
    ProtocolCodecFilter myFilter = new ProtocolCodecFilter(new MessageCodecFactory());
    connector.getFilterChain().addLast("codec", myFilter);

    connector.setHandler(new ClientHandler(sb.toString()));

    connector.connect(new InetSocketAddress("192.168.14.14", 554));
  }
Ejemplo n.º 11
0
  /** Close. */
  public void close() {
    if (selector != null) {
      selector.wakeup();
      try {
        selector.close();
      } catch (IOException e1) {
        log.warn("close selector fails", e1);
      } finally {
        selector = null;
      }
    }

    if (connector != null) {
      connector.dispose();
      connector = null;
    }
  }
Ejemplo n.º 12
0
  public static void main(String[] args) {
    // 创建一个非阻塞的客户端程序
    IoConnector connector = new NioSocketConnector();
    // 设置链接超时时间
    connector.setConnectTimeout(30000);
    // 设置过滤器
    connector
        .getFilterChain()
        .addLast(
            "codec",
            new ProtocolCodecFilter(
                new TextLineCodecFactory(
                    Charset.forName("UTF-8"),
                    LineDelimiter.WINDOWS.getValue(),
                    LineDelimiter.WINDOWS.getValue())));

    // 添加业务逻辑处理器类
    connector.setHandler(new Demo1ClientHandler());
    IoSession session = null;
    try {
      ConnectFuture future = connector.connect(new InetSocketAddress(HOST, PORT)); // 创建连接
      future.awaitUninterruptibly(); // 等待连接创建完成
      session = future.getSession(); // 获得session

      String sendPhone = "13681803609"; // 当前发送人的手机号码
      String receivePhone = "13721427169"; // 接收人手机号码
      String message = "测试发送短信,这个是短信信息哦,当然长度是有限制的哦....";
      String msg = sendPhone + ";" + receivePhone + ";" + message;

      session.write(msg); // 发送给移动服务端
    } catch (Exception e) {
      logger.error("客户端链接异常...", e);
    }

    session.getCloseFuture().awaitUninterruptibly(); // 等待连接断开
    connector.dispose();
  }
Ejemplo n.º 13
0
 public DefaultIoFilterChainBuilder getFilterChain() {
   return connector.getFilterChain();
 }
Ejemplo n.º 14
0
 @Override
 protected void tearDown() throws Exception {
   acceptor.dispose();
   connector.dispose();
 }
 /**
  * Crea un nuevo conector para la conexión saliente por socket
  *
  * @return El conector del nuevo socket
  */
 protected IoConnector newIoConnector() {
   final IoConnector ioConnector = componentsFactory.createIoConnector();
   final DefaultIoFilterChainBuilder filterChain = ioConnector.getFilterChain();
   configureFilterChain(filterChain);
   return ioConnector;
 }
Ejemplo n.º 16
0
  /** {@inheritDoc} */
  @SuppressWarnings("resource")
  @Override
  public void sessionCreated(IoSession session) throws Exception {

    boolean isClient = session.getRemoteAddress().equals(forward);

    if (log.isDebugEnabled()) {
      log.debug("Is downstream: " + isClient);
      session.getFilterChain().addFirst("protocol", new ProtocolCodecFilter(codecFactory));
    }

    session.getFilterChain().addFirst("proxy", new ProxyFilter(isClient ? "client" : "server"));

    if (true) {

      String fileName =
          System.currentTimeMillis()
              + '_'
              + forward.getHostName()
              + '_'
              + forward.getPort()
              + '_'
              + (isClient ? "DOWNSTREAM" : "UPSTREAM");

      File headersFile = loader.getResource(dumpTo + fileName + ".cap").getFile();
      headersFile.createNewFile();

      File rawFile = loader.getResource(dumpTo + fileName + ".raw").getFile();
      rawFile.createNewFile();

      FileOutputStream headersFos = new FileOutputStream(headersFile);
      WritableByteChannel headers = headersFos.getChannel();

      FileOutputStream rawFos = new FileOutputStream(rawFile);
      WritableByteChannel raw = rawFos.getChannel();

      IoBuffer header = IoBuffer.allocate(1);
      header.put((byte) (isClient ? 0x00 : 0x01));
      header.flip();
      headers.write(header.buf());

      session.getFilterChain().addFirst("dump", new NetworkDumpFilter(headers, raw));
    }

    // session.getFilterChain().addLast("logger", new LoggingFilter() );

    if (!isClient) {
      log.debug("Connecting..");
      IoConnector connector = new NioSocketConnector();
      connector.setHandler(this);
      ConnectFuture future = connector.connect(forward);
      future.awaitUninterruptibly(); // wait for connect, or timeout
      if (future.isConnected()) {
        if (log.isDebugEnabled()) {
          log.debug("Connected: {}", forward);
        }
        IoSession client = future.getSession();
        client.setAttribute(ProxyFilter.FORWARD_KEY, session);
        session.setAttribute(ProxyFilter.FORWARD_KEY, client);
      }
    }
    super.sessionCreated(session);
  }