List of usage examples for java.nio.channels SocketChannel configureBlocking
public final SelectableChannel configureBlocking(boolean block) throws IOException
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 va2s .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.apache.hadoop.mapred.buffer.net.BufferExchangeSink.java
/** Open the sink for incoming connections. */ public void open() { /* Create a new thread for accepting new connections. */ this.acceptor = new Thread() { public void run() { try { while (server.isOpen()) { LOG.info("in server open"); SocketChannel channel = server.accept(); channel.configureBlocking(true); /* Note: no buffered input stream due to memory pressure. */ DataInputStream istream = new DataInputStream(channel.socket().getInputStream()); DataOutputStream ostream = new DataOutputStream( new BufferedOutputStream(channel.socket().getOutputStream())); LOG.info("server is open"); if (complete()) { WritableUtils.writeEnum(ostream, Connect.BUFFER_COMPLETE); ostream.close(); } else if (handlers.size() > maxConnections) { LOG.info("Connections full. connections = " + handlers.size() + ", max allowed " + maxConnections); WritableUtils.writeEnum(ostream, Connect.CONNECTIONS_FULL); ostream.close(); } else { WritableUtils.writeEnum(ostream, Connect.OPEN); ostream.flush(); BufferExchange.BufferType type = WritableUtils.readEnum(istream, BufferExchange.BufferType.class); Handler handler = null; if (BufferType.FILE == type) { handler = new FileHandler(collector, istream, ostream); } else if (BufferType.SNAPSHOT == type) { handler = new SnapshotHandler(collector, istream, ostream); } else if (BufferType.STREAM == type) { handler = new StreamHandler(collector, istream, ostream); } else if (BufferType.ITERATE == type) { handler = new IterateHandler(collector, istream, ostream); } else { LOG.error("Unknown buffer type " + type); channel.close(); continue; }/*from ww w . j a v a 2s. co m*/ LOG.info("JBufferSink: " + ownerid + " opening connection."); handlers.add(handler); executor.execute(handler); } } LOG.info("JBufferSink " + ownerid + " buffer response server closed."); } catch (IOException e) { if (!complete()) { e.printStackTrace(); } } } }; acceptor.setDaemon(true); acceptor.setPriority(Thread.MAX_PRIORITY); acceptor.start(); }
From source file:org.apache.htrace.impl.PackedBufferManager.java
private SelectionKey doConnect() throws IOException { SocketChannel sock = SocketChannel.open(); SelectionKey sockKey = null;/* w ww. j a v a2 s. co m*/ 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.apache.james.imap.tester.builder.ScriptBuilder.java
public static ScriptBuilder open(String host, int port) throws Exception { InetSocketAddress address = new InetSocketAddress(host, port); SocketChannel socket = SocketChannel.open(address); socket.configureBlocking(false); Client client = new Client(socket, socket); return new ScriptBuilder(client); }
From source file:org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher.java
@Override public void run() { while (!stopped) { try {/*from w w w.j a v a 2 s.c o m*/ int selected = selector.select(); // if stopped the selector could already be closed which would result in a ClosedSelectorException if (selected > 0 && !stopped) { Iterator<SelectionKey> selectorKeys = selector.selectedKeys().iterator(); // if stopped we don't want to modify the keys because close() may still be in progress while (selectorKeys.hasNext() && !stopped) { SelectionKey key = selectorKeys.next(); selectorKeys.remove(); if (!key.isValid()) { continue; } if (key.isAcceptable()) { // Handle new connections coming in final ServerSocketChannel channel = (ServerSocketChannel) key.channel(); final SocketChannel socketChannel = channel.accept(); // Check for available connections if (currentConnections.incrementAndGet() > maxConnections) { currentConnections.decrementAndGet(); logger.warn("Rejecting connection from {} because max connections has been met", new Object[] { socketChannel.getRemoteAddress().toString() }); IOUtils.closeQuietly(socketChannel); continue; } logger.debug("Accepted incoming connection from {}", new Object[] { socketChannel.getRemoteAddress().toString() }); // Set socket to non-blocking, and register with selector socketChannel.configureBlocking(false); SelectionKey readKey = socketChannel.register(selector, SelectionKey.OP_READ); // Prepare the byte buffer for the reads, clear it out ByteBuffer buffer = bufferPool.poll(); buffer.clear(); buffer.mark(); // If we have an SSLContext then create an SSLEngine for the channel SSLSocketChannel sslSocketChannel = null; if (sslContext != null) { final SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(false); switch (clientAuth) { case REQUIRED: sslEngine.setNeedClientAuth(true); break; case WANT: sslEngine.setWantClientAuth(true); break; case NONE: sslEngine.setNeedClientAuth(false); sslEngine.setWantClientAuth(false); break; } sslSocketChannel = new SSLSocketChannel(sslEngine, socketChannel); } // Attach the buffer and SSLSocketChannel to the key SocketChannelAttachment attachment = new SocketChannelAttachment(buffer, sslSocketChannel); readKey.attach(attachment); } else if (key.isReadable()) { // Clear out the operations the select is interested in until done reading key.interestOps(0); // Create a handler based on the protocol and whether an SSLEngine was provided or not final Runnable handler; if (sslContext != null) { handler = handlerFactory.createSSLHandler(key, this, charset, eventFactory, events, logger); } else { handler = handlerFactory.createHandler(key, this, charset, eventFactory, events, logger); } // run the handler executor.execute(handler); } } } // Add back all idle sockets to the select SelectionKey key; while ((key = keyQueue.poll()) != null) { key.interestOps(SelectionKey.OP_READ); } } catch (IOException e) { logger.error("Error accepting connection from SocketChannel", e); } } }
From source file:org.commoncrawl.io.internal.NIOClientTCPSocket.java
private static void setClientSocketOptions(SocketChannel channel) throws IOException { channel.socket().setPerformancePreferences(0, 1, 3); channel.socket().setTcpNoDelay(true); probeAndSetSize(false, 2 << 16, 2 << 10, channel); probeAndSetSize(true, 2 << 15, 2 << 10, channel); channel.configureBlocking(false); }
From source file:org.commoncrawl.io.internal.NIOServerTCPSocket.java
private static void setClientSocketOptions(SocketChannel channel) throws IOException { channel.socket().setTcpNoDelay(true); channel.configureBlocking(false); }
From source file:org.commoncrawl.io.NIOClientTCPSocket.java
private static void setClientSocketOptions(SocketChannel channel) throws IOException { channel.socket().setPerformancePreferences(0, 1, 3); channel.socket().setTcpNoDelay(true); channel.socket().setSoLinger(false, 0); channel.socket().setKeepAlive(true); probeAndSetSize(false, 2 << 16, 2 << 10, channel); probeAndSetSize(true, 2 << 15, 2 << 10, channel); channel.configureBlocking(false); }
From source file:org.cryptomator.ui.util.SingleInstanceManager.java
/** * Checks if there is a valid port at/*from w ww . j av a2s . com*/ * {@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:org.gcaldaemon.core.ldap.LDAPListener.java
public final void run() { log.info("LDAP server started successfully."); // Create variables SelectionKey key, newKey;// w ww .j a v a 2 s . c o m SocketChannel channel; Socket socket = null; Iterator keys; int n; // Server loop for (;;) { try { // Select sockets try { socket = null; n = selector.select(); } catch (NullPointerException closedError) { // Ignore Selector bug - client socket closed if (log.isDebugEnabled()) { log.debug("Socket closed.", closedError); } continue; } catch (ClosedSelectorException interrupt) { break; } catch (Exception selectError) { // Unknown exception - stop server log.warn("Unable to select sockets!", selectError); break; } if (n != 0) { // Get an iterator over the set of selected keys keys = selector.selectedKeys().iterator(); if (keys == null) { continue; } // Look at each key in the selected set while (keys.hasNext()) { key = (SelectionKey) keys.next(); keys.remove(); // Nothing to do if (key == null) { continue; } // Check key status if (key.isValid()) { // Accept new incoming connection if (key.isAcceptable()) { channel = serverChannel.accept(); if (channel != null) { // Register new socket connection socket = channel.socket(); channel.configureBlocking(false); newKey = channel.register(selector, SelectionKey.OP_READ); processAccept(newKey); } } else { if (key.isReadable()) { // Read from socket connection socket = ((SocketChannel) key.channel()).socket(); processRead(key); } else { // Write to socket connection if (key.isWritable()) { socket = ((SocketChannel) key.channel()).socket(); processWrite(key); } } } } } } } catch (InterruptedException interrupt) { closeSocket(socket); break; } catch (IOException socketClosed) { closeSocket(socket); continue; } catch (Exception processingException) { closeSocket(socket); log.warn(processingException.getMessage(), processingException); } } log.info("LDAP server stopped."); }