Example usage for java.nio.channels SocketChannel close

List of usage examples for java.nio.channels SocketChannel close

Introduction

In this page you can find the example usage for java.nio.channels SocketChannel close.

Prototype

public final void close() throws IOException 

Source Link

Document

Closes this channel.

Usage

From source file:com.turn.ttorrent.client.Client.java

/**
 * Handle a new peer connection./*from   w w  w .j av a2  s.  co m*/
 *
 * <p>
 * This handler is called once the connection has been successfully
 * established and the handshake exchange made. This generally simply means
 * binding the peer to the socket, which will put in place the communication
 * thread and logic with this peer.
 * </p>
 *
 * @param channel The connected socket channel to the remote peer. Note
 * that if the peer somehow rejected our handshake reply, this socket might
 * very soon get closed, but this is handled down the road.
 * @param peerId The byte-encoded peerId extracted from the peer's
 * handshake, after validation.
 * @see com.turn.ttorrent.client.peer.SharingPeer
 */
@Override
public void handleNewPeerConnection(SocketChannel channel, byte[] peerId) {
    Peer search = new Peer(channel.socket().getInetAddress().getHostAddress(), channel.socket().getPort(),
            (peerId != null ? ByteBuffer.wrap(peerId) : (ByteBuffer) null));

    logger.info("Handling new peer connection with {}...", search);
    SharingPeer peer = this.getOrCreatePeer(search);

    try {
        synchronized (peer) {
            if (peer.isConnected()) {
                logger.info("Already connected with {}, closing link.", peer);
                channel.close();
                return;
            }

            peer.register(this);
            peer.bind(channel);
        }

        this.connected.put(peer.getHexPeerId(), peer);
        peer.register(this.torrent);
        logger.debug("New peer connection with {} [{}/{}].",
                new Object[] { peer, this.connected.size(), this.peers.size() });
    } catch (Exception e) {
        this.connected.remove(peer.getHexPeerId());
        logger.warn("Could not handle new peer connection " + "with {}: {}", peer, e.getMessage());
    }
}

From source file:x10.x10rt.yarn.ApplicationMaster.java

protected void handleX10() {
    // handle X10 place requests
    Iterator<SelectionKey> events = null;
    while (running) {
        try {//  www .  j a va2  s  .co m
            SelectionKey key;
            // check for previously unhandled events
            if (events != null && events.hasNext()) {
                key = events.next();
                events.remove();
            } else if (selector.select() == 0) // check for new events
                continue; // nothing to process, go back and block on select again
            else { // select returned some events
                events = selector.selectedKeys().iterator();
                key = events.next();
                events.remove();
            }

            // process the selectionkey
            if (key.isAcceptable()) {
                LOG.info("New connection from X10 detected");
                // accept any connections on the server socket, and look for things to read from it
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                SocketChannel sc = ssc.accept();
                sc.configureBlocking(false);
                sc.register(selector, SelectionKey.OP_READ);
            }
            if (key.isReadable()) {
                SocketChannel sc = (SocketChannel) key.channel();

                ByteBuffer incomingMsg;
                if (pendingReads.containsKey(sc))
                    incomingMsg = pendingReads.remove(sc);
                else
                    incomingMsg = ByteBuffer.allocateDirect(headerLength).order(ByteOrder.nativeOrder());

                LOG.info("Reading message from X10");
                try {
                    if (sc.read(incomingMsg) == -1) {
                        // socket closed
                        sc.close();
                        key.cancel();
                        pendingReads.remove(sc);
                    } else if (incomingMsg.hasRemaining()) {
                        LOG.info("Message header partially read. " + incomingMsg.remaining()
                                + " bytes remaining");
                        pendingReads.put(sc, incomingMsg);
                    } else { // buffer is full
                        if (incomingMsg.capacity() == headerLength) {
                            // check to see if there is a body associated with this message header
                            int datalen = incomingMsg.getInt(headerLength - 4);
                            //System.err.println("Byte order is "+incomingMsg.order()+" datalen="+datalen);
                            if (datalen == 0)
                                processMessage(incomingMsg, sc);
                            else { // create a larger array to hold the header+body
                                ByteBuffer newBuffer = ByteBuffer.allocateDirect(headerLength + datalen)
                                        .order(ByteOrder.nativeOrder());
                                incomingMsg.rewind();
                                newBuffer.put(incomingMsg);
                                incomingMsg = newBuffer;
                                sc.read(incomingMsg); // read in the body, if available
                                if (incomingMsg.hasRemaining()) {
                                    LOG.info("Message partially read. " + incomingMsg.remaining()
                                            + " bytes remaining");
                                    pendingReads.put(sc, incomingMsg);
                                } else
                                    processMessage(incomingMsg, sc);
                            }
                        }
                    }
                } catch (IOException e) {
                    LOG.warn("Error reading in message from socket channel", e);
                }
            }
        } catch (IOException e) {
            LOG.warn("Error handling X10 links", e);
        }
    }
}

From source file:com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource.java

public String connect(final String ipAddress, final int port) {
    for (int i = 0; i <= _retry; i++) {
        SocketChannel sch = null;
        try {/*from w w w.j  a va  2s .c  om*/
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Trying to connect to " + ipAddress);
            }
            sch = SocketChannel.open();
            sch.configureBlocking(true);

            final InetSocketAddress addr = new InetSocketAddress(ipAddress, port);
            sch.connect(addr);
            return null;
        } catch (final IOException e) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Could not connect to " + ipAddress);
            }
        } finally {
            if (sch != null) {
                try {
                    sch.close();
                } catch (final IOException e) {
                }
            }
        }
        try {
            Thread.sleep(_sleep);
        } catch (final InterruptedException e) {
        }
    }

    s_logger.debug("Unable to logon to " + ipAddress);

    return "Unable to connect";
}

From source file:org.openhab.binding.irtrans.handler.EthernetBridgeHandler.java

protected void onConnectable() {
    lock.lock();/*from  www.ja  v a2 s.c o  m*/
    SocketChannel aSocketChannel = null;
    try {
        synchronized (selector) {
            selector.selectNow();
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey selKey = it.next();
            it.remove();
            if (selKey.isValid() && selKey.isConnectable()) {
                aSocketChannel = (SocketChannel) selKey.channel();
                aSocketChannel.finishConnect();
                logger.trace("The channel for '{}' is connected", aSocketChannel.getRemoteAddress());
            }
        }
    } catch (IOException | NoConnectionPendingException e) {
        if (aSocketChannel != null) {
            logger.debug("Disconnecting '{}' because of a socket error : '{}'", getThing().getUID(),
                    e.getMessage(), e);
            try {
                aSocketChannel.close();
            } catch (IOException e1) {
                logger.debug("An exception occurred while closing the channel '{}': {}", socketChannel,
                        e1.getMessage());
            }
        }
    } finally {
        lock.unlock();
    }
}

From source file:Proxy.java

/** We handle only non-SSL connections */
void loop(Selector selector) {
    Set ready_keys;/*from ww w  . j  a  va 2 s .  c  o m*/
    SelectionKey key;
    ServerSocketChannel srv_sock;
    SocketChannel in_sock, out_sock;
    InetSocketAddress src, dest;

    while (true) {
        if (verbose)
            log("[Proxy] ready to accept connection");

        // 4. Call Selector.select()
        try {
            selector.select();

            // get set of ready objects
            ready_keys = selector.selectedKeys();
            for (Iterator it = ready_keys.iterator(); it.hasNext();) {
                key = (SelectionKey) it.next();
                it.remove();

                if (key.isAcceptable()) {
                    srv_sock = (ServerSocketChannel) key.channel();
                    // get server socket and attachment
                    src = (InetSocketAddress) key.attachment();
                    in_sock = srv_sock.accept(); // accept request
                    if (verbose)
                        log("Proxy.loop()", "accepted connection from " + toString(in_sock));
                    dest = (InetSocketAddress) mappings.get(src);
                    // find corresponding dest
                    if (dest == null) {
                        in_sock.close();
                        log("Proxy.loop()", "did not find a destination host for " + src);
                        continue;
                    } else {
                        if (verbose)
                            log("Proxy.loop()",
                                    "relaying traffic from " + toString(src) + " to " + toString(dest));
                    }

                    // establish connection to destination host
                    try {
                        out_sock = SocketChannel.open(dest);
                        // uses thread pool (Executor) to handle request, closes socks at end
                        handleConnection(in_sock, out_sock);
                    } catch (Exception ex) {
                        in_sock.close();
                        throw ex;
                    }
                }
            }
        } catch (Exception ex) {
            log("Proxy.loop()", "exception: " + ex);
        }
    }
}

From source file:org.apache.zookeeper.server.quorum.QuorumPeerMainTest.java

/**
 * verify if bad packets are being handled properly
 * at the quorum port//  ww w. j av  a 2s  .  c om
 * @throws Exception
 */
@Test
public void testBadPackets() throws Exception {
    ClientBase.setupTestEnv();
    final int CLIENT_PORT_QP1 = PortAssignment.unique();
    final int CLIENT_PORT_QP2 = PortAssignment.unique();
    int electionPort1 = PortAssignment.unique();
    int electionPort2 = PortAssignment.unique();
    String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + electionPort1 + ";"
            + CLIENT_PORT_QP1 + "\nserver.2=127.0.0.1:" + PortAssignment.unique() + ":" + electionPort2 + ";"
            + CLIENT_PORT_QP2;

    MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
    MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection);
    q1.start();
    q2.start();

    Assert.assertTrue("waiting for server 1 being up",
            ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, CONNECTION_TIMEOUT));
    Assert.assertTrue("waiting for server 2 being up",
            ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, CONNECTION_TIMEOUT));

    byte[] b = new byte[4];
    int length = 1024 * 1024 * 1024;
    ByteBuffer buff = ByteBuffer.wrap(b);
    buff.putInt(length);
    buff.position(0);
    SocketChannel s = SocketChannel.open(new InetSocketAddress("127.0.0.1", electionPort1));
    s.write(buff);
    s.close();
    buff.position(0);
    s = SocketChannel.open(new InetSocketAddress("127.0.0.1", electionPort2));
    s.write(buff);
    s.close();

    ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT, this);
    waitForOne(zk, States.CONNECTED);
    zk.create("/foo_q1", "foobar1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    Assert.assertEquals(new String(zk.getData("/foo_q1", null, null)), "foobar1");
    zk.close();
    q1.shutdown();
    q2.shutdown();
}

From source file:org.apache.hadoop.mapred.buffer.Manager.java

public void open() throws IOException {
    Configuration conf = tracker.conf();
    int maxMaps = conf.getInt("mapred.tasktracker.map.tasks.maximum", 2);
    int maxReduces = conf.getInt("mapred.tasktracker.reduce.tasks.maximum", 1);

    InetSocketAddress serverAddress = getServerAddress(conf);
    this.server = RPC.getServer(this, serverAddress.getHostName(), serverAddress.getPort(),
            maxMaps + maxReduces, false, conf);
    this.server.start();

    this.requestTransfer.setPriority(Thread.MAX_PRIORITY);
    this.requestTransfer.start();

    /** The server socket and selector registration */
    InetSocketAddress controlAddress = getControlAddress(conf);
    this.controlPort = controlAddress.getPort();
    this.channel = ServerSocketChannel.open();
    this.channel.socket().bind(controlAddress);

    this.acceptor = new Thread() {
        @Override/*from  www  .java  2  s  .co m*/
        public void run() {
            while (!isInterrupted()) {
                SocketChannel connection = null;
                try {
                    connection = channel.accept();
                    DataInputStream in = new DataInputStream(connection.socket().getInputStream());
                    int numRequests = in.readInt();
                    for (int i = 0; i < numRequests; i++) {
                        BufferRequest request = BufferRequest.read(in);
                        if (request instanceof ReduceBufferRequest) {
                            add((ReduceBufferRequest) request);
                            LOG.info("add new request " + request);
                        } else if (request instanceof MapBufferRequest) {
                            add((MapBufferRequest) request);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (connection != null)
                            connection.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    };
    this.acceptor.setDaemon(true);
    this.acceptor.setPriority(Thread.MAX_PRIORITY);
    this.acceptor.start();

    this.serviceQueue = new Thread() {
        public void run() {
            List<OutputFile> service = new ArrayList<OutputFile>();
            while (!isInterrupted()) {
                try {
                    OutputFile o = queue.take();
                    service.add(o);
                    queue.drainTo(service);
                    for (OutputFile file : service) {
                        try {
                            if (file != null)
                                add(file);
                        } catch (Throwable t) {
                            t.printStackTrace();
                            LOG.error("Error service file: " + file + ". " + t);
                        }
                    }
                } catch (Throwable t) {
                    t.printStackTrace();
                    LOG.error(t);
                } finally {
                    service.clear();
                }
            }
            LOG.info("Service queue thread exit.");
        }
    };
    this.serviceQueue.setPriority(Thread.MAX_PRIORITY);
    this.serviceQueue.setDaemon(true);
    this.serviceQueue.start();
}

From source file:org.apache.htrace.impl.PackedBufferManager.java

private SelectionKey doConnect() throws IOException {
    SocketChannel sock = SocketChannel.open();
    SelectionKey sockKey = null;//from   w  w w . j  av  a  2 s .  com
    boolean success = false;
    try {
        if (sock.isBlocking()) {
            sock.configureBlocking(false);
        }
        InetSocketAddress resolvedEndpoint = new InetSocketAddress(conf.endpoint.getHostString(),
                conf.endpoint.getPort());
        resolvedEndpoint.getHostName(); // trigger DNS resolution
        sock.connect(resolvedEndpoint);
        sockKey = sock.register(selector, SelectionKey.OP_CONNECT, sock);
        long startMs = TimeUtil.nowMs();
        long remainingMs = conf.connectTimeoutMs;
        while (true) {
            selector.select(remainingMs);
            for (SelectionKey key : selector.keys()) {
                if (key.isConnectable()) {
                    SocketChannel s = (SocketChannel) key.attachment();
                    s.finishConnect();
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Successfully connected to " + conf.endpointStr + ".");
                    }
                    success = true;
                    return sockKey;
                }
            }
            remainingMs = updateRemainingMs(startMs, conf.connectTimeoutMs);
            if (remainingMs == 0) {
                throw new IOException("Attempt to connect to " + conf.endpointStr + " timed out after "
                        + TimeUtil.deltaMs(startMs, TimeUtil.nowMs()) + " ms.");
            }
        }
    } finally {
        if (!success) {
            if (sockKey != null) {
                sockKey.cancel();
            }
            sock.close();
        }
    }
}

From source file:org.openhab.binding.irtrans.handler.EthernetBridgeHandler.java

protected ByteBuffer onReadable(int bufferSize, boolean isSelective) {
    lock.lock();/*from  w  w w .  j  av a  2  s . com*/
    try {
        synchronized (selector) {
            try {
                selector.selectNow();
            } catch (IOException e) {
                logger.error("An exception occurred while selecting: {}", e.getMessage());
            }
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey selKey = it.next();
            it.remove();
            if (selKey.isValid() && selKey.isReadable()) {
                SocketChannel aSocketChannel = (SocketChannel) selKey.channel();

                if ((aSocketChannel.equals(socketChannel) && isSelective) || !isSelective) {
                    ByteBuffer readBuffer = ByteBuffer.allocate(bufferSize);
                    int numberBytesRead = 0;
                    boolean error = false;

                    try {
                        numberBytesRead = aSocketChannel.read(readBuffer);
                    } catch (NotYetConnectedException e) {
                        logger.warn("The channel '{}' is not yet connected: {}", aSocketChannel,
                                e.getMessage());
                        if (!aSocketChannel.isConnectionPending()) {
                            error = true;
                        }
                    } catch (IOException e) {
                        // If some other I/O error occurs
                        logger.warn("An IO exception occured on channel '{}': {}", aSocketChannel,
                                e.getMessage());
                        error = true;
                    }

                    if (numberBytesRead == -1) {
                        error = true;
                    }

                    if (error) {
                        logger.debug("Disconnecting '{}' because of a socket error", getThing().getUID());
                        try {
                            aSocketChannel.close();
                        } catch (IOException e1) {
                            logger.debug("An exception occurred while closing the channel '{}': {}",
                                    socketChannel, e1.getMessage());
                        }
                    } else {
                        readBuffer.flip();
                        return readBuffer;
                    }
                }
            }
        }

        return null;
    } finally {
        lock.unlock();
    }
}

From source file:org.openhab.binding.irtrans.handler.EthernetBridgeHandler.java

protected void onWritable(ByteBuffer buffer) {
    lock.lock();//www .j  a v a2  s.  com
    try {
        synchronized (selector) {
            try {
                selector.selectNow();
            } catch (IOException e) {
                logger.error("An exception occurred while selecting: {}", e.getMessage());
            }
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey selKey = it.next();
            it.remove();
            if (selKey.isValid() && selKey.isWritable()) {
                SocketChannel aSocketChannel = (SocketChannel) selKey.channel();

                if (aSocketChannel.equals(socketChannel)) {
                    boolean error = false;

                    buffer.rewind();
                    try {
                        logger.trace("Sending '{}' on the channel '{}'->'{}'", new String(buffer.array()),
                                aSocketChannel.getLocalAddress(), aSocketChannel.getRemoteAddress());
                        aSocketChannel.write(buffer);
                    } catch (NotYetConnectedException e) {
                        logger.warn("The channel '{}' is not yet connected: {}", aSocketChannel,
                                e.getMessage());
                        if (!aSocketChannel.isConnectionPending()) {
                            error = true;
                        }
                    } catch (ClosedChannelException e) {
                        // If some other I/O error occurs
                        logger.warn("The channel for '{}' is closed: {}", aSocketChannel, e.getMessage());
                        error = true;
                    } catch (IOException e) {
                        // If some other I/O error occurs
                        logger.warn("An IO exception occured on channel '{}': {}", aSocketChannel,
                                e.getMessage());
                        error = true;
                    }

                    if (error) {
                        try {
                            aSocketChannel.close();
                        } catch (IOException e) {
                            logger.warn("An exception occurred while closing the channel '{}': {}",
                                    aSocketChannel, e.getMessage());
                        }
                    }
                }
            }
        }
    } finally {
        lock.unlock();
    }
}