List of usage examples for java.nio.channels SocketChannel finishConnect
public abstract boolean finishConnect() throws IOException;
From source file:gridool.communication.transport.tcp.GridNonBlockingClient.java
public void sendMessage(SocketAddress sockAddr, GridCommunicationMessage msg) throws GridException { final SocketChannel channel; try {// ww w . j a va 2 s .com channel = SocketChannel.open(); channel.configureBlocking(false); } catch (IOException e) { LOG.error(PrintUtils.prettyPrintStackTrace(e, -1)); throw new GridException(e); } final Socket socket = channel.socket(); try { socket.connect(sockAddr); // wait for connect succeeds while (!channel.finishConnect()) { try { Thread.sleep(1000L); } catch (InterruptedException e) { ; } } } catch (IOException e) { IOUtils.closeQuietly(channel); NetUtils.closeQuietly(socket); LOG.error(PrintUtils.prettyPrintStackTrace(e, -1)); throw new GridException(e); } final ByteBuffer buf = toBuffer(msg); if (LOG.isDebugEnabled()) { LOG.debug("Sending a GridCommunicationMessage [" + msg.getMessageId() + " (" + buf.remaining() + " bytes)] to a node [" + sockAddr + "] using a channel [" + channel + ']'); } final int written; try { written = NIOUtils.countingWriteFully(channel, buf); NetUtils.shutdownOutputQuietly(socket); // terminate socket output (send FIN) } catch (IOException ioe) { final String errmsg = "Failed to send a GridCommunicationMessage [" + msg + "] to host [" + sockAddr + ']'; LOG.error(errmsg, ioe); throw new GridException(errmsg, ioe); } catch (Throwable e) { LOG.fatal(e.getMessage(), e); throw new GridException("Unexpected exception was caused", e); } finally { NetUtils.closeQuietly(socket); } if (LOG.isDebugEnabled()) { LOG.debug("Succeeded to send a GridCommunicationMessage (" + written + " bytes) to host [" + sockAddr + "]"); } }
From source file:com.byteatebit.nbserver.simple.client.SimpleNbClient.java
public void tcpConnect(String remoteHost, int remotePort, IClientSocketChannelHandler socketChannelHandler, long timeout) throws IOException { if (!initialized.get()) throw new IllegalStateException("SimpleNbClient must first be initialized via init()"); SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); InetSocketAddress address = new InetSocketAddress(remoteHost, remotePort); INbContext nbContext = new NbContext(simpleNbService.getSelectorRegistrarBalancer().getSelectorRegistrar(), simpleNbService.getScheduler()); IOTask connectTask = (selectionKey) -> { boolean connectionFinished = false; try {//from ww w . ja va 2s . co m connectionFinished = socketChannel.finishConnect(); } catch (IOException e) { LOG.error("Could not complete socket connection.", e); } if (!connectionFinished) { LOG.error("Could not complete socket connection. Closing socket channel"); selectionKey.cancel(); IOUtils.closeQuietly(socketChannel); socketChannelHandler.connectFailed(remoteHost, remotePort); return; } selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_CONNECT); socketChannelHandler.accept(nbContext, socketChannel); }; IOTimeoutTask timeoutTask = (selectionKey, ops) -> { LOG.error("Connect attempt timed out after " + timeout + " ms"); selectionKey.cancel(); IOUtils.closeQuietly(socketChannel); socketChannelHandler.connectFailed(remoteHost, remotePort); }; nbContext.register(socketChannel, SelectionKey.OP_CONNECT, connectTask, timeoutTask, timeout); socketChannel.connect(address); }
From source file:org.sonews.daemon.sync.SynchronousNNTPDaemon.java
@Override public void run() { try {/*from w ww . j a va2 s . c o m*/ 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:co.elastic.tealess.SSLChecker.java
private void checkConnect(SSLReport sslReport, SocketChannel socket, long timeout) { final InetSocketAddress address = sslReport.getAddress(); try {/*from w w w .j a v a 2 s.c o m*/ logger.trace("Connecting to {}", address); Selector selector = Selector.open(); SelectionKey sk = socket.register(selector, SelectionKey.OP_CONNECT); socket.connect(address); selector.select(timeout); if (!sk.isConnectable()) { sslReport.setFailed(new SocketTimeoutException()); return; } if (socket.isConnectionPending()) { socket.finishConnect(); } } catch (ConnectException e) { logger.debug("Connection failed to {}: {}", address, e); sslReport.setFailed(e); return; } catch (IOException e) { logger.error("Failed connecting to {}: {}", address, e); sslReport.setFailed(e); return; } logger.debug("Connection successful to {}", address); }
From source file:com.mobicage.rpc.newxmpp.XMPPConfigurationFactory.java
public ConnectionConfiguration getSafeXmppConnectionConfiguration(final String xmppServiceName, final String email, final boolean hasFailed) throws XMPPConfigurationException { debuglog("Creating new XMPP connection"); if (!mConnectivityManager.isConnected()) { debuglog("No network."); throw new XMPPConfigurationException("No network."); }//from w w w.j av a2 s. co m final ConnectionConfiguration xmppConfig; if (hasFailed) { debuglog("Getting config from cloud because previous connection attempt failed."); xmppConfig = getBasicXMPPConfigurationFromCloud(xmppServiceName, email); } else { debuglog("Getting config from config provider."); ConnectionConfiguration tmpXmppConfig = getBasicXMPPConfigurationFromConfigProvider(xmppServiceName); if (tmpXmppConfig == null) { debuglog("Getting config from cloud because config provider is empty."); xmppConfig = getBasicXMPPConfigurationFromCloud(xmppServiceName, email); } else xmppConfig = tmpXmppConfig; } if (xmppConfig == null) { debuglog("No xmpp configuration found."); throw new XMPPConfigurationException("No xmpp configuration found."); } final HostAddress[] hostAddresses = xmppConfig.getHosts(); if (hostAddresses.length == 0) { debuglog("Error: did not receive any XMPP DNS SRV record"); throw new XMPPConfigurationException("Did not find any XMPP DNS SRV record"); } else if (hostAddresses.length == 1 && xmppServiceName.equals(hostAddresses[0].getHost()) && XMPP_DEFAULT_PORT == hostAddresses[0].getPort()) { buglog("Using fallback value for DNS SRV (but network is up): " + hostAddresses[0]); } debuglog("Found XMPP DNS SRV records:"); for (int i = hostAddresses.length - 1; i >= 0; i--) { debuglog("- host = " + hostAddresses[i]); } final int preferredXMPPPort = hostAddresses[hostAddresses.length - 1].getPort(); debuglog("Preferred XMPP port is " + preferredXMPPPort); // Do non-blocking TCP connect attempts Map<HostAddress, SocketChannel> allChannels = new HashMap<HostAddress, SocketChannel>(); Map<HostAddress, SocketChannel> remainingChannels = new HashMap<HostAddress, SocketChannel>(); for (int i = hostAddresses.length - 1; i >= 0; i--) { final HostAddress ha = hostAddresses[i]; try { SocketChannel sChannel = SocketChannel.open(); allChannels.put(ha, sChannel); sChannel.configureBlocking(false); sChannel.connect(new InetSocketAddress(ha.getHost(), ha.getPort())); remainingChannels.put(ha, sChannel); } catch (IOException e) { // Cannot connect to one socket ; let's not drop others debuglog("Ignoring socket due to connection error: " + ha); } } if (remainingChannels.size() == 0) { debuglog("Error: could not connect to any of the XMPP DNS SRV records"); debuglog("Closing attempted TCP sockets"); for (SocketChannel sc : allChannels.values()) { try { sc.close(); } catch (IOException e) { } } debuglog("All attempted TCP sockets are closed now"); throw new XMPPConfigurationException("Error: could not connect to any of the XMPP DNS SRV records"); } final long starttime = SystemClock.elapsedRealtime(); HostAddress goodHostAddress = null; while (true) { Iterator<Entry<HostAddress, SocketChannel>> iter = remainingChannels.entrySet().iterator(); while (iter.hasNext()) { Entry<HostAddress, SocketChannel> e = iter.next(); final HostAddress ha = e.getKey(); final SocketChannel sc = e.getValue(); try { if (sc.finishConnect()) { if (sc.isConnected()) { debuglog("Successful TCP connection to " + ha); iter.remove(); if (goodHostAddress != null) { // We already found a host // Pick this better one only if the one we found already was not using the // preferred XMPP port, and the new one does have the preferred XMPP port if (goodHostAddress.getPort() != preferredXMPPPort && ha.getPort() == preferredXMPPPort) { goodHostAddress = ha; debuglog("Found better host " + goodHostAddress); } else { debuglog("Old host was better: " + goodHostAddress); } } else { goodHostAddress = ha; debuglog("Selecting host " + goodHostAddress); } } else { debuglog("Failed TCP connection to " + ha); iter.remove(); } } } catch (IOException ex) { // Error during finishConnect() debuglog("TCP connection timeout to " + ha); iter.remove(); } } final long now = SystemClock.elapsedRealtime(); if (goodHostAddress != null && goodHostAddress.getPort() == preferredXMPPPort) { debuglog("Found responsive XMPP host with preferred port " + preferredXMPPPort); break; } if (remainingChannels.size() == 0) { debuglog("No more XMPP hosts to check"); break; } if (now > starttime + XMPP_MAX_CONNECT_MILLIS) { debuglog("Timeout trying to find responsive XMPP host"); break; } if (goodHostAddress != null) { if (now > starttime + XMPP_MAX_TRY_PREFERRED_PORT_MILLIS) { // XXX: would be better to wait at most N seconds (e.g. 2) AFTER the first successful connection // happened (to a non preferred port) debuglog("Give up looking for responsive XMPP host with preferred port."); break; } boolean stillWaitingForConnectionWithPreferredPort = false; for (HostAddress ha : remainingChannels.keySet()) { if (ha.getPort() == preferredXMPPPort) { stillWaitingForConnectionWithPreferredPort = true; break; } } if (!stillWaitingForConnectionWithPreferredPort) { debuglog("No more responsive XMPP hosts with preferred port to wait for."); break; } } debuglog("Sleeping " + XMPP_POLLING_INTERVAL_MILLIS + "ms while trying to connect to XMPP"); try { Thread.sleep(XMPP_POLLING_INTERVAL_MILLIS); } catch (InterruptedException ex) { throw new XMPPConfigurationException("Interrupt during Thread.sleep()"); } } debuglog("Closing attempted TCP sockets"); for (SocketChannel sc : allChannels.values()) { try { sc.close(); } catch (IOException e) { } } debuglog("All attempted TCP sockets are closed now"); if (goodHostAddress == null) { debuglog("Did not find a good host address and hasfailed: " + hasFailed); clearSRVConfig(); if (hasFailed) throw new XMPPConfigurationException("Could not connect to any of the XMPP targets"); else return getSafeXmppConnectionConfiguration(xmppServiceName, email, true); } debuglog("Using XMPP host " + goodHostAddress); xmppConfig.setHosts(new HostAddress[] { goodHostAddress }); return xmppConfig; }
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 {//from ww w.j a v a 2s. co 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:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpMultiplexer.java
protected boolean finalizeConnect(NIOClientSocketHandler clientHandler, SocketChannel channel, Selector selector) {/*from ww w . jav a2s . c o m*/ try { // Finish the connection handshake channel.finishConnect(); log.debug("[" + clientHandler.getId() + "] Connected to " + channel.socket().getInetAddress()); // Unregister connect interest removeInterest(channel, SelectionKey.OP_CONNECT, selector); return true; } catch (SocketException e) { log.error("[" + clientHandler.getId() + "] Could not connect to remote server : " + e.getMessage()); return false; } catch (Exception e) { log.error("[" + clientHandler.getId() + "] Could not finalize connection", e); return false; } }
From source file:net.ymate.platform.serv.nio.support.NioEventProcessor.java
protected void __doConnectEvent(SelectionKey key) throws IOException { INioSession _session = (INioSession) key.attachment(); if (_session != null) { SocketChannel _channel = (SocketChannel) key.interestOps(0).channel(); if (_channel.finishConnect()) { _session.finishConnect();/*from w w w . ja va 2 s. c om*/ } _session.selectionKey(key); _session.status(ISession.Status.CONNECTED); __eventGroup.listener().onSessionConnected(_session); } }
From source file:org.apache.htrace.impl.PackedBufferManager.java
private SelectionKey doConnect() throws IOException { SocketChannel sock = SocketChannel.open(); SelectionKey sockKey = null;/* ww w . j a va 2 s .c om*/ 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.cryptomator.ui.util.SingleInstanceManager.java
/** * Checks if there is a valid port at/*ww w . j a v a 2 s . co 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); } } }