Example usage for java.nio.channels SocketChannel open

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

Introduction

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

Prototype

public static SocketChannel open() throws IOException 

Source Link

Document

Opens a socket channel.

Usage

From source file:org.apache.gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

@Test(enabled = false, timeOut = 15000)
public void testTunnelToEchoServerMultiRequest() throws IOException {
    MockServer proxyServer = startConnectProxyServer();
    Tunnel tunnel = Tunnel.build("localhost", doubleEchoServer.getServerSocketPort(), "localhost",
            proxyServer.getServerSocketPort());

    try {// w  ww  . ja v a2 s. c  o m
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

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

        client.write(ByteBuffer.wrap("Hello\n".getBytes()));
        String response2 = readFromSocket(client);

        client.close();

        assertEquals(response1, "Knock Knock\n");
        assertEquals(response2, "Hello Hello\n");
        assertEquals(proxyServer.getNumConnects(), 1);
    } finally {
        proxyServer.stopServer();
        tunnel.close();
        assertFalse(tunnel.isTunnelThreadAlive());
    }
}

From source file:org.cryptomator.ui.util.SingleInstanceManager.java

/**
 * Checks if there is a valid port at/*ww  w. ja  v a 2  s.c  o m*/
 * {@link Preferences#userNodeForPackage(Class)} for {@link Main} under the
 * given applicationKey, tries to connect to the port at the loopback
 * address and checks if the port identifies with the applicationKey.
 * 
 * @param applicationKey
 *            key used to load the port and check the identity of the
 *            connection.
 * @return
 */
public static Optional<RemoteInstance> getRemoteInstance(String applicationKey) {
    Optional<Integer> port = getSavedPort(applicationKey);

    if (!port.isPresent()) {
        return Optional.empty();
    }

    SocketChannel channel = null;
    boolean close = true;
    try {
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        LOG.info("connecting to instance {}", port.get());
        channel.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), port.get()));

        SocketChannel fChannel = channel;
        if (!TimeoutTask.attempt(t -> fChannel.finishConnect(), 1000, 10)) {
            return Optional.empty();
        }

        LOG.info("connected to instance {}", port.get());

        final byte[] bytes = applicationKey.getBytes();
        ByteBuffer buf = ByteBuffer.allocate(bytes.length);
        tryFill(channel, buf, 1000);
        if (buf.hasRemaining()) {
            return Optional.empty();
        }

        buf.flip();

        for (int i = 0; i < bytes.length; i++) {
            if (buf.get() != bytes[i]) {
                return Optional.empty();
            }
        }

        close = false;
        return Optional.of(new RemoteInstance(channel));
    } catch (Exception e) {
        return Optional.empty();
    } finally {
        if (close) {
            IOUtils.closeQuietly(channel);
        }
    }
}

From source file:HttpDownloadManager.java

public void run() {
    log.info("HttpDownloadManager thread starting.");

    // The download thread runs until release() is called
    while (!released) {
        // The thread blocks here waiting for something to happen
        try {/*  ww w  .j  a va 2s  .c  o m*/
            selector.select();
        } catch (IOException e) {
            // This should never happen.
            log.log(Level.SEVERE, "Error in select()", e);
            return;
        }

        // If release() was called, the thread should exit.
        if (released)
            break;

        // If any new Download objects are pending, deal with them first
        if (!pendingDownloads.isEmpty()) {
            // Although pendingDownloads is a synchronized list, we still
            // need to use a synchronized block to iterate through its
            // elements to prevent a concurrent call to download().
            synchronized (pendingDownloads) {
                Iterator iter = pendingDownloads.iterator();
                while (iter.hasNext()) {
                    // Get the pending download object from the list
                    DownloadImpl download = (DownloadImpl) iter.next();
                    iter.remove(); // And remove it.

                    // Now begin an asynchronous connection to the
                    // specified host and port. We don't block while
                    // waiting to connect.
                    SelectionKey key = null;
                    SocketChannel channel = null;
                    try {
                        // Open an unconnected channel
                        channel = SocketChannel.open();
                        // Put it in non-blocking mode
                        channel.configureBlocking(false);
                        // Register it with the selector, specifying that
                        // we want to know when it is ready to connect
                        // and when it is ready to read.
                        key = channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT,
                                download);
                        // Create the web server address
                        SocketAddress address = new InetSocketAddress(download.host, download.port);
                        // Ask the channel to start connecting
                        // Note that we don't send the HTTP request yet.
                        // We'll do that when the connection completes.
                        channel.connect(address);
                    } catch (Exception e) {
                        handleError(download, channel, key, e);
                    }
                }
            }
        }

        // Now get the set of keys that are ready for connecting or reading
        Set keys = selector.selectedKeys();
        if (keys == null)
            continue; // bug workaround; should not be needed
        // Loop through the keys in the set
        for (Iterator i = keys.iterator(); i.hasNext();) {
            SelectionKey key = (SelectionKey) i.next();
            i.remove(); // Remove the key from the set before handling

            // Get the Download object we attached to the key
            DownloadImpl download = (DownloadImpl) key.attachment();
            // Get the channel associated with the key.
            SocketChannel channel = (SocketChannel) key.channel();

            try {
                if (key.isConnectable()) {
                    // If the channel is ready to connect, complete the
                    // connection and then send the HTTP GET request to it.
                    if (channel.finishConnect()) {
                        download.status = Status.CONNECTED;
                        // This is the HTTP request we wend
                        String request = "GET " + download.path + " HTTP/1.1\r\n" + "Host: " + download.host
                                + "\r\n" + "Connection: close\r\n" + "\r\n";
                        // Wrap in a CharBuffer and encode to a ByteBuffer
                        ByteBuffer requestBytes = LATIN1.encode(CharBuffer.wrap(request));
                        // Send the request to the server. If the bytes
                        // aren't all written in one call, we busy loop!
                        while (requestBytes.hasRemaining())
                            channel.write(requestBytes);

                        log.info("Sent HTTP request: " + download.host + ":" + download.port + ": " + request);
                    }
                }
                if (key.isReadable()) {
                    // If the key indicates that there is data to be read,
                    // then read it and store it in the Download object.
                    int numbytes = channel.read(buffer);

                    // If we read some bytes, store them, otherwise
                    // the download is complete and we need to note this
                    if (numbytes != -1) {
                        buffer.flip(); // Prepare to drain the buffer
                        download.addData(buffer); // Store the data
                        buffer.clear(); // Prepare for another read
                        log.info("Read " + numbytes + " bytes from " + download.host + ":" + download.port);
                    } else {
                        // If there are no more bytes to read
                        key.cancel(); // We're done with the key
                        channel.close(); // And with the channel.
                        download.status = Status.DONE;
                        if (download.listener != null) // notify listener
                            download.listener.done(download);
                        log.info("Download complete from " + download.host + ":" + download.port);
                    }
                }
            } catch (Exception e) {
                handleError(download, channel, key, e);
            }
        }
    }
    log.info("HttpDownloadManager thread exiting.");
}

From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

private void runClientToTalkFirstServer(int tunnelPort) throws IOException {
    SocketChannel client = SocketChannel.open();

    client.connect(new InetSocketAddress("localhost", tunnelPort));
    String response0 = readFromSocket(client);
    LOG.info(response0);/* w w  w .j a  va  2s  .  c om*/

    client.write(ByteBuffer.wrap("Knock\n".getBytes()));
    String response1 = readFromSocket(client);
    LOG.info(response1);

    client.write(ByteBuffer.wrap("Hello\n".getBytes()));
    String response2 = readFromSocket(client);
    LOG.info(response2);

    client.close();

    assertEquals(response0, "Hello\n");
    assertEquals(response1, "Knock Knock\n");
    assertEquals(response2, "Hello Hello\n");
}

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

private void establishConnection() {
    lock.lock();//from   w  ww.  java 2 s .  c o  m
    try {
        if (getConfig().get(IP_ADDRESS) != null && getConfig().get(PORT_NUMBER) != null) {
            try {
                socketChannel = SocketChannel.open();
                socketChannel.socket().setKeepAlive(true);
                socketChannel.configureBlocking(false);

                synchronized (selector) {
                    selector.wakeup();
                    int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT;
                    socketChannelKey = socketChannel.register(selector, interestSet);
                }

                InetSocketAddress remoteAddress = new InetSocketAddress((String) getConfig().get(IP_ADDRESS),
                        ((BigDecimal) getConfig().get(PORT_NUMBER)).intValue());
                socketChannel.connect(remoteAddress);
            } catch (IOException e) {
                logger.debug("An exception occurred while connecting to '{}:{}' : {}",
                        getConfig().get(IP_ADDRESS), ((BigDecimal) getConfig().get(PORT_NUMBER)).intValue(),
                        e.getMessage());
                updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
            }

            try {
                Thread.sleep(((BigDecimal) getConfig().get(RESPONSE_TIME_OUT)).intValue());
            } catch (NumberFormatException | InterruptedException e) {
                Thread.currentThread().interrupt();
                logger.debug("An exception occurred while putting a thread to sleep: '{}'", e.getMessage());
                updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
            }
            onConnectable();
        }
    } finally {
        lock.unlock();
    }
}

From source file:org.onlab.nio.service.IOLoopMessaging.java

/**
 * Initiates open connection request and registers the pending socket
 * channel with the given IO loop.//from  www .j a v a  2 s.  c  o m
 *
 * @param loop loop with which the channel should be registered
 * @throws java.io.IOException if the socket could not be open or connected
 */
private DefaultMessageStream createConnection(Endpoint ep, DefaultIOLoop loop) throws IOException {
    SocketAddress sa = new InetSocketAddress(ep.host().toString(), ep.port());
    SocketChannel ch = SocketChannel.open();
    ch.configureBlocking(false);
    DefaultMessageStream stream = loop.connectStream(ch);
    ch.connect(sa);
    return stream;
}

From source file:hornet.framework.clamav.service.ClamAVCheckService.java

/**
 * Ouverture de la socket.//from  w w  w. j  a  v  a  2s . co  m
 *
 * @return la socket
 * @throws ClamAVException
 *             the clam av exception
 */
private SocketChannel openSocket() throws ClamAVException {

    SocketChannel channel = null;
    try {
        // Rcuperation de la socket depuis le pool
        channel = this.socketPool.borrowObject();

        if (!channel.isOpen()) {
            channel = SocketChannel.open();
        }
        if (!channel.isConnected()) {
            channel.configureBlocking(true);
            channel.connect(new InetSocketAddress(this.clamAVServer, this.clamAVPort));
        }
    } catch (final Exception e) {
        ClamAVCheckService.LOGGER.error("Unable to borrow socket from pool", e);
        throw new ClamAVException(ERR_TEC_CLAMAV_01, new String[] { e.getMessage() }, e);
    }

    return channel;
}

From source file:de.tum.in.socket.client.SocketClient.java

/**
 * Process the receiving of data from server
 *///from w  ww . ja  va2 s . com
private void doProcess(final KuraResponsePayload respPayload) throws KuraException {
    this.m_activityLogService.saveLog("Socket Communication Started");

    String message = null;
    try {
        if (isNull(this.channel)) {
            this.channel = SocketChannel.open();
        }

        // we open this channel in non blocking mode
        if (!isNull(this.channel) && this.channel.isOpen() && !this.channel.isConnected()) {
            this.channel.configureBlocking(false);
            this.channel.connect(new InetSocketAddress(this.m_socketIPAddress, this.m_socketPort));
        }

        while (!this.channel.finishConnect()) {
            // No need to log. Still connecting to server.
        }
        while (!Thread.currentThread().isInterrupted()) {
            final ByteBuffer bufferA = ByteBuffer.allocate(500);
            message = "";
            while ((this.channel.read(bufferA)) > 0) {
                bufferA.flip();
                message += Charset.defaultCharset().decode(bufferA);
            }
            if (message.length() > 0) {
                LOGGER.info("Message Received: " + message);
            }
            if (!Strings.isNullOrEmpty(message)) {
                this.doPublish(respPayload, message);
            }
        }
    } catch (final Exception e) {
        LOGGER.error(Throwables.getStackTraceAsString(e));
    }
}

From source file:org.apache.hadoop.hdfs.web.TestWebHdfsTimeouts.java

/**
 * Consumes the test server's connection backlog by spamming non-blocking
 * SocketChannel client connections.  We never do anything with these sockets
 * beyond just initiaing the connections.  The method saves a reference to each
 * new SocketChannel so that it can be closed during tearDown.  We define a
 * very small connection backlog, but the OS may silently enforce a larger
 * minimum backlog than requested.  To work around this, we create far more
 * client connections than our defined backlog.
 * //from w ww .  j  a  v  a2  s  .c  o  m
 * @throws IOException thrown for any I/O error
 */
private void consumeConnectionBacklog() throws IOException {
    for (int i = 0; i < CLIENTS_TO_CONSUME_BACKLOG; ++i) {
        SocketChannel client = SocketChannel.open();
        client.configureBlocking(false);
        client.connect(nnHttpAddress);
        clients.add(client);
    }
}

From source file:org.eclipsetrader.directa.internal.core.BrokerConnector.java

@Override
public void run() {
    Selector socketSelector;//from  w  ww .j a va 2  s.c  om
    ByteBuffer dst = ByteBuffer.wrap(new byte[2048]);
    List<Position> positions = new ArrayList<Position>();

    try {
        // Create a non-blocking socket channel
        socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);

        socketChannel.socket().setReceiveBufferSize(32768);
        socketChannel.socket().setSoLinger(true, 1);
        socketChannel.socket().setSoTimeout(0x15f90);
        socketChannel.socket().setReuseAddress(true);

        // Kick off connection establishment
        socketChannel.connect(new InetSocketAddress(server, port));

        // Create a new selector
        socketSelector = SelectorProvider.provider().openSelector();

        // Register the server socket channel, indicating an interest in
        // accepting new connections
        socketChannel.register(socketSelector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT);
    } catch (Exception e) {
        Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error connecting to orders monitor", //$NON-NLS-1$
                e);
        Activator.log(status);
        return;
    }

    for (;;) {
        try {
            if (socketSelector.select(30 * 1000) == 0) {
                logger.trace(">" + HEARTBEAT); //$NON-NLS-1$
                socketChannel.write(ByteBuffer.wrap(new String(HEARTBEAT + "\r\n").getBytes())); //$NON-NLS-1$
            }
        } catch (Exception e) {
            break;
        }

        // Iterate over the set of keys for which events are available
        Iterator<SelectionKey> selectedKeys = socketSelector.selectedKeys().iterator();
        while (selectedKeys.hasNext()) {
            SelectionKey key = selectedKeys.next();
            selectedKeys.remove();

            if (!key.isValid()) {
                continue;
            }

            try {
                // Check what event is available and deal with it
                if (key.isConnectable()) {
                    // Finish the connection. If the connection operation failed
                    // this will raise an IOException.
                    try {
                        socketChannel.finishConnect();
                    } catch (IOException e) {
                        // Cancel the channel's registration with our selector
                        key.cancel();
                        return;
                    }

                    // Register an interest in writing on this channel
                    key.interestOps(SelectionKey.OP_WRITE);
                }
                if (key.isWritable()) {
                    logger.trace(">" + LOGIN + WebConnector.getInstance().getUser()); //$NON-NLS-1$
                    socketChannel.write(ByteBuffer.wrap(
                            new String(LOGIN + WebConnector.getInstance().getUser() + "\r\n").getBytes())); //$NON-NLS-1$

                    // Register an interest in reading on this channel
                    key.interestOps(SelectionKey.OP_READ);
                }
                if (key.isReadable()) {
                    dst.clear();
                    int readed = socketChannel.read(dst);
                    if (readed > 0) {
                        String[] s = new String(dst.array(), 0, readed).split("\r\n"); //$NON-NLS-1$
                        for (int i = 0; i < s.length; i++) {
                            logger.trace("<" + s[i]); //$NON-NLS-1$

                            if (s[i].endsWith(";" + WebConnector.getInstance().getUser() + ";")) { //$NON-NLS-1$ //$NON-NLS-2$
                                logger.trace(">" + UNKNOWN70); //$NON-NLS-1$
                                socketChannel.write(ByteBuffer.wrap(new String(UNKNOWN70 + "\r\n").getBytes())); //$NON-NLS-1$
                                logger.trace(">" + UNKNOWN55); //$NON-NLS-1$
                                socketChannel.write(ByteBuffer.wrap(new String(UNKNOWN55 + "\r\n").getBytes())); //$NON-NLS-1$
                            }

                            if (s[i].indexOf(";6;5;") != -1 || s[i].indexOf(";8;0;") != -1) { //$NON-NLS-1$ //$NON-NLS-2$
                                try {
                                    OrderMonitor monitor = parseOrderLine(s[i]);

                                    OrderDelta[] delta;
                                    synchronized (orders) {
                                        if (!orders.contains(monitor)) {
                                            orders.add(monitor);
                                            delta = new OrderDelta[] {
                                                    new OrderDelta(OrderDelta.KIND_ADDED, monitor) };
                                        } else {
                                            delta = new OrderDelta[] {
                                                    new OrderDelta(OrderDelta.KIND_UPDATED, monitor) };
                                        }
                                    }
                                    fireUpdateNotifications(delta);

                                    if (monitor.getFilledQuantity() != null
                                            && monitor.getAveragePrice() != null) {
                                        Account account = WebConnector.getInstance().getAccount();
                                        account.updatePosition(monitor);
                                    }
                                } catch (ParseException e) {
                                    Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0,
                                            "Error parsing line: " + s[i], e); //$NON-NLS-1$
                                    Activator.log(status);
                                }
                            }
                            if (s[i].indexOf(";6;0;") != -1) { //$NON-NLS-1$
                                updateStatusLine(s[i]);
                            }
                            if (s[i].indexOf(";7;0;") != -1) { //$NON-NLS-1$
                                try {
                                    positions.add(new Position(s[i]));
                                } catch (Exception e) {
                                    Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0,
                                            "Error parsing line: " + s[i], e); //$NON-NLS-1$
                                    Activator.log(status);
                                }
                            }
                            if (s[i].indexOf(";7;9;") != -1) { //$NON-NLS-1$
                                Account account = WebConnector.getInstance().getAccount();
                                account.setPositions(positions.toArray(new Position[positions.size()]));
                                positions.clear();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Connection error", e); //$NON-NLS-1$
                Activator.log(status);
            }
        }
    }
}