private static void startSender() {
   Thread t =
       new Thread() {
         public void run() {
           try {
             DatagramChannel channel = DatagramChannel.open();
             channel.configureBlocking(false);
             // channel.socket().connect(new InetSocketAddress(InetAddress.getLocalHost(), 1000));
             ByteBuffer buffer = ByteBuffer.allocate(512 * 1000);
             byte[] buf;
             long time = JGN.getNanoTime();
             for (int i = 0; i < 1000; i++) {
               ByteArrayOutputStream baos = new ByteArrayOutputStream();
               DataOutputStream dos = new DataOutputStream(baos);
               byte[] textBytes = ("Testing " + (i + 1)).getBytes();
               dos.writeInt(textBytes.length);
               dos.write(textBytes);
               buf = baos.toByteArray();
               baos.close();
               buffer.clear();
               buffer.put(buf);
               buffer.flip();
               // channel.write(buffer);
               channel.send(buffer, new InetSocketAddress(InetAddress.getLocalHost(), 1000));
               Thread.sleep(5);
             }
             System.out.println("Took " + ((JGN.getNanoTime() - time) / 1000000) + "ms to send.");
           } catch (Throwable t) {
             t.printStackTrace();
           }
         }
       };
   t.start();
 }
Example #2
0
  // Test the connected case to see if PUE is thrown
  public static void test2() throws Exception {

    setup();
    server.configureBlocking(true);
    server.connect(isa);
    server.configureBlocking(false);
    outBuf.rewind();
    server.write(outBuf);
    server.receive(inBuf);

    client.close();
    Thread.sleep(2000);
    outBuf.rewind();

    try {
      server.write(outBuf);
      Thread.sleep(2000);
      inBuf.clear();
      server.read(inBuf);
      if (onSolarisOrLinux()) throw new Exception("Expected PUE not thrown");
    } catch (PortUnreachableException pue) {
      System.err.println("received PUE");
    }
    server.close();
  }
Example #3
0
 void start() {
   logger.log(Level.FINEST, "Starting TCP node");
   please_stop = false;
   node_thread = new SelectThread();
   node_thread.setDaemon(true);
   node_thread.start();
   logger.log(Level.FINEST, "Started TCP node");
 }
Example #4
0
  /** Start the network listening thread. */
  void start() {
    this.running = true;

    Thread thread = new Thread(this, "IceConnector@" + hashCode());

    thread.setDaemon(true);
    thread.start();
  }
Example #5
0
 public static void main(String[] args) throws Exception {
   TypeServer ts = new TypeServer();
   ts.port = Integer.parseInt(args[0]);
   Thread t = new Thread(ts);
   t.start();
   System.out.println("Type server ready...Type CTRL-D to exit");
   while (System.in.read() > 0) ;
   ts.stopServer();
   t.join();
 }
 private static void startReceiver() {
   Thread t =
       new Thread() {
         public void run() {
           try {
             DatagramChannel server = DatagramChannel.open();
             server.configureBlocking(false);
             server.socket().bind(new InetSocketAddress(InetAddress.getLocalHost(), 1000));
             // Selector selector = Selector.open();
             // server.register(selector, SelectionKey.OP_READ);
             ByteBuffer buffer = ByteBuffer.allocate(512 * 1000);
             byte[] buf = new byte[512 * 1000];
             long time = 0;
             while (true) {
               Thread.sleep(1);
               SocketAddress address = server.receive(buffer);
               if (address != null) {
                 int len = buffer.position();
                 buffer.rewind();
                 buffer.get(buf, 0, len);
                 buffer.clear();
                 ByteArrayInputStream bais = new ByteArrayInputStream(buf, 0, len);
                 DataInputStream dis = new DataInputStream(bais);
                 int bytesLength;
                 byte[] bytes;
                 int packets = 0;
                 try {
                   while ((bytesLength = dis.readInt()) > -1) {
                     dis.read(bytes = new byte[bytesLength]);
                     packets++;
                     String s = new String(bytes);
                     if (s.equals("Testing 1000")) {
                       System.out.println(
                           "Took "
                               + ((JGN.getNanoTime() - time) / 1000000)
                               + "ms to receive "
                               + packets
                               + " packets.");
                       System.exit(0);
                     }
                   }
                 } catch (EOFException exc) {
                   // System.out.println("End of stream reached!");
                 }
                 bais.close();
               }
             }
           } catch (Throwable t) {
             t.printStackTrace();
           }
         }
       };
   t.start();
 }
  /*
   * 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();
  }
    /** {@inheritDoc} */
    @Override
    protected void body() throws InterruptedException, IgniteInterruptedCheckedException {
      if (log.isDebugEnabled()) log.debug("GC worker started.");

      File workTokDir = tokDir.getParentFile();

      assert workTokDir != null;

      boolean lastRunNeeded = true;

      while (true) {
        try {
          // Sleep only if not cancelled.
          if (lastRunNeeded) Thread.sleep(GC_FREQ);
        } catch (InterruptedException ignored) {
          // No-op.
        }

        if (log.isDebugEnabled()) log.debug("Starting GC iteration.");

        cleanupResources(workTokDir);

        // Process spaces created by this endpoint.
        if (log.isDebugEnabled()) log.debug("Processing local spaces.");

        for (IpcSharedMemoryClientEndpoint e : endpoints) {
          if (log.isDebugEnabled()) log.debug("Processing endpoint: " + e);

          if (!e.checkOtherPartyAlive()) {
            endpoints.remove(e);

            if (log.isDebugEnabled()) log.debug("Removed endpoint: " + e);
          }
        }

        if (isCancelled()) {
          if (lastRunNeeded) {
            lastRunNeeded = false;

            // Clear interrupted status.
            Thread.interrupted();
          } else {
            Thread.currentThread().interrupt();

            break;
          }
        }
      }
    }
    /** @param workTokDir Token directory (common for multiple nodes). */
    private void cleanupResources(File workTokDir) {
      RandomAccessFile lockFile = null;

      FileLock lock = null;

      try {
        lockFile = new RandomAccessFile(new File(workTokDir, LOCK_FILE_NAME), "rw");

        lock = lockFile.getChannel().lock();

        if (lock != null) processTokenDirectory(workTokDir);
        else if (log.isDebugEnabled())
          log.debug(
              "Token directory is being processed concurrently: " + workTokDir.getAbsolutePath());
      } catch (OverlappingFileLockException ignored) {
        if (log.isDebugEnabled())
          log.debug(
              "Token directory is being processed concurrently: " + workTokDir.getAbsolutePath());
      } catch (FileLockInterruptionException ignored) {
        Thread.currentThread().interrupt();
      } catch (IOException e) {
        U.error(log, "Failed to process directory: " + workTokDir.getAbsolutePath(), e);
      } finally {
        U.releaseQuiet(lock);
        U.closeQuiet(lockFile);
      }
    }
Example #10
0
  @Override
  public void run() {
    try {
      while (true) {
        this.selector.select(SELECT_MILLISECONDS);
        if (Thread.interrupted()) break;

        Iterator<SelectionKey> i = this.selector.selectedKeys().iterator();
        while (i.hasNext()) {
          SelectionKey key = i.next();
          SelectableChannel channel = key.channel();
          handleReadableChannel(key, channel);
          handleWritableChannel(key, channel);
          i.remove();
        }
      }
    } catch (ClosedByInterruptException e) {
      // User-requested interrupt, so clean up
    } catch (IOException e) {
      reportIOException(e);
    }

    for (Map.Entry<SelectableChannel, SelectableChannel> e : this.outputs.entrySet()) {
      closeChannelAndReportException(e.getKey());
      closeChannelAndReportException(e.getValue());
    }

    for (SelectableChannel c : this.outputBuffers.keySet()) closeChannelAndReportException(c);
  }
Example #11
0
 void startServer(boolean newThread) throws Exception {
   if (newThread) {
     serverThread =
         new Thread() {
           public void run() {
             try {
               doServerSide();
             } catch (Exception e) {
               /*
                * Our server thread just died.
                *
                * Release the client, if not active already...
                */
               System.err.println("Server died...");
               System.err.println(e);
               serverReady = true;
               serverException = e;
             }
           }
         };
     serverThread.start();
   } else {
     doServerSide();
   }
 }
Example #12
0
  /*
   * Define the client side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doClientSide() throws Exception {
    // create SSLEngine.
    SSLEngine ssle = createSSLEngine(true);

    /*
     * Wait for server to get started.
     */
    while (!serverReady) {
      Thread.sleep(50);
    }

    // Create a non-blocking socket channel.
    SocketChannel sc = SocketChannel.open();
    sc.configureBlocking(false);
    InetSocketAddress isa = new InetSocketAddress(InetAddress.getLocalHost(), serverPort);
    sc.connect(isa);

    // Complete connection.
    while (!sc.finishConnect()) {
      // waiting for the connection completed.
    }

    // handshaking
    handshaking(ssle, sc, null);

    // send out application data
    deliver(ssle, sc);

    // receive application data
    receive(ssle, sc);

    // close the socket channel.
    sc.close();
  }
    /** blocks until connected */
    @Override
    SelectableChannel doConnect() throws IOException, InterruptedException {
      boolean success = false;
      final SocketChannel socketChannel = SocketChannel.open();
      try {
        socketChannel.configureBlocking(false);
        socketChannel.socket().setReuseAddress(true);
        socketChannel.socket().setSoLinger(false, 0);
        socketChannel.socket().setSoTimeout(0);
        socketChannel.socket().setTcpNoDelay(true);

        try {
          socketChannel.connect(details.address());
        } catch (UnresolvedAddressException e) {
          this.connectLater();
        }

        // Under experiment, the concoction was found to be more successful if we
        // paused before registering the OP_CONNECT
        Thread.sleep(10);

        // the registration has be be run on the same thread as the selector
        addPendingRegistration(
            new Runnable() {
              @Override
              public void run() {

                final Attached attached = new Attached();
                attached.connector = ClientConnector.this;

                try {
                  socketChannel.register(selector, OP_CONNECT, attached);
                } catch (ClosedChannelException e) {
                  if (socketChannel.isOpen()) LOG.error("", e);
                }
              }
            });

        selector.wakeup();
        success = true;
        return socketChannel;

      } finally {
        if (!success) {
          try {
            try {
              socketChannel.socket().close();
            } catch (Exception e) {
              LOG.error("", e);
            }
            socketChannel.close();
          } catch (IOException e) {
            LOG.error("", e);
          }
        }
      }
    }
 /**
  * Marks the end of an I/O operation that might block indefinitely.
  *
  * <p>This method should be invoked in tandem with the {@link #begin begin} method, using a
  * <tt>try</tt>&nbsp;...&nbsp;<tt>finally</tt> block as shown <a href="#be">above</a>, in order to
  * implement asynchronous closing and interruption for this channel.
  *
  * @param completed <tt>true</tt> if, and only if, the I/O operation completed successfully, that
  *     is, had some effect that would be visible to the operation's invoker
  * @throws AsynchronousCloseException If the channel was asynchronously closed
  * @throws ClosedByInterruptException If the thread blocked in the I/O operation was interrupted
  */
 protected final void end(boolean completed) throws AsynchronousCloseException {
   blockedOn(null);
   Thread interrupted = this.interrupted;
   if (interrupted != null && interrupted == Thread.currentThread()) {
     interrupted = null;
     throw new ClosedByInterruptException();
   }
   if (!completed && !open) throw new AsynchronousCloseException();
 }
Example #15
0
 void join() {
   logger.log(Level.FINEST, "Joining selector thread");
   try {
     node_thread.join();
   } catch (java.lang.InterruptedException ex) {
   }
   node_thread = null;
   logger.log(Level.FINEST, "Selector thread joined");
 }
 /**
  * @param log Logger.
  * @param time Time.
  * @param msg Message.
  */
 private static void log0(@Nullable IgniteLogger log, long time, String msg) {
   if (log != null) {
     if (log.isDebugEnabled()) log.debug(msg);
     else log.warning(msg);
   } else
     X.println(
         String.format(
             "[%s][%s]%s",
             DEBUG_DATE_FMT.get().format(time), Thread.currentThread().getName(), msg));
 }
Example #17
0
  public ShowComp() throws InterruptedException, IOException {
    super("CONNECTED COMPUTERS");
    int x = 0, d = 20;
    mb = new JMenuBar();
    File = new JMenu("File");
    mb.add(File);
    exit = new JMenuItem("Exit");
    exit.addActionListener(this);
    File.add(exit);
    ta = new JTextArea();
    ta.setBounds(20, 30, 315, 470);
    ta.setEditable(false);
    add(ta);

    setJMenuBar(mb);

    sel = new JLabel("The connected computers are..");
    sel.setBounds(15, 5, 300, 30);
    add(sel);
    b1 = new JButton("<< BACK");
    b1.setBounds(140, 510, 100, 30);
    b1.setToolTipText("Back to main page");
    b1.addActionListener(this);
    add(b1);
    setLayout(null);
    while (x < 360) {
      x = x + d;
      setBounds(675, 50, x, 600);
      this.show();
    }
    // setVisible(true);
    String s = "192.168.0.", temp = null;
    Printer printer = new Printer();
    printer.start();
    Connector connector = new Connector(printer);
    connector.start();

    LinkedList targets = new LinkedList();
    for (int i = 1; i <= 255; i++) {
      temp = s + Integer.toString(i);
      Target t = new Target(temp);
      targets.add(t);
      connector.add(t);
    }
    Thread.sleep(2000);
    connector.shutdown();
    connector.join();

    for (Iterator i = targets.iterator(); i.hasNext(); ) {
      Target t = (Target) i.next();
      if (!t.shown) t.show();
    }

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
  }
 /**
  * Marks the beginning of an I/O operation that might block indefinitely.
  *
  * <p>This method should be invoked in tandem with the {@link #end end} method, using a
  * <tt>try</tt>&nbsp;...&nbsp;<tt>finally</tt> block as shown <a href="#be">above</a>, in order to
  * implement asynchronous closing and interruption for this channel.
  */
 protected final void begin() {
   if (interruptor == null) {
     interruptor =
         new Interruptible() {
           public void interrupt(Thread target) {
             synchronized (closeLock) {
               if (!open) return;
               open = false;
               interrupted = target;
               try {
                 AbstractInterruptibleChannel.this.implCloseChannel();
               } catch (IOException x) {
               }
             }
           }
         };
   }
   blockedOn(interruptor);
   Thread me = Thread.currentThread();
   if (me.isInterrupted()) interruptor.interrupt(me);
 }
  /** {@inheritDoc} */
  @Override
  public void close() {
    closed = true;

    U.closeQuiet(srvSock);

    if (gcWorker != null) {
      U.cancel(gcWorker);

      // This method may be called from already interrupted thread.
      // Need to ensure cleaning on close.
      boolean interrupted = Thread.interrupted();

      try {
        U.join(gcWorker);
      } catch (IgniteInterruptedCheckedException e) {
        U.warn(log, "Interrupted when stopping GC worker.", e);
      } finally {
        if (interrupted) Thread.currentThread().interrupt();
      }
    }
  }
Example #20
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();
    }
  }
Example #21
0
  /*
   * Primary constructor, used to drive remainder of the test.
   *
   * Fork off the other side, then do your work.
   */
  LargePacket() throws Exception {
    super("../../../../../etc");

    if (separateServerThread) {
      startServer(true);
      startClient(false);
    } else {
      startClient(true);
      startServer(false);
    }

    /*
     * Wait for other side to close down.
     */
    if (separateServerThread) {
      serverThread.join();
    } else {
      clientThread.join();
    }

    /*
     * When we get here, the test is pretty much over.
     *
     * If the main thread excepted, that propagates back
     * immediately.  If the other thread threw an exception, we
     * should report back.
     */
    if (serverException != null) {
      System.out.print("Server Exception:");
      throw serverException;
    }
    if (clientException != null) {
      System.out.print("Client Exception:");
      throw clientException;
    }
  }
  public static void main(String args[]) throws Exception {
    final int ENOUGH_SIZE = 1024;
    final int SMALL_SIZE = 4;

    boolean isBlocked = true;
    int size = ENOUGH_SIZE;

    if (args.length > 0) {
      int opt = Integer.parseInt(args[0]);
      switch (opt) {
        case 1:
          isBlocked = true;
          size = ENOUGH_SIZE;
          break;
        case 2:
          isBlocked = true;
          size = SMALL_SIZE;
          break;
        case 3:
          isBlocked = false;
          size = ENOUGH_SIZE;
          break;
        case 4:
          isBlocked = false;
          size = SMALL_SIZE;
          break;
      }
    }

    DatagramChannel channel = DatagramChannel.open();
    channel.configureBlocking(isBlocked);
    ByteBuffer buffer = ByteBuffer.allocate(size);
    DatagramSocket socket = channel.socket();
    SocketAddress localAddr = new InetSocketAddress(8000);
    socket.bind(localAddr);

    while (true) {
      System.out.println("开始接收数据报");
      SocketAddress remoteAddr = channel.receive(buffer);
      if (remoteAddr == null) {
        System.out.println("没有接收到数据报");
      } else {
        buffer.flip();
        System.out.println("接收到的数据报的大小为" + buffer.remaining());
      }
      Thread.sleep(500);
    }
  }
Example #23
0
  public static void main(String args[]) throws IOException {
    if (args.length != 1) {
      System.err.println("Usage: java LockingExample <input file>");
      System.exit(0);
    }

    FileLock sharedLock = null;
    FileLock exclusiveLock = null;

    try {
      RandomAccessFile raf = new RandomAccessFile(args[0], "rw");

      // get the channel for the file
      FileChannel channel = raf.getChannel();

      System.out.println("trying to acquire lock ...");
      // this locks the first half of the file - exclusive
      exclusiveLock = channel.lock(0, raf.length() / 2, SHARED);
      System.out.println("lock acquired ...");

      /** Now modify the data . . . */
      try {
        // sleep for 10 seconds
        Thread.sleep(10000);
      } catch (InterruptedException ie) {
      }

      // release the lock
      exclusiveLock.release();
      System.out.println("lock released ...");

      // this locks the second half of the file - shared
      sharedLock = channel.lock(raf.length() / 2 + 1, raf.length(), SHARED);

      /** Now read the data . . . */

      // release the lock
      sharedLock.release();
    } catch (java.io.IOException ioe) {
      System.err.println(ioe);
    } finally {
      if (exclusiveLock != null) exclusiveLock.release();
      if (sharedLock != null) sharedLock.release();
    }
  }
  /**
   * Checks if address can be reached using one argument InetAddress.isReachable() version or ping
   * command if failed.
   *
   * @param addr Address to check.
   * @param reachTimeout Timeout for the check.
   * @return {@code True} if address is reachable.
   */
  public static boolean reachableByPing(InetAddress addr, int reachTimeout) {
    try {
      if (addr.isReachable(reachTimeout)) return true;

      String cmd = String.format("ping -%s 1 %s", U.isWindows() ? "n" : "c", addr.getHostAddress());

      Process myProc = Runtime.getRuntime().exec(cmd);

      myProc.waitFor();

      return myProc.exitValue() == 0;
    } catch (IOException ignore) {
      return false;
    } catch (InterruptedException ignored) {
      Thread.currentThread().interrupt();

      return false;
    }
  }
 protected void accept_loop() {
   while (isRunning()) {
     try {
       SocketChannel client_channel = server_channel.accept();
       last_accept_time = SystemTime.getCurrentTime();
       client_channel.configureBlocking(false);
       listener.newConnectionAccepted(server_channel, client_channel);
     } catch (AsynchronousCloseException e) {
       /* is thrown when stop() is called */
     } catch (Throwable t) {
       Debug.out(t);
       try {
         Thread.sleep(500);
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
   }
 }
  // package-private
  int poll(int events, long timeout) throws IOException {
    assert Thread.holdsLock(blockingLock()) && !isBlocking();

    synchronized (readLock) {
      int n = 0;
      try {
        begin();
        synchronized (stateLock) {
          if (!isOpen()) return 0;
          readerThread = NativeThread.current();
        }
        n = Net.poll(fd, events, timeout);
      } finally {
        readerThread = 0;
        end(n > 0);
      }
      return n;
    }
  }
Example #27
0
 void startClient(boolean newThread) throws Exception {
   if (newThread) {
     clientThread =
         new Thread() {
           public void run() {
             try {
               doClientSide();
             } catch (Exception e) {
               /*
                * Our client thread just died.
                */
               System.err.println("Client died...");
               clientException = e;
             }
           }
         };
     clientThread.start();
   } else {
     doClientSide();
   }
 }
 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();
 }
Example #29
0
  public static void main(String[] args) throws IOException {
    ChannelRouter channelRouter =
        new ChannelRouter(
            new ExceptionListener<IOException>() {
              @Override
              public void exceptionThrown(IOException exception) {
                exception.printStackTrace();
              }
            });

    int port = Integer.parseInt(args[1]);
    SocketChannel socketChannel;
    if (args[0].equals("--server")) {
      System.out.println("Server mode started; listening on port " + port);
      ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
      serverSocketChannel.socket().bind(new InetSocketAddress(port));
      socketChannel = serverSocketChannel.accept();
      System.out.println("Client connected");
      serverSocketChannel.close();
    } else {
      String host = args[0];
      System.out.println("Client mode started; connecting to " + host + " on port " + port);
      socketChannel = SocketChannel.open(new InetSocketAddress(host, port));
      System.out.println("Connected to server");
    }
    socketChannel.configureBlocking(false);

    Pipe localToRemote = Pipe.open();
    localToRemote.source().configureBlocking(false);
    channelRouter.addRoute(localToRemote.source(), socketChannel);

    final Pipe remoteToLocal = Pipe.open();
    remoteToLocal.sink().configureBlocking(false);
    channelRouter.addRoute(socketChannel, remoteToLocal.sink());

    Thread channelRouterThread = new Thread(channelRouter, "ChannelRouter");
    channelRouterThread.start();

    Thread remoteReaderThread =
        new Thread("RemoteReader") {
          @Override
          public void run() {
            try {
              // BufferedReader.readLine() blocks until an end-of-line is
              // written, so make sure they get written by the main thread
              InputStream temporaryInputStream = Channels.newInputStream(remoteToLocal.source());
              BufferedReader in = new BufferedReader(new InputStreamReader(temporaryInputStream));
              String line = in.readLine();
              while (null != line) {
                System.out.println(line);
                line = in.readLine();
              }
            } catch (ClosedByInterruptException e) {
              // The main thread wants us to close, so do nothing
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        };
    remoteReaderThread.start();

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    Writer temporaryWriter = new OutputStreamWriter(Channels.newOutputStream(localToRemote.sink()));
    temporaryWriter = new BufferedWriter(temporaryWriter);
    PrintWriter out = new PrintWriter(temporaryWriter, true);

    System.out.println(
        "Press end-of-file to terminate (Ctrl+Z on Windows, Ctrl+D on other platforms)");
    String line = in.readLine();
    while (null != line) {
      // The end-of-line is required for BufferedReader.readLine() to
      // return and this will automatically flush due to the auto-flush
      // parameter on construction
      out.println(line);
      line = in.readLine();
    }

    remoteReaderThread.interrupt();
    channelRouterThread.interrupt();
    socketChannel.close();
  }
    public void run() {
      // every second, go through all the packets that havent been
      // ack'd
      List<RDPConnection> conList = new LinkedList<RDPConnection>();
      long lastCounterTime = System.currentTimeMillis();
      while (true) {
        try {
          long startTime = System.currentTimeMillis();
          long interval = startTime - lastCounterTime;
          if (interval > 1000) {

            if (Log.loggingNet) {
              Log.net(
                  "RDPServer counters: activeChannelCalls "
                      + activeChannelCalls
                      + ", selectCalls "
                      + selectCalls
                      + ", transmits "
                      + transmits
                      + ", retransmits "
                      + retransmits
                      + " in "
                      + interval
                      + "ms");
            }
            activeChannelCalls = 0;
            selectCalls = 0;
            transmits = 0;
            retransmits = 0;
            lastCounterTime = startTime;
          }
          if (Log.loggingNet) Log.net("RDPServer.RETRY: startTime=" + startTime);

          // go through all the rdpconnections and re-send any
          // unacked packets
          conList.clear();

          lock.lock();
          try {
            // make a copy since the values() collection is
            // backed by the map
            Set<RDPConnection> conCol = RDPServer.getAllConnections();
            if (conCol == null) {
              throw new MVRuntimeException("values() returned null");
            }
            conList.addAll(conCol); // make non map backed copy
          } finally {
            lock.unlock();
          }

          Iterator<RDPConnection> iter = conList.iterator();
          while (iter.hasNext()) {
            RDPConnection con = iter.next();
            long currentTime = System.currentTimeMillis();

            // is the connection in CLOSE_WAIT
            if (con.getState() == RDPConnection.CLOSE_WAIT) {
              long closeTime = con.getCloseWaitTimer();
              long elapsedTime = currentTime - closeTime;
              Log.net(
                  "RDPRetryThread: con is in CLOSE_WAIT: elapsed close timer(ms)="
                      + elapsedTime
                      + ", waiting for 30seconds to elapse. con="
                      + con);
              if (elapsedTime > 30000) {
                // close the connection
                Log.net("RDPRetryThread: removing CLOSE_WAIT connection. con=" + con);
                removeConnection(con);
              } else {
                Log.net(
                    "RDPRetryThread: time left on CLOSE_WAIT timer: "
                        + (30000 - (currentTime - closeTime)));
              }
              // con.close();
              continue;
            }
            if (Log.loggingNet)
              Log.net(
                  "RDPServer.RETRY: resending expired packets "
                      + con
                      + " - current list size = "
                      + con.unackListSize());

            // see if we should send a null packet, but only if con is already open
            if ((con.getState() == RDPConnection.OPEN)
                && ((currentTime - con.getLastNullPacketTime()) > 30000)) {
              con.getLock().lock();
              try {
                RDPPacket nulPacket = RDPPacket.makeNulPacket();
                con.sendPacketImmediate(nulPacket, false);
                con.setLastNullPacketTime();
                if (Log.loggingNet) Log.net("RDPServer.retry: sent nul packet: " + nulPacket);
              } finally {
                con.getLock().unlock();
              }
            } else {
              if (Log.loggingNet)
                Log.net(
                    "RDPServer.retry: sending nul packet in "
                        + (30000 - (currentTime - con.getLastNullPacketTime())));
            }
            con.resend(
                currentTime - resendTimerMS, // resend cutoff time
                currentTime - resendTimeoutMS); // giveup time
          }

          long endTime = System.currentTimeMillis();
          if (Log.loggingNet)
            Log.net(
                "RDPServer.RETRY: endTime=" + endTime + ", elapse(ms)=" + (endTime - startTime));
          Thread.sleep(250);
        } catch (Exception e) {
          Log.exception("RDPServer.RetryThread.run caught exception", e);
        }
      }
    }