Ejemplo n.º 1
0
  public static void main(String[] argv) throws Exception {
    Pipe[] pipes = new Pipe[PIPES_COUNT];
    Pipe pipe = Pipe.open();
    Pipe.SinkChannel sink = pipe.sink();
    Pipe.SourceChannel source = pipe.source();
    Selector sel = Selector.open();
    source.configureBlocking(false);
    source.register(sel, SelectionKey.OP_READ);

    for (int i = 0; i < PIPES_COUNT; i++) {
      pipes[i] = Pipe.open();
      Pipe.SourceChannel sc = pipes[i].source();
      sc.configureBlocking(false);
      sc.register(sel, SelectionKey.OP_READ);
      Pipe.SinkChannel sc2 = pipes[i].sink();
      sc2.configureBlocking(false);
      sc2.register(sel, SelectionKey.OP_WRITE);
    }

    for (int i = 0; i < LOOPS; i++) {
      sink.write(ByteBuffer.allocate(BUF_SIZE));
      int x = sel.selectNow();
      sel.selectedKeys().clear();
      source.read(ByteBuffer.allocate(BUF_SIZE));
    }

    for (int i = 0; i < PIPES_COUNT; i++) {
      pipes[i].sink().close();
      pipes[i].source().close();
    }
    pipe.sink().close();
    pipe.source().close();
    sel.close();
  }
Ejemplo n.º 2
0
 public PingClient() throws IOException {
   selector = Selector.open();
   Connector connector = new Connector();
   Printer printer = new Printer();
   connector.start();
   printer.start();
   receiveTarget();
 }
Ejemplo n.º 3
0
 void openIO() throws java.io.IOException {
   // create a new Selector for use below
   selector = Selector.open();
   if (settings.port() != 0) {
     // allocate an unbound server socket channel
     serverChannel = ServerSocketChannel.open();
     // set the (host,port) into the server channel will listen to
     serverChannel.socket().bind(new InetSocketAddress(settings.hostId(), settings.port()));
   }
 }
Ejemplo n.º 4
0
  private void prepareNioObjects() throws IOException {
    serverSocketChannel = ServerSocketChannel.open();
    selector = Selector.open();

    serverSocketChannel.configureBlocking(false);
    serverSocketChannel.socket().setReuseAddress(true);

    serverSocketChannel.bind(new InetSocketAddress(port));

    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
  }
Ejemplo n.º 5
0
  /*
   * CancelledKeyException is the failure symptom of 4729342
   * NOTE: The failure is timing dependent and is not always
   * seen immediately when the bug is present.
   */
  public static void main(String[] args) throws Exception {
    InetAddress lh = InetAddress.getLocalHost();
    isa = new InetSocketAddress(lh, TEST_PORT);
    selector = Selector.open();
    ssc = ServerSocketChannel.open();

    // Create and start a selector in a separate thread.
    new Thread(
            new Runnable() {
              public void run() {
                try {
                  ssc.configureBlocking(false);
                  ssc.socket().bind(isa);
                  sk = ssc.register(selector, SelectionKey.OP_ACCEPT);
                  selector.select();
                } catch (IOException e) {
                  System.err.println("error in selecting thread");
                  e.printStackTrace();
                }
              }
            })
        .start();

    // Wait for above thread to get to select() before we call close.
    Thread.sleep(3000);

    // Try to close. This should wakeup select.
    new Thread(
            new Runnable() {
              public void run() {
                try {
                  SocketChannel sc = SocketChannel.open();
                  sc.connect(isa);
                  ssc.close();
                  sk.cancel();
                  sc.close();
                } catch (IOException e) {
                  System.err.println("error in closing thread");
                  System.err.println(e);
                }
              }
            })
        .start();

    // Wait for select() to be awakened, which should be done by close.
    Thread.sleep(3000);

    selector.wakeup();
    selector.close();
  }
Ejemplo n.º 6
0
  public Overlord() {
    try {
      selector = Selector.open();
      queue = new ConcurrentLinkedQueue<Communicator>();

      // open the pipe and register it with our selector
      pipe = Pipe.open();
      pipe.sink().configureBlocking(false);
      pipe.source().configureBlocking(false);
      pipe.source().register(selector, SelectionKey.OP_READ);
    } catch (IOException e) {
      throw new RuntimeException("select() failed");
    }
  }
Ejemplo n.º 7
0
  static void test() throws Exception {
    ServerSocketChannel ssc = null;
    SocketChannel sc = null;
    SocketChannel peer = null;
    try {
      ssc = ServerSocketChannel.open().bind(new InetSocketAddress(0));

      // loopback connection
      InetAddress lh = InetAddress.getLocalHost();
      sc = SocketChannel.open(new InetSocketAddress(lh, ssc.socket().getLocalPort()));
      peer = ssc.accept();

      // peer sends message so that "sc" will be readable
      int n = peer.write(ByteBuffer.wrap("Hello".getBytes()));
      assert n > 0;

      sc.configureBlocking(false);

      Selector selector = Selector.open();
      SelectionKey key = sc.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);

      boolean done = false;
      int failCount = 0;
      while (!done) {
        int nSelected = selector.select();
        if (nSelected > 0) {
          if (nSelected > 1) throw new RuntimeException("More than one channel selected");
          Set<SelectionKey> keys = selector.selectedKeys();
          Iterator<SelectionKey> iterator = keys.iterator();
          while (iterator.hasNext()) {
            key = iterator.next();
            iterator.remove();
            if (key.isWritable()) {
              failCount++;
              if (failCount > 10) throw new RuntimeException("Test failed");
              Thread.sleep(250);
            }
            if (key.isReadable()) {
              done = true;
            }
          }
        }
      }
    } finally {
      if (peer != null) peer.close();
      if (sc != null) sc.close();
      if (ssc != null) ssc.close();
    }
  }
Ejemplo n.º 8
0
 public static void main(String[] args) throws Exception {
   SocketChannel sc = SocketChannel.open();
   Selector sel = Selector.open();
   if (sc.keyFor(sel) != null) throw new Exception("keyFor != null");
   sc.configureBlocking(false);
   SelectionKey sk = sc.register(sel, SelectionKey.OP_READ, args);
   if (sc.keyFor(sel) != sk) throw new Exception("keyFor returned " + sc.keyFor(sel));
   if (sk.attachment() != args) throw new Exception("attachment() returned " + sk.attachment());
   Trivial t = new Trivial();
   sk.attach(t);
   if (sk.attachment() != t) throw new Exception("Wrong attachment");
   sk.isReadable();
   sk.isWritable();
   sk.isConnectable();
   sk.isAcceptable();
 }
Ejemplo n.º 9
0
 public static Devolucion seleccionarDevolucion(
     final Cliente c, final EventList<Devolucion> devos) {
   final Selector<Devolucion> selector =
       new AbstractSelector<Devolucion>(
           devos,
           "Devoluciones",
           "Lista de devoluciones pendientes",
           MessageFormat.format("{0} ({1})", c.getNombre(), c.getClave())) {
         @Override
         protected TableFormat<Devolucion> getTableFormat() {
           return CXCTableFormats.getDevolucionTF();
         }
       };
   selector.open();
   if (!selector.hasBeenCanceled()) {
     return selector.getSelected();
   }
   return null;
 }
Ejemplo n.º 10
0
  /**
   * Presenta un selector adecuado para seleccionar una {@link Venta} misma que regresa
   *
   * @param c
   * @param notas
   * @return
   */
  public static Venta seleccionarVentaCredito(final Cliente c, final EventList<Venta> ventas) {
    final Selector<Venta> selector =
        new AbstractSelector<Venta>(
            ventas,
            "Lista de venas",
            "Ventas a credito pendientes de pago",
            MessageFormat.format("{0} ({1})", c.getNombre(), c.getClave())) {

          @Override
          protected TableFormat<Venta> getTableFormat() {
            return CXCTableFormats.getVentasCreTF();
          }
        };
    selector.open();
    if (!selector.hasBeenCanceled()) {
      return selector.getSelected();
    }
    return null;
  }
Ejemplo n.º 11
0
  /**
   * Presenta un selector adecuado para seleccionar una {@link NotaDeCredito} misma que regresa
   *
   * @param c
   * @param notas
   * @return
   */
  public static NotaDeCredito seleccionarNotaDeCredito(
      final Cliente c, final EventList<NotaDeCredito> notas) {
    final Selector<NotaDeCredito> selector =
        new AbstractSelector<NotaDeCredito>(
            notas,
            "Notas de Crédito",
            "Disponibles para pago",
            MessageFormat.format("{0} ({1})", c.getNombre(), c.getClave())) {

          @Override
          protected TableFormat<NotaDeCredito> getTableFormat() {
            return CXCTableFormats.getNotaDeCreditoTF();
          }
        };
    selector.open();
    if (!selector.hasBeenCanceled()) {
      return selector.getSelected();
    }
    return null;
  }
Ejemplo n.º 12
0
 public static void startRDPServer() {
   if (rdpServerStarted) return;
   rdpServerStarted = true;
   rdpServerThread = new Thread(rdpServer, "RDPServer");
   retryThread = new Thread(new RetryThread(), "RDPRetry");
   packetCallbackThread = new Thread(new PacketCallbackThread(), "RDPCallback");
   if (Log.loggingNet) Log.net("static - starting rdpserver thread");
   try {
     selector = Selector.open();
   } catch (Exception e) {
     Log.exception("RDPServer caught exception opening selector", e);
     System.exit(1);
   }
   rdpServerThread.setPriority(rdpServerThread.getPriority() + 2);
   if (Log.loggingDebug)
     Log.debug(
         "RDPServer: starting rdpServerThread with priority " + rdpServerThread.getPriority());
   rdpServerThread.start();
   retryThread.start();
   packetCallbackThread.start();
 }
Ejemplo n.º 13
0
  public static void main(String[] args) {
    port[0] = -1;

    try {
      reader = new BufferedReader(new InputStreamReader(System.in));
      clients = new LinkedHashMap<String, SocketChannel>();
      selector = Selector.open();
      List<SocketChannel> anonymousClients = new ArrayList<SocketChannel>();

      serverSocket = ServerSocketChannel.open();
      serverSocket.configureBlocking(false);

      while (true) {
        readCommand();
        checkClients(anonymousClients);
      }

    } catch (Exception expt) {
      Utils.printErrorAndExit("Error: " + expt.getMessage());
    }
  }
    public ServerThread() throws IOException {
      setName("DefaultTCPTransportMapping_" + getAddress());
      buf = new byte[getMaxInboundMessageSize()];
      // Selector for incoming requests
      selector = Selector.open();

      if (serverEnabled) {
        // Create a new server socket and set to non blocking mode
        ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);

        // Bind the server socket
        InetSocketAddress isa =
            new InetSocketAddress(tcpAddress.getInetAddress(), tcpAddress.getPort());
        ssc.socket().bind(isa);
        // Register accepts on the server socket with the selector. This
        // step tells the selector that the socket wants to be put on the
        // ready list when accept operations occur, so allowing multiplexed
        // non-blocking I/O to take place.
        ssc.register(selector, SelectionKey.OP_ACCEPT);
      }
    }
Ejemplo n.º 15
0
  public void run() {
    try {
      mySelector = Selector.open();
      bRunReactor = true;
    } catch (IOException e) {
      throw new RuntimeException("Could not open selector", e);
    }

    while (bRunReactor) {
      runLoopbreaks();
      if (!bRunReactor) break;

      runTimers();
      if (!bRunReactor) break;

      removeUnboundConnections();
      checkIO();
      addNewConnections();
      processIO();
    }

    close();
  }
Ejemplo n.º 16
0
  public void init() throws IOException {
    this._logger = LoggerFactory.getLogger(AcquirePort.class);
    selector = Selector.open();
    // 通过open方法来打开一个未绑定的ServerSocketChannel实例
    ServerSocketChannel server = ServerSocketChannel.open();
    InetSocketAddress isa = new InetSocketAddress(_acquirePort);
    // 将该ServerSocketChannel绑定到指定IP地址
    server.socket().bind(isa);
    // 设置ServerSocket以非阻塞方式工作
    server.configureBlocking(false);
    // 将server注册到指定Selector对象
    server.register(selector, SelectionKey.OP_ACCEPT);
    // 定义准备执行读取数据的ByteBuffer
    ByteBuffer buff = ByteBuffer.allocate(1024);
    while (selector.select() > 0) {
      // 依次处理selector上的每个已选择的SelectionKey
      Set<SelectionKey> sks = selector.selectedKeys();
      Iterator keys = sks.iterator();
      while (keys.hasNext()) {
        SelectionKey sk = (SelectionKey) keys.next();
        // 从selector上的已选择Key集中删除正在处理的SelectionKey
        keys.remove();
        // 如果sk对应的通道包含客户端的连接请求
        if (sk.isAcceptable()) {
          // 调用accept方法接受连接,产生服务器端对应的SocketChannel
          SocketChannel sc = server.accept();
          // 设置采用非阻塞模式
          sc.configureBlocking(false);
          // 将该SocketChannel也注册到selector
          sc.register(selector, SelectionKey.OP_READ);
        }
        // 如果sk对应的通道有数据需要读取
        if (sk.isReadable()) {
          // 获取该SelectionKey对应的Channel,该Channel中有可读的数据
          SocketChannel sc = (SocketChannel) sk.channel();
          // 开始读取数据

          try {
            while (sc.read(buff) > 0) {
              buff.flip();
              this._logger.info("content" + buff);
              sc.write(buff);
              if (buff.hasRemaining()) {
                buff.compact();
              } else {
                buff.clear();
              }
            }
            // 打印从该sk对应的Channel里读取到的数据
            this._logger.info("accpect content" + buff);
          }
          // 如果捕捉到该sk对应的Channel出现了异常,即表明该Channel
          // 对应的Client出现了问题,所以从Selector中取消sk的注册
          catch (IOException ex) {
            // 从Selector中删除指定的SelectionKey
            sk.cancel();
            if (sk.channel() != null) {
              sk.channel().close();
            }
          }
        }
      }
    }
  }
Ejemplo n.º 17
0
  /** {@inheritDoc} */
  @Override
  public void initializeConnectionHandler(LDAPConnectionHandlerCfg config)
      throws ConfigException, InitializationException {
    if (friendlyName == null) {
      friendlyName = config.dn().rdn().getAttributeValue(0).toString();
    }

    // Open the selector.
    try {
      selector = Selector.open();
    } catch (Exception e) {
      logger.traceException(e);

      LocalizableMessage message =
          ERR_LDAP_CONNHANDLER_OPEN_SELECTOR_FAILED.get(
              config.dn(), stackTraceToSingleLineString(e));
      throw new InitializationException(message, e);
    }

    // Save this configuration for future reference.
    currentConfig = config;
    enabled = config.isEnabled();
    requestHandlerIndex = 0;
    allowedClients = config.getAllowedClient();
    deniedClients = config.getDeniedClient();

    // Configure SSL if needed.
    try {
      // This call may disable the connector if wrong SSL settings
      configureSSL(config);
    } catch (DirectoryException e) {
      logger.traceException(e);
      throw new InitializationException(e.getMessageObject());
    }

    // Save properties that cannot be dynamically modified.
    allowReuseAddress = config.isAllowTCPReuseAddress();
    backlog = config.getAcceptBacklog();
    listenAddresses = config.getListenAddress();
    listenPort = config.getListenPort();
    numRequestHandlers = getNumRequestHandlers(config.getNumRequestHandlers(), friendlyName);

    // Construct a unique name for this connection handler, and put
    // together the set of listeners.
    listeners = new LinkedList<>();
    StringBuilder nameBuffer = new StringBuilder();
    nameBuffer.append(friendlyName);
    for (InetAddress a : listenAddresses) {
      listeners.add(new HostPort(a.getHostAddress(), listenPort));
      nameBuffer.append(" ");
      nameBuffer.append(a.getHostAddress());
    }
    nameBuffer.append(" port ");
    nameBuffer.append(listenPort);
    handlerName = nameBuffer.toString();

    // Attempt to bind to the listen port on all configured addresses to
    // verify whether the connection handler will be able to start.
    LocalizableMessage errorMessage =
        checkAnyListenAddressInUse(listenAddresses, listenPort, allowReuseAddress, config.dn());
    if (errorMessage != null) {
      logger.error(errorMessage);
      throw new InitializationException(errorMessage);
    }

    // Create a system property to store the LDAP(S) port the server is
    // listening to. This information can be displayed with jinfo.
    System.setProperty(protocol + "_port", String.valueOf(listenPort));

    // Create and start a connection finalizer thread for this
    // connection handler.
    connectionFinalizer =
        Executors.newSingleThreadScheduledExecutor(
            new DirectoryThread.Factory(
                "LDAP Connection Finalizer for connection handler " + toString()));

    connectionFinalizerActiveJobQueue = new ArrayList<>();
    connectionFinalizerPendingJobQueue = new ArrayList<>();

    connectionFinalizer.scheduleWithFixedDelay(
        new ConnectionFinalizerRunnable(), 100, 100, TimeUnit.MILLISECONDS);

    // Create and start the request handlers.
    requestHandlers = new LDAPRequestHandler[numRequestHandlers];
    for (int i = 0; i < numRequestHandlers; i++) {
      requestHandlers[i] = new LDAPRequestHandler(this, i);
    }

    for (int i = 0; i < numRequestHandlers; i++) {
      requestHandlers[i].start();
    }

    // Register the set of supported LDAP versions.
    DirectoryServer.registerSupportedLDAPVersion(3, this);
    if (config.isAllowLDAPV2()) {
      DirectoryServer.registerSupportedLDAPVersion(2, this);
    }

    // Create and register monitors.
    statTracker = new LDAPStatistics(handlerName + " Statistics");
    DirectoryServer.registerMonitorProvider(statTracker);

    connMonitor = new ClientConnectionMonitorProvider(this);
    DirectoryServer.registerMonitorProvider(connMonitor);

    // Register this as a change listener.
    config.addLDAPChangeListener(this);
  }
Ejemplo n.º 18
0
  private void go() throws IOException {
    // Create a new selector
    Selector selector = Selector.open();

    // Open a listener on each port, and register each one
    // with the selector
    for (int i = 0; i < ports.length; ++i) {
      ServerSocketChannel ssc = ServerSocketChannel.open();
      ssc.configureBlocking(false);
      ServerSocket ss = ssc.socket();
      InetSocketAddress address = new InetSocketAddress(ports[i]);
      ss.bind(address);

      SelectionKey key = ssc.register(selector, SelectionKey.OP_ACCEPT);

      System.out.println("Going to listen on " + ports[i]);
    }

    while (true) {
      int num = selector.select();

      Set selectedKeys = selector.selectedKeys();
      Iterator it = selectedKeys.iterator();

      while (it.hasNext()) {
        SelectionKey key = (SelectionKey) it.next();

        if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
          // Accept the new connection
          ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
          SocketChannel sc = ssc.accept();
          sc.configureBlocking(false);

          // Add the new connection to the selector
          SelectionKey newKey = sc.register(selector, SelectionKey.OP_READ);
          it.remove();

          System.out.println("Got connection from " + sc);
        } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
          // Read the data
          SocketChannel sc = (SocketChannel) key.channel();

          // Echo data
          int bytesEchoed = 0;
          while (true) {
            echoBuffer.clear();

            int r = sc.read(echoBuffer);

            if (r <= 0) {
              break;
            }

            echoBuffer.flip();

            sc.write(echoBuffer);
            bytesEchoed += r;
          }

          System.out.println("Echoed " + bytesEchoed + " from " + sc);

          it.remove();
        }
      }

      // System.out.println( "going to clear" );
      //      selectedKeys.clear();
      // System.out.println( "cleared" );
    }
  }
Ejemplo n.º 19
0
 Dispatcher1() throws IOException {
   sel = Selector.open();
 }
Ejemplo n.º 20
0
 public ChannelRouter(ExceptionListener<IOException> exceptionListener) throws IOException {
   this.exceptionListener = exceptionListener;
   this.outputBuffers = new ConcurrentHashMap<SelectableChannel, ByteBuffer>();
   this.outputs = new ConcurrentHashMap<SelectableChannel, SelectableChannel>();
   this.selector = Selector.open();
 }
Ejemplo n.º 21
0
 Connector(Printer pr) throws IOException {
   printer = pr;
   sel = Selector.open();
   setName("Connector");
 }