Ejemplo n.º 1
0
 private void closeChannelAndReportException(Channel channel) {
   try {
     channel.close();
   } catch (IOException e) {
     reportIOException(e);
   }
 }
Ejemplo n.º 2
0
 public static void closeChannel(Channel channel) throws NetIOException {
   try {
     channel.close();
   } catch (IOException e) {
     throw new NetIOException(e);
   }
 }
Ejemplo n.º 3
0
  void finish(boolean close) throws BadDescriptorException, IOException {
    synchronized (refCounter) {
      // if refcount is at or below zero, we're no longer valid
      if (refCounter.get() <= 0) {
        throw new BadDescriptorException();
      }

      // if channel is already closed, we're no longer valid
      if (!channel.isOpen()) {
        throw new BadDescriptorException();
      }

      // otherwise decrement and possibly close as normal
      if (close) {
        int count = refCounter.decrementAndGet();

        if (DEBUG) LOG.info("Descriptor for fileno {} refs: {}", internalFileno, count);

        if (count <= 0) {
          // if we're the last referrer, close the channel
          try {
            channel.close();
          } finally {
            unregisterDescriptor(internalFileno);
          }
        }
      }
    }
  }
Ejemplo n.º 4
0
 /**
  * Closes the channel (safe).
  *
  * <p>This method tries to close the given channel and if an IOException occurs a message with the
  * level {@link Level#FINE} is logged. It's safe to pass a <code>null</code> reference for the
  * argument.
  *
  * @param channel the channel that should be closed.
  */
 public static void close(Channel channel) {
   if (channel != null) {
     try {
       channel.close();
     } catch (IOException x) {
       logCloseFailedWarningMessage(Channel.class, channel.getClass(), x);
     }
   }
 }
 static void closeAndWait(@Nullable Channel channel, Logger log) throws IOException {
   if (channel != null) {
     channel.close();
     try {
       Thread.sleep(500);
     } catch (InterruptedException e) {
       log.warn("", e);
     }
   }
 }
Ejemplo n.º 6
0
  /**
   * Close the channel
   *
   * @param channel the channel to close
   */
  public static void close(Channel channel) {
    if (channel != null) {

      try {
        channel.close();
      } catch (IOException e) {
        // Nothing to do
      }
    }
  }
Ejemplo n.º 7
0
 public static void cleanUp(Channel channel) {
   try {
     if (channel != null) {
       channel.close();
     }
   } catch (Exception e) {
     if (_log.isWarnEnabled()) {
       _log.warn(e, e);
     }
   }
 }
    void cleanupChannel(final Channel ch, final Runnable callback) {

      if (null == ch) {
        // not expected
        logger.warn("null channel passed to cleanupChannel()", new Throwable());
        return;
      }

      if (Thread.currentThread() != this) {
        if (logger.isDebugEnabled()) {
          logger.debug("queue'ing channel close operation");
        }

        addSelectorTask(
            new Runnable() {
              @Override
              public void run() {
                CommThread.this.cleanupChannel(ch, callback);
              }
            });
        return;
      }

      try {
        if (ch instanceof SelectableChannel) {
          SelectableChannel sc = (SelectableChannel) ch;

          try {
            SelectionKey sk = sc.keyFor(selector);
            if (sk != null) {
              sk.attach(null);
              sk.cancel();
            }
          } catch (Exception e) {
            logger.warn("Exception trying to clear selection key", e);
          }
        }

        if (ch instanceof SocketChannel) {
          SocketChannel sc = (SocketChannel) ch;

          Socket s = sc.socket();

          if (null != s) {
            synchronized (s) {
              if (s.isConnected()) {
                try {
                  if (!s.isOutputShutdown()) {
                    s.shutdownOutput();
                  }
                } catch (Exception e) {
                  logger.warn("Exception trying to shutdown socket output: " + e.getMessage());
                }

                try {
                  if (!s.isClosed()) {
                    s.close();
                  }
                } catch (Exception e) {
                  logger.warn("Exception trying to close() socket: " + e.getMessage());
                }
              }
            }
          }
        } else if (ch instanceof ServerSocketChannel) {
          ServerSocketChannel ssc = (ServerSocketChannel) ch;

          try {
            ssc.close();
          } catch (Exception e) {
            logger.warn("Exception trying to close() server socket" + e.getMessage());
          }
        }

        try {
          ch.close();
        } catch (Exception e) {
          logger.warn("Exception trying to close channel", e);
        }
      } catch (Exception e) {
        // this is just a catch all to make sure that no exceptions will be thrown by this method,
        // please do not remove
        logger.error("Unhandled exception in cleanupChannel()", e);
      } finally {
        try {
          if (callback != null) {
            callback.run();
          }
        } catch (Throwable t) {
          logger.error("Unhandled exception in cleanupChannel callback.", t);
        }
      }
    }
Ejemplo n.º 9
0
    @Override
    public void run() {
      // loop while any socket is open
      while (incoming.isOpen() || !peers.isEmpty()) {
        try {
          // wait on selector
          selector.select(10000);

          // Handle all ready channels
          Set<SelectionKey> selected = selector.selectedKeys();
          for (SelectionKey k : selected.toArray(new SelectionKey[0])) {
            selected.remove(k); // We're handling it

            if (!k.isValid()) continue; // Invalid?

            Channel c = k.channel();
            if (c.equals(incoming)) {
              acceptIncomingPeer();
            } else if (new_sockets.contains(c)) {
              processNewSocket((SocketChannel) c);
            } else if (new_peers.containsKey(c)) {
              processNewPeer((SocketChannel) c);
            } else if (peers.containsKey(c)) {
              processPeerMessage((SocketChannel) c);
            } else {
              System.err.println("Tried to process unknown socket.");
              k.cancel(); // If we don't know it now, we'll probably never know it.
              c.close();
            }
          }

          // Check for closed sockets
          for (SocketChannel socket : peers.keySet().toArray(new SocketChannel[0])) {
            if (!socket.isOpen()) {
              socket.keyFor(selector).cancel();
              Peer peer = peers.get(socket);
              peers.remove(socket);
              sockets.remove(peer);
              if (listener != null) listener.dropPeer(peer);
              // TODO: Reconnect, propose drop
            }
          }
          for (SocketChannel socket : new_sockets) {
            if (!socket.isOpen()) {
              socket.keyFor(selector).cancel();
              new_sockets.remove(socket);
            }
          }
          for (SocketChannel socket : new_peers.keySet()) {
            if (!socket.isOpen()) {
              socket.keyFor(selector).cancel();
              new_peers.remove(socket);
              // TODO: Retry?
            } else if (!socket.isRegistered()) {
              // Check for new sockets.
              socket.register(selector, SelectionKey.OP_READ);
            }
          }
        } catch (IOException e) {
          // TODO Handle this better.  In mean time, just keep going.
          System.err.println(e);
          e.printStackTrace();
        }
      }
      try {
        selector.close();
      } catch (IOException e) {
        // Not much to do.
        e.printStackTrace();
      }
    }