Java Code Examples for java.nio.channels.SocketChannel#close()

The following examples show how to use java.nio.channels.SocketChannel#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestTunnelWithArbitraryTCPTraffic.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Test(enabled=false, timeOut = 15000)
public void testTunnelToEchoServer() throws IOException {
  MockServer proxyServer = startConnectProxyServer();
  Tunnel tunnel = Tunnel.build("localhost", doubleEchoServer.getServerSocketPort(), "localhost",
      proxyServer.getServerSocketPort());

  try {
    int tunnelPort = tunnel.getPort();
    SocketChannel client = SocketChannel.open();

    client.connect(new InetSocketAddress("localhost", tunnelPort));
    client.write(ByteBuffer.wrap("Knock\n".getBytes()));
    String response = readFromSocket(client);
    client.close();

    assertEquals(response, "Knock Knock\n");
    assertEquals(proxyServer.getNumConnects(), 1);
  } finally {
    proxyServer.stopServer();
    tunnel.close();
    assertFalse(tunnel.isTunnelThreadAlive());
  }
}
 
Example 2
Source File: SocketChannelTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * @tests SocketChannel#read(ByteBuffer[], int, int) with a null ByteBuffer
 */
public void test_socketChannel_read_ByteBufferII_bufNULL() throws Exception {
    // regression 3 for HARMONY-549
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(null);
    SocketChannel sc = SocketChannel.open();
    sc.connect(ssc.socket().getLocalSocketAddress());
    ssc.accept();
    ByteBuffer[] buf = new ByteBuffer[2];
    buf[0] = ByteBuffer.allocate(1);
    // let buf[1] be null
    try {
        sc.read(buf, 0, 2);
        fail("should throw NullPointerException");
    } catch (NullPointerException expected) {
    }
    ssc.close();
    sc.close();
}
 
Example 3
Source File: ReactorEchoServerV1.java    From new-bull with MIT License 6 votes vote down vote up
@Override
        public void handle(SelectionKey key) {
//            System.out.println("encoder. writingSize:" + writingSize);
            SocketChannel channel = (SocketChannel) key.channel();
            try {
                if (writingSize) {
                    channel.write(sizeBuf);
                    if (!sizeBuf.hasRemaining()) {
                        writingSize = false;
                    }
                } else {
                    channel.write(dataBuf);
                    if (!dataBuf.hasRemaining()) {
                        channel.close();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
 
Example 4
Source File: TunnelTest.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Test (enabled=false)
public void mustHandleClientDisconnectingWithoutClosingTunnel()
    throws Exception {
  mockExample();
  Tunnel tunnel = Tunnel.build("example.org", 80, "localhost", PORT);

  try {
    int tunnelPort = tunnel.getPort();
    SocketChannel client = SocketChannel.open();

    client.connect(new InetSocketAddress("localhost", tunnelPort));
    client.write(ByteBuffer.wrap("GET / HTTP/1.1%nUser-Agent: GobblinTunnel%nConnection:keep - alive %n%n".getBytes()));
    client.close();

    assertNotNull(fetchContent(tunnelPort));
  } finally {
    tunnel.close();
  }
}
 
Example 5
Source File: P2pMgr.java    From aion with MIT License 6 votes vote down vote up
@Override
public void closeSocket(SocketChannel _sc, String _reason, Exception e) {
    if (p2pLOG.isDebugEnabled()) {
        if (e != null) {
            p2pLOG.debug("close-socket reason=" + _reason, e);
        } else {
            p2pLOG.debug("close-socket reason={}", _reason);
        }
    }

    if (_sc != null) {
        SelectionKey sk = _sc.keyFor(selector);
        if (sk != null) {
            sk.cancel();
            sk.attach(null);
        }

        try {
            _sc.close();
        } catch (IOException ex) {
            p2pLOG.info("close-socket-io-exception.", ex);
        }
    }
}
 
Example 6
Source File: RCONServer.java    From Nemisys with GNU General Public License v3.0 5 votes vote down vote up
private void read(SelectionKey key) throws IOException {
    SocketChannel channel = (SocketChannel) key.channel();
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    buffer.order(ByteOrder.LITTLE_ENDIAN);

    int bytesRead;
    try {
        bytesRead = channel.read(buffer);
    } catch (IOException exception) {
        key.cancel();
        channel.close();
        if (this.rconSessions.contains(channel)) {
            this.rconSessions.remove(channel);
        }
        if (this.sendQueues.containsKey(channel)) {
            this.sendQueues.remove(channel);
        }
        return;
    }

    if (bytesRead == -1) {
        key.cancel();
        channel.close();
        if (this.rconSessions.contains(channel)) {
            this.rconSessions.remove(channel);
        }
        if (this.sendQueues.containsKey(channel)) {
            this.sendQueues.remove(channel);
        }
        return;
    }

    buffer.flip();
    this.handle(channel, new RCONPacket(buffer));
}
 
Example 7
Source File: RCONServer.java    From BukkitPE with GNU General Public License v3.0 5 votes vote down vote up
private void write(SelectionKey key) throws IOException {
    SocketChannel channel = (SocketChannel) key.channel();

    synchronized (this.sendQueues) {
        List<RCONPacket> queue = this.sendQueues.get(channel);

        ByteBuffer buffer = queue.get(0).toBuffer();
        try {
            channel.write(buffer);
            queue.remove(0);
        } catch (IOException exception) {
            key.cancel();
            channel.close();
            if (this.rconSessions.contains(channel)) {
                this.rconSessions.remove(channel);
            }
            if (this.sendQueues.containsKey(channel)) {
                this.sendQueues.remove(channel);
            }
            return;
        }

        if (queue.isEmpty()) {
            this.sendQueues.remove(channel);
        }

        key.interestOps(SelectionKey.OP_READ);
    }
}
 
Example 8
Source File: DriverOptions.java    From karate with MIT License 5 votes vote down vote up
private boolean waitForPort(String host, int port) {
    int attempts = 0;
    do {
        SocketAddress address = new InetSocketAddress(host, port);
        try {
            processLogger.debug("poll attempt #{} for port to be ready - {}:{}", attempts, host, port);
            SocketChannel sock = SocketChannel.open(address);
            sock.close();
            return true;
        } catch (IOException e) {
            sleep(pollInterval);
        }
    } while (attempts++ < pollAttempts);
    return false;
}
 
Example 9
Source File: DeviceMonitor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private void removeDevice(@NonNull Device device) {
    device.clearClientList();
    mDevices.remove(device);

    SocketChannel channel = device.getClientMonitoringSocket();
    if (channel != null) {
        try {
            channel.close();
        } catch (IOException e) {
            // doesn't really matter if the close fails.
        }
    }
}
 
Example 10
Source File: TestBlockingNIO2.java    From cs-summary-reflection with Apache License 2.0 5 votes vote down vote up
@Test
public void client() throws IOException {
    SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));

    FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);

    ByteBuffer buf = ByteBuffer.allocate(1024);

    while (inChannel.read(buf) != -1) {
        buf.flip();
        sChannel.write(buf);
        buf.clear();
    }

    sChannel.shutdownOutput();

    // 接收服务端的反馈
    int len = 0;
    while ((len = sChannel.read(buf)) != -1) {
        buf.flip();
        System.out.println(new String(buf.array(), 0, len));
        buf.clear();
    }

    inChannel.close();
    sChannel.close();
}
 
Example 11
Source File: SelectorTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void assert_select_OP_ACCEPT(SelectType type, int timeout)
        throws IOException, ClosedChannelException {
    SocketChannel sc = SocketChannel.open();
    SocketChannel client = null;
    try {
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        sc.connect(localAddress);
        int count = blockingSelect(type, timeout);
        assertEquals(1, count);
        Set<SelectionKey> selectedKeys = selector.selectedKeys();
        assertEquals(1, selectedKeys.size());
        SelectionKey key = selectedKeys.iterator().next();
        assertEquals(ssc.keyFor(selector), key);
        assertEquals(SelectionKey.OP_ACCEPT, key.readyOps());
        // select again, it should return 0
        count = selectOnce(type, timeout);
        assertEquals(0,count);
        // but selectedKeys remains the same as previous
        assertSame(selectedKeys, selector.selectedKeys());
        client = ssc.accept();
        selectedKeys.clear();
    } finally {
        try {
            sc.close();
        } catch (IOException e) {
            // do nothing
        }
        if (null != client) {
            client.close();
        }
    }
    ssc.keyFor(selector).cancel();
}
 
Example 12
Source File: TestTunnelWithArbitraryTCPTraffic.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Test(enabled=false, timeOut = 15000, expectedExceptions = IOException.class)
public void testTunnelThreadDeadAfterUnexpectedException() throws IOException, InterruptedException {
  MockServer proxyServer = startConnectProxyServer(false, false, 8);

  Tunnel tunnel = Tunnel.build("localhost", doubleEchoServer.getServerSocketPort(),
      "localhost", proxyServer.getServerSocketPort());

  String response = "";
  try {
    int tunnelPort = tunnel.getPort();
    SocketChannel client = SocketChannel.open();

    client.connect(new InetSocketAddress("localhost", tunnelPort));
    client.write(ByteBuffer.wrap("Knock\n".getBytes()));
    response = readFromSocket(client);
    LOG.info(response);

    for (int i = 0; i < 5; i++) {
      client.write(ByteBuffer.wrap("Hello\n".getBytes()));
      Thread.sleep(100);
    }
    client.close();
  } finally {
    proxyServer.stopServer();
    tunnel.close();
    assertNotEquals(response, "Knock Knock\n");
    assertEquals(proxyServer.getNumConnects(), 1);
    assertFalse(tunnel.isTunnelThreadAlive());
  }
}
 
Example 13
Source File: TestTunnelWithArbitraryTCPTraffic.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Test(enabled=false, timeOut = 15000)
public void testDirectConnectionToEchoServer() throws IOException {
  SocketChannel client = SocketChannel.open();
  try {
    client.connect(new InetSocketAddress("localhost", doubleEchoServer.getServerSocketPort()));
    writeToSocket(client, "Knock\n".getBytes());
    String response = readFromSocket(client);
    client.close();
    assertEquals(response, "Knock Knock\n");
  } finally {
    client.close();
  }
}
 
Example 14
Source File: RCONServer.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
private void read(SelectionKey key) throws IOException {
    SocketChannel channel = (SocketChannel) key.channel();
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    buffer.order(ByteOrder.LITTLE_ENDIAN);

    int bytesRead;
    try {
        bytesRead = channel.read(buffer);
    } catch (IOException exception) {
        key.cancel();
        channel.close();
        this.rconSessions.remove(channel);
        this.sendQueues.remove(channel);
        return;
    }

    if (bytesRead == -1) {
        key.cancel();
        channel.close();
        this.rconSessions.remove(channel);
        this.sendQueues.remove(channel);
        return;
    }

    buffer.flip();
    this.handle(channel, new RCONPacket(buffer));
}
 
Example 15
Source File: AsynchronousEcho.java    From vertx-in-action with MIT License 4 votes vote down vote up
private static void cleanup(SocketChannel socketChannel) throws IOException {
  socketChannel.close();
  contexts.remove(socketChannel);
}
 
Example 16
Source File: SocketIOWithTimeout.java    From RDFS with Apache License 2.0 4 votes vote down vote up
/**
 * The contract is similar to {@link SocketChannel#connect(SocketAddress)} 
 * with a timeout.
 * 
 * @see SocketChannel#connect(SocketAddress)
 * 
 * @param channel - this should be a {@link SelectableChannel}
 * @param endpoint
 * @throws IOException
 */
static void connect(SocketChannel channel, 
                    SocketAddress endpoint, int timeout) throws IOException {
  
  boolean blockingOn = channel.isBlocking();
  if (blockingOn) {
    channel.configureBlocking(false);
  }
  
  try { 
    if (channel.connect(endpoint)) {
      return;
    }

    long timeoutLeft = timeout;
    long endTime = (timeout > 0) ? (System.currentTimeMillis() + timeout): 0;
    
    while (true) {
      // we might have to call finishConnect() more than once
      // for some channels (with user level protocols)
      
      int ret = selector.select((SelectableChannel)channel, 
                                SelectionKey.OP_CONNECT, timeoutLeft);
      
      if (ret > 0 && channel.finishConnect()) {
        return;
      }
      
      if (ret == 0 ||
          (timeout > 0 &&  
            (timeoutLeft = (endTime - System.currentTimeMillis())) <= 0)) {
        throw new SocketTimeoutException(
                  timeoutExceptionString(channel, timeout, 
                                         SelectionKey.OP_CONNECT));
      }
    }
  } catch (IOException e) {
    // javadoc for SocketChannel.connect() says channel should be closed.
    try {
      channel.close();
    } catch (IOException ignored) {}
    throw e;
  } finally {
    if (blockingOn && channel.isOpen()) {
      channel.configureBlocking(true);
    }
  }
}
 
Example 17
Source File: SocketIOWithTimeout.java    From hadoop-gpu with Apache License 2.0 4 votes vote down vote up
/**
 * The contract is similar to {@link SocketChannel#connect(SocketAddress)} 
 * with a timeout.
 * 
 * @see SocketChannel#connect(SocketAddress)
 * 
 * @param channel - this should be a {@link SelectableChannel}
 * @param endpoint
 * @throws IOException
 */
static void connect(SocketChannel channel, 
                    SocketAddress endpoint, int timeout) throws IOException {
  
  boolean blockingOn = channel.isBlocking();
  if (blockingOn) {
    channel.configureBlocking(false);
  }
  
  try { 
    if (channel.connect(endpoint)) {
      return;
    }

    long timeoutLeft = timeout;
    long endTime = (timeout > 0) ? (System.currentTimeMillis() + timeout): 0;
    
    while (true) {
      // we might have to call finishConnect() more than once
      // for some channels (with user level protocols)
      
      int ret = selector.select((SelectableChannel)channel, 
                                SelectionKey.OP_CONNECT, timeoutLeft);
      
      if (ret > 0 && channel.finishConnect()) {
        return;
      }
      
      if (ret == 0 ||
          (timeout > 0 &&  
            (timeoutLeft = (endTime - System.currentTimeMillis())) <= 0)) {
        throw new SocketTimeoutException(
                  timeoutExceptionString(channel, timeout, 
                                         SelectionKey.OP_CONNECT));
      }
    }
  } catch (IOException e) {
    // javadoc for SocketChannel.connect() says channel should be closed.
    try {
      channel.close();
    } catch (IOException ignored) {}
    throw e;
  } finally {
    if (blockingOn && channel.isOpen()) {
      channel.configureBlocking(true);
    }
  }
}
 
Example 18
Source File: AdbHelper.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Runs a log service on the {@link Device}, and provides its output to the {@link LogReceiver}.
 * <p/>This call is blocking until {@link LogReceiver#isCancelled()} returns true.
 * @param adbSockAddr the socket address to connect to adb
 * @param device the Device on which to run the service
 * @param logName the name of the log file to output
 * @param rcvr the {@link LogReceiver} to receive the log output
 * @throws TimeoutException in case of timeout on the connection.
 * @throws AdbCommandRejectedException if adb rejects the command
 * @throws IOException in case of I/O error on the connection.
 */
public static void runLogService(InetSocketAddress adbSockAddr, Device device, String logName,
        LogReceiver rcvr) throws TimeoutException, AdbCommandRejectedException, IOException {
    SocketChannel adbChan = null;

    try {
        adbChan = SocketChannel.open(adbSockAddr);
        adbChan.configureBlocking(false);

        // if the device is not -1, then we first tell adb we're looking to talk
        // to a specific device
        setDevice(adbChan, device);

        byte[] request = formAdbRequest("log:" + logName);
        write(adbChan, request);

        AdbResponse resp = readAdbResponse(adbChan, false /* readDiagString */);
        if (!resp.okay) {
            throw new AdbCommandRejectedException(resp.message);
        }

        byte[] data = new byte[16384];
        ByteBuffer buf = ByteBuffer.wrap(data);
        while (true) {
            int count;

            if (rcvr != null && rcvr.isCancelled()) {
                break;
            }

            count = adbChan.read(buf);
            if (count < 0) {
                break;
            } else if (count == 0) {
                try {
                    Thread.sleep(WAIT_TIME * 5);
                } catch (InterruptedException ie) {
                }
            } else {
                if (rcvr != null) {
                    rcvr.parseNewData(buf.array(), buf.arrayOffset(), buf.position());
                }
                buf.rewind();
            }
        }
    } finally {
        if (adbChan != null) {
            adbChan.close();
        }
    }
}
 
Example 19
Source File: LotsOfCancels.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
static void closeAll(List<SocketChannel> channels)
        throws Exception {
    for (SocketChannel channel : channels) {
        channel.close();
    }
}
 
Example 20
Source File: CloseAfterConnect.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(new InetSocketAddress(0));

    InetAddress lh = InetAddress.getLocalHost();
    final SocketChannel sc = SocketChannel.open();
    final InetSocketAddress isa =
        new InetSocketAddress(lh, ssc.socket().getLocalPort());

    // establish connection in another thread
    Runnable connector =
        new Runnable() {
            public void run() {
                try {
                    sc.connect(isa);
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        };
    Thread thr = new Thread(connector);
    thr.start();

    // wait for connect to be established and for thread to
    // terminate
    do {
        try {
            thr.join();
        } catch (InterruptedException x) { }
    } while (thr.isAlive());

    // check connection is established
    if (!sc.isConnected()) {
        throw new RuntimeException("SocketChannel not connected");
    }

    // close channel - this triggered the bug as it attempted to signal
    // a thread that no longer exists
    sc.close();

    // clean-up
    ssc.accept().close();
    ssc.close();
}