Example usage for java.nio.channels SocketChannel configureBlocking

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

Introduction

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

Prototype

public final SelectableChannel configureBlocking(boolean block) throws IOException 

Source Link

Document

Adjusts this channel's blocking mode.

Usage

From source file:idgs.client.TcpClient.java

/**
 * //from w ww  .ja  v  a2 s .  co  m
 * @param timeout
 * @param retryTimes
 * @throws IOException
 */
public boolean connect(final boolean enableTimeoutCheck, final int timeout, final int retryTimes) {
    if (enableTimeoutCheck) {
        if (retryTimes <= 0) { // up to re-try times
            return isConnected();
        }
        Timer timer = new Timer(); // after timeout seconds, run timer task, if not connected, re-try again
        timer.schedule(new TimerTask() {
            public void run() {
                if (!isConnected()) {
                    int newRetryTimes = retryTimes - 1;
                    connect(enableTimeoutCheck, timeout, newRetryTimes);
                }
            }
        }, timeout);
    }
    try {
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.register(selector, SelectionKey.OP_CONNECT);
        channel.connect(servAddr);
        select();
    } catch (IOException e) {
        log.warn("try to connecte to server[" + servAddr.toString() + "] error, " + e.getMessage());
    }
    return isConnected();
}

From source file:co.elastic.tealess.SSLChecker.java

private SSLReport check(InetSocketAddress address, String name, long timeout) {
    SSLReport sslReport = new SSLReport();
    sslReport.setSSLContextBuilder(ctxbuilder);
    sslReport.setSSLContext(ctx);// w w  w.j  a  v  a2  s  . com
    sslReport.setHostname(name);
    sslReport.setAddress(address);
    sslReport.setTimeout(timeout);

    logger.debug("Trying {} (expected hostname {})", address, name);
    SocketChannel socket;
    try {
        socket = SocketChannel.open();
        socket.configureBlocking(false);
    } catch (IOException e) {
        sslReport.setFailed(e);
        return sslReport;
    }

    checkConnect(sslReport, socket, timeout);
    if (sslReport.getException() != null) {
        return sslReport;
    }

    checkHandshake(sslReport, socket);
    if (sslReport.getException() != null) {
        return sslReport;
    }

    checkHostnameVerification(sslReport);
    return sslReport;
}

From source file:org.reunionemu.jreunion.server.Network.java

private void processAccept(SocketChannel socketChannel) throws IOException {

    socketChannel.configureBlocking(false);

    fireEvent(NetworkAcceptEvent.class, socketChannel);

    // Register it with the selector, for reading
    selector.wakeup();//  ww  w.  j  a va2 s.  c  o m
    socketChannel.register(selector, SelectionKey.OP_READ);

}

From source file:gridool.util.xfer.RecievedFileWriter.java

public final void handleRequest(@Nonnull final SocketChannel inChannel, @Nonnull final Socket socket)
        throws IOException {
    final StopWatch sw = new StopWatch();
    if (!inChannel.isBlocking()) {
        inChannel.configureBlocking(true);
    }/*from  www.j  a  v a  2 s.  co  m*/

    InputStream in = socket.getInputStream();
    DataInputStream dis = new DataInputStream(in);

    String fname = IOUtils.readString(dis);
    String dirPath = IOUtils.readString(dis);
    long len = dis.readLong();
    boolean append = dis.readBoolean();
    boolean ackRequired = dis.readBoolean();
    boolean hasAdditionalHeader = dis.readBoolean();
    if (hasAdditionalHeader) {
        readAdditionalHeader(dis, fname, dirPath, len, append, ackRequired);
    }

    final File file;
    if (dirPath == null) {
        file = new File(baseDir, fname);
    } else {
        File dir = FileUtils.resolvePath(baseDir, dirPath);
        file = new File(dir, fname);
    }

    preFileAppend(file, append);
    final FileOutputStream dst = new FileOutputStream(file, append);
    final String fp = file.getAbsolutePath();
    final ReadWriteLock filelock = accquireLock(fp, locks);
    final FileChannel fileCh = dst.getChannel();
    final long startPos = file.length();
    try {
        NIOUtils.transferFully(inChannel, 0, len, fileCh); // REVIEWME really an atomic operation?
    } finally {
        IOUtils.closeQuietly(fileCh, dst);
        releaseLock(fp, filelock, locks);
        postFileAppend(file, startPos, len);
    }
    if (ackRequired) {
        OutputStream out = socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(out);
        dos.writeLong(len);
        postAck(file, startPos, len);
    }

    if (LOG.isDebugEnabled()) {
        SocketAddress remoteAddr = socket.getRemoteSocketAddress();
        LOG.debug("Received a " + (append ? "part of file '" : "file '") + file.getAbsolutePath() + "' of "
                + len + " bytes from " + remoteAddr + " in " + sw.toString());
    }
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnectionThread.java

@Override
public void run() {

    while (!isInterrupted()) {

        synchronized (this.pendingConnectionRequests) {

            if (!this.pendingConnectionRequests.isEmpty()) {

                final OutgoingConnection outgoingConnection = this.pendingConnectionRequests.poll();
                try {
                    final SocketChannel socketChannel = SocketChannel.open();
                    socketChannel.configureBlocking(false);
                    final SelectionKey key = socketChannel.register(this.selector, SelectionKey.OP_CONNECT);
                    socketChannel.connect(outgoingConnection.getConnectionAddress());
                    key.attach(outgoingConnection);
                } catch (final IOException ioe) {
                    // IOException is reported by separate thread to avoid deadlocks
                    final Runnable reporterThread = new Runnable() {

                        @Override
                        public void run() {
                            outgoingConnection.reportConnectionProblem(ioe);
                        }//from w  w  w. ja  va  2  s.  c  o m
                    };
                    new Thread(reporterThread).start();
                }
            }
        }

        synchronized (this.pendingWriteEventSubscribeRequests) {

            if (!this.pendingWriteEventSubscribeRequests.isEmpty()) {
                final SelectionKey oldSelectionKey = this.pendingWriteEventSubscribeRequests.poll();
                final OutgoingConnection outgoingConnection = (OutgoingConnection) oldSelectionKey.attachment();
                final SocketChannel socketChannel = (SocketChannel) oldSelectionKey.channel();

                try {
                    final SelectionKey newSelectionKey = socketChannel.register(this.selector,
                            SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                    newSelectionKey.attach(outgoingConnection);
                    outgoingConnection.setSelectionKey(newSelectionKey);
                } catch (final IOException ioe) {
                    // IOException is reported by separate thread to avoid deadlocks
                    final Runnable reporterThread = new Runnable() {

                        @Override
                        public void run() {
                            outgoingConnection.reportTransmissionProblem(ioe);
                        }
                    };
                    new Thread(reporterThread).start();
                }
            }
        }

        synchronized (this.connectionsToClose) {

            final Iterator<Map.Entry<OutgoingConnection, Long>> closeIt = this.connectionsToClose.entrySet()
                    .iterator();
            final long now = System.currentTimeMillis();
            while (closeIt.hasNext()) {

                final Map.Entry<OutgoingConnection, Long> entry = closeIt.next();
                if ((entry.getValue().longValue() + MIN_IDLE_TIME_BEFORE_CLOSE) < now) {
                    final OutgoingConnection outgoingConnection = entry.getKey();
                    closeIt.remove();
                    // Create new thread to close connection to avoid deadlocks
                    final Runnable closeThread = new Runnable() {

                        @Override
                        public void run() {
                            try {
                                outgoingConnection.closeConnection();
                            } catch (IOException ioe) {
                                outgoingConnection.reportTransmissionProblem(ioe);
                            }
                        }
                    };

                    new Thread(closeThread).start();
                }

            }
        }

        try {
            this.selector.select(10);
        } catch (IOException e) {
            LOG.error(e);
        }

        final Iterator<SelectionKey> iter = this.selector.selectedKeys().iterator();

        while (iter.hasNext()) {
            final SelectionKey key = iter.next();

            iter.remove();
            if (key.isValid()) {
                if (key.isConnectable()) {
                    doConnect(key);
                } else {
                    if (key.isReadable()) {
                        doRead(key);
                        // A read will always result in an exception, so the write key will not be valid anymore
                        continue;
                    }
                    if (key.isWritable()) {
                        doWrite(key);
                    }
                }
            } else {
                LOG.error("Received invalid key: " + key);
            }
        }
    }

    // Finally, try to close the selector
    try {
        this.selector.close();
    } catch (IOException ioe) {
        LOG.debug(StringUtils.stringifyException(ioe));
    }
}

From source file:jp.queuelinker.system.net.SelectorThread.java

public int connectChannel(final SocketAddress remoteAddress, final SelectorCallBack callBack)
        throws IOException {
    SocketChannel socketChannel = SocketChannel.open(remoteAddress);
    socketChannel.configureBlocking(false);
    // socketChannel.socket().setTcpNoDelay(true);
    socketChannel.socket().setReuseAddress(true);
    return addSocketChannel(socketChannel, callBack);
}

From source file:org.sonews.daemon.sync.SynchronousNNTPDaemon.java

@Override
public void run() {
    try {/*  w w w .j  a  v a2s  .  com*/
        Log.get().log(Level.INFO, "Server listening on port {0}", port);

        // Create a Selector that handles the SocketChannel multiplexing
        final Selector readSelector = Selector.open();
        final Selector writeSelector = Selector.open();

        // Start working threads
        final int workerThreads = Math.max(4, 2 * Runtime.getRuntime().availableProcessors());
        ConnectionWorker[] cworkers = new ConnectionWorker[workerThreads];
        for (int n = 0; n < workerThreads; n++) {
            cworkers[n] = new ConnectionWorker();
            cworkers[n].start();
        }
        Log.get().log(Level.INFO, "{0} worker threads started.", workerThreads);

        ChannelWriter.getInstance().setSelector(writeSelector);
        ChannelReader.getInstance().setSelector(readSelector);
        ChannelWriter.getInstance().start();
        ChannelReader.getInstance().start();

        final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(true); // Set to blocking mode

        // Configure ServerSocket; bind to socket...
        serverSocket = serverSocketChannel.socket();
        serverSocket.bind(new InetSocketAddress(this.port));

        while (isRunning()) {
            SocketChannel socketChannel;

            try {
                // As we set the server socket channel to blocking mode the
                // accept()
                // method will block.
                socketChannel = serverSocketChannel.accept();
                socketChannel.configureBlocking(false);
                assert socketChannel.isConnected();
                assert socketChannel.finishConnect();
            } catch (IOException ex) {
                // Under heavy load an IOException "Too many open files may
                // be thrown. It most cases we should slow down the
                // connection accepting, to give the worker threads some
                // time to process work.
                Log.get().log(Level.SEVERE, "IOException while accepting connection: {0}", ex.getMessage());
                Log.get().info("Connection accepting sleeping for seconds...");
                Thread.sleep(5000); // 5 seconds
                continue;
            }

            //FIXME conn should be NNTPConnection
            final SynchronousNNTPConnection conn = (SynchronousNNTPConnection) context
                    .getBean("syncNNTPConnection", NNTPConnection.class);
            conn.setChannelWrapper(new SocketChannelWrapperFactory(socketChannel).create());
            Connections.getInstance().add(conn);

            try {
                SelectionKey selKeyWrite = registerSelector(writeSelector, socketChannel,
                        SelectionKey.OP_WRITE);
                registerSelector(readSelector, socketChannel, SelectionKey.OP_READ);

                Log.get().log(Level.INFO, "Connected: {0}", socketChannel.socket().getRemoteSocketAddress());

                // Set write selection key and send hello to client
                conn.setWriteSelectionKey(selKeyWrite);
                conn.println("200 " + Config.inst().get(Config.HOSTNAME, "localhost") + " <unknown version>" // + Application.VERSION
                        + " news server ready - (posting ok).");
            } catch (CancelledKeyException cke) {
                Log.get().log(Level.WARNING, "CancelledKeyException {0} was thrown: {1}",
                        new Object[] { cke.getMessage(), socketChannel.socket() });
            } catch (ClosedChannelException cce) {
                Log.get().log(Level.WARNING, "ClosedChannelException {0} was thrown: {1}",
                        new Object[] { cce.getMessage(), socketChannel.socket() });
            }
        }
    } catch (BindException ex) {
        // Could not bind to socket; this is a fatal, so perform a shutdown
        Log.get().log(Level.SEVERE, ex.getLocalizedMessage() + " -> shutdown sonews", ex);
        setRunning(false);
    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkServer.java

/**
 * ?, ?Session, ?Session, // w  ww  . j a v  a  2s  . c o  m
 * Session?
 * @param key
 * @throws IOException
 */
private void onAccept(SelectionKey key) throws IOException {
    SocketChannel channel = ((ServerSocketChannel) key.channel()).accept();
    opsChangeRequstMap.put(channel, new SocketChannelOPSChangeRequest(channel, 0));
    if (logger.isWarnEnabled())
        logger.warn("Accept client from : " + channel.socket().getRemoteSocketAddress());
    channel.configureBlocking(false);
    Session session = sessionManager.newSession(this, channel, false);
    channel.register(selector, SelectionKey.OP_READ, session);
    session.start();
}

From source file:jp.queuelinker.system.net.SelectorThread.java

@Override
public void run() {
    ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
    // I believe the inner try-catches does not cause overhead.
    // http://stackoverflow.com/questions/141560/
    long sendCount = 0;

    SocketChannel currentChannel;
    SelectionKey key = null;//from   ww w .j a  v  a 2 s . c  o  m
    while (true) {
        try {
            selector.select();
            // selector.selectNow();
        } catch (ClosedSelectorException e) {
            logger.fatal("BUG: The selector is closed.");
            return;
        } catch (IOException e) {
            logger.fatal("An IOException occured while calling select().");
            // Fatal Error. Notify the error to the users and leave the matter to them.
            for (ChannelState state : channels) {
                state.callBack.fatalError();
            }
            return;
        }

        if (!requests.isEmpty()) {
            handleRequest();
            continue;
        }

        if (stopRequested) {
            return;
        }

        Set<SelectionKey> keys = selector.selectedKeys();

        Iterator<SelectionKey> iter = keys.iterator();
        iter_loop: while (iter.hasNext()) {
            key = iter.next();
            iter.remove(); // Required. Don't remove.

            if (key.isReadable()) {
                currentChannel = (SocketChannel) key.channel();
                final ChannelState state = (ChannelState) key.attachment();

                int valid;
                try {
                    valid = currentChannel.read(buffer);
                } catch (IOException e) {
                    logger.warn("An IOException happened while reading from a channel.");
                    state.callBack.exceptionOccured(state.channelId, state.attachment);
                    key.cancel();
                    continue;
                }
                if (valid == -1) {
                    // Normal socket close?
                    state.callBack.exceptionOccured(state.channelId, state.attachment);
                    // cleanUpChannel(state.channelId);
                    key.cancel();
                    continue;
                }

                buffer.rewind();
                if (state.callBack.receive(state.channelId, buffer, valid, state.attachment) == false) {
                    state.key.interestOps(state.key.interestOps() & ~SelectionKey.OP_READ);
                }
                buffer.clear();
            } else if (key.isWritable()) {
                currentChannel = (SocketChannel) key.channel();
                final ChannelState state = (ChannelState) key.attachment();

                while (state.sendBuffer.readableSize() < WRITE_SIZE) {
                    ByteBuffer newBuffer = state.callBack.send(state.channelId, state.attachment);
                    if (newBuffer != null) {
                        state.sendBuffer.write(newBuffer);
                        if (++sendCount % 50000 == 0) {
                            logger.info("Send Count: " + sendCount);
                        }
                    } else if (state.sendBuffer.readableSize() == 0) {
                        key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
                        continue iter_loop;
                    } else {
                        break;
                    }
                }

                final int available = state.sendBuffer.readableSize();
                if (available >= WRITE_SIZE || ++state.noopCount >= HEURISTIC_WAIT) {
                    int done;
                    try {
                        done = currentChannel.write(state.sendBuffer.getByteBuffer());
                    } catch (IOException e) {
                        logger.warn("An IOException occured while writing to a channel.");
                        state.callBack.exceptionOccured(state.channelId, state.attachment);
                        key.cancel();
                        continue;
                    }
                    if (done < available) {
                        state.sendBuffer.rollback(available - done);
                    }
                    state.sendBuffer.compact();
                    state.noopCount = 0;
                }
            } else if (key.isAcceptable()) {
                ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                ChannelState state = (ChannelState) key.attachment();
                SocketChannel socketChannel;
                try {
                    socketChannel = channel.accept();
                    socketChannel.configureBlocking(false);
                } catch (IOException e) {
                    continue; // Do nothing.
                }
                state.callBack.newConnection(state.channelId, socketChannel, state.attachment);
            }
        }
    }
}

From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

@Test(expectedExceptions = IOException.class)
public void testTunnelWhereProxyConnectionToServerFailsWithWriteFirstClient()
        throws IOException, InterruptedException {
    MockServer proxyServer = startConnectProxyServer();
    final int nonExistentPort = 54321; // hope this doesn't exist!
    Tunnel tunnel = Tunnel.build("localhost", nonExistentPort, "localhost", proxyServer.getServerSocketPort());
    try {//ww  w. ja v  a  2s.  c o m
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.configureBlocking(true);
        client.connect(new InetSocketAddress("localhost", tunnelPort));
        // Might have to write multiple times before connection error propagates back from proxy through tunnel to client
        for (int i = 0; i < 5; i++) {
            client.write(ByteBuffer.wrap("Knock\n".getBytes()));
            Thread.sleep(100);
        }
        String response1 = readFromSocket(client);
        LOG.info(response1);

        client.close();

    } finally {
        proxyServer.stopServer();
        tunnel.close();
        assertFalse(tunnel.isTunnelThreadAlive());
        assertEquals(proxyServer.getNumConnects(), 1);
    }
}