List of usage examples for java.nio.channels SocketChannel isConnected
public abstract boolean isConnected();
From source file:edu.hawaii.soest.kilonalu.adcp.ADCPSource.java
/** * A method used to the TCP socket of the remote source host for communication * @param host the name or IP address of the host to connect to for the * socket connection (reading) * @param portNumber the number of the TCP port to connect to (i.e. 2604) *//* w w w . jav a2s. com*/ protected SocketChannel getSocketConnection() { String host = getHostName(); int portNumber = new Integer(getHostPort()).intValue(); SocketChannel dataSocket = null; try { // create the socket channel connection to the data source via the // converter serial2IP converter dataSocket = SocketChannel.open(); dataSocket.connect(new InetSocketAddress(host, portNumber)); // if the connection to the source fails, also disconnect from the RBNB // server and return null if (!dataSocket.isConnected()) { dataSocket.close(); disconnect(); dataSocket = null; } } catch (UnknownHostException ukhe) { System.err.println("Unable to look up host: " + host + "\n"); disconnect(); dataSocket = null; } catch (IOException nioe) { System.err.println("Couldn't get I/O connection to: " + host); disconnect(); dataSocket = null; } catch (Exception e) { disconnect(); dataSocket = null; } return dataSocket; }
From source file:com.bittorrent.mpetazzoni.client.ConnectionHandler.java
/** * Accept the next incoming connection./*from w w w . j av a2 s . co m*/ * * <p> * When a new peer connects to this service, wait for it to send its * handshake. We then parse and check that the handshake advertises the * torrent hash we expect, then reply with our own handshake. * </p> * * <p> * If everything goes according to plan, notify the * <code>IncomingConnectionListener</code>s with the connected socket and * the parsed peer ID. * </p> * * @param client The accepted client's socket channel. */ private void accept(SocketChannel client) throws IOException, SocketTimeoutException { try { logger.debug("New incoming connection, waiting for handshake..."); Handshake hs = this.validateHandshake(client, null); int sent = this.sendHandshake(client); logger.trace("Replied to {} with handshake ({} bytes).", this.socketRepr(client), sent); // Go to non-blocking mode for peer interaction client.configureBlocking(false); client.socket().setSoTimeout(CLIENT_KEEP_ALIVE_MINUTES * 60 * 1000); this.fireNewPeerConnection(client, hs.getPeerId()); } catch (ParseException pe) { logger.info("Invalid handshake from {}: {}", this.socketRepr(client), pe.getMessage()); IOUtils.closeQuietly(client); } catch (IOException ioe) { logger.warn("An error occured while reading an incoming " + "handshake: {}", ioe.getMessage()); if (client.isConnected()) { IOUtils.closeQuietly(client); } } }
From source file:edu.hawaii.soest.kilonalu.tchain.TChainSource.java
/** * A method used to the TCP socket of the remote source host for communication * @param host the name or IP address of the host to connect to for the * socket connection (reading) * @param portNumber the number of the TCP port to connect to (i.e. 2604) *///from w w w.ja va 2s .co m protected SocketChannel getSocketConnection() { String host = getHostName(); int portNumber = new Integer(getHostPort()).intValue(); SocketChannel dataSocket = null; try { // create the socket channel connection to the data source via the // converter serial2IP converter dataSocket = SocketChannel.open(); Socket tcpSocket = dataSocket.socket(); tcpSocket.setTcpNoDelay(true); tcpSocket.setReceiveBufferSize(40); dataSocket.connect(new InetSocketAddress(host, portNumber)); // if the connection to the source fails, also disconnect from the RBNB // server and return null if (!dataSocket.isConnected()) { dataSocket.close(); disconnect(); dataSocket = null; } } catch (UnknownHostException ukhe) { System.err.println("Unable to look up host: " + host + "\n"); disconnect(); dataSocket = null; } catch (IOException nioe) { System.err.println("Couldn't get I/O connection to: " + host); disconnect(); dataSocket = null; } catch (Exception e) { disconnect(); dataSocket = null; } return dataSocket; }
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 ww .j ava 2 s . c o 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:edu.hawaii.soest.kilonalu.ctd.CTDSource.java
/** * A method used to the TCP socket of the remote source host for communication * @param host the name or IP address of the host to connect to for the * socket connection (reading) * @param portNumber the number of the TCP port to connect to (i.e. 2604) *//*from w w w . j av a 2 s . c o m*/ protected SocketChannel getSocketConnection() { String host = getHostName(); int portNumber = new Integer(getHostPort()).intValue(); SocketChannel dataSocket = null; try { // create the socket channel connection to the data source via the // converter serial2IP converter dataSocket = SocketChannel.open(); dataSocket.connect(new InetSocketAddress(host, portNumber)); // if the connection to the source fails, also disconnect from the RBNB // server and return null if (!dataSocket.isConnected()) { dataSocket.close(); disconnect(); dataSocket = null; } } catch (UnknownHostException ukhe) { logger.info("Unable to look up host: " + host + "\n"); disconnect(); dataSocket = null; } catch (IOException nioe) { logger.info("Couldn't get I/O connection to: " + host); disconnect(); dataSocket = null; } catch (Exception e) { disconnect(); dataSocket = null; } return dataSocket; }
From source file:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpMultiplexer.java
protected void updateConnectInterest(NIOClientSocketHandler clientHandler, Selector selector) { SocketChannel socketChannel = clientHandler.getSocketChannel(); if (!socketChannel.isOpen()) return;/*w ww .j a va2 s . c om*/ // We are interested in connect if not already done if (!socketChannel.isConnected()) addInterest(socketChannel, SelectionKey.OP_CONNECT, clientHandler, selector); else removeInterest(socketChannel, SelectionKey.OP_CONNECT, selector); }
From source file:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpMultiplexer.java
protected void updateReadInterest(NIOClientSocketHandler clientHandler, Selector selector) { SocketChannel socketChannel = clientHandler.getSocketChannel(); if (!socketChannel.isOpen()) return;// w w w . ja va2 s .c o m if (!socketChannel.isConnected()) return; // We are interested in reading only if we have some buffer space left if (clientHandler.getInputBuffer().remaining() > 0) addInterest(socketChannel, SelectionKey.OP_READ, clientHandler, selector); else removeInterest(socketChannel, SelectionKey.OP_READ, selector); }
From source file:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpMultiplexer.java
protected void updateWriteInterest(NIOClientSocketHandler clientHandler, Selector selector) { SocketChannel socketChannel = clientHandler.getSocketChannel(); if (!socketChannel.isOpen()) return;/*ww w .j a v a2 s . c o m*/ if (!socketChannel.isConnected()) return; // We are interested in writing only if there is something in the output buffer or // the handler expresses the need to write something if (clientHandler.getOutputBuffer().position() > 0 || clientHandler.hasWriteInterest()) addInterest(socketChannel, SelectionKey.OP_WRITE, null, selector); else removeInterest(socketChannel, SelectionKey.OP_WRITE, selector); }
From source file:org.openhab.binding.tcp.AbstractSocketChannelBinding.java
/** * {@inheritDoc}//from w ww . java 2s .com */ protected void internalReceiveCommand(String itemName, Command command) { P provider = findFirstMatchingBindingProvider(itemName); if (provider == null) { logger.warn("cannot find matching binding provider [itemName={}, command={}]", itemName, command); return; } if (command != null) { List<Command> commands = provider.getQualifiedCommands(itemName, command); for (Command someCommand : commands) { Channel theChannel = null; if (useAddressMask && (((P) provider).getHost(itemName, someCommand).equals("*") || ((P) provider).getPortAsString(itemName, someCommand).equals("*"))) { theChannel = channels.get(itemName, someCommand, ((P) provider).getDirection(itemName, someCommand), ((P) provider).getHost(itemName, someCommand), ((P) provider).getPortAsString(itemName, someCommand)); } else { theChannel = channels.get(itemName, someCommand, ((P) provider).getDirection(itemName, someCommand), new InetSocketAddress(provider.getHost(itemName, someCommand), provider.getPort(itemName, someCommand))); } SocketChannel theSocketChannel = null; if (theChannel != null) { theSocketChannel = theChannel.channel; } if (theSocketChannel != null) { boolean result = internalReceiveChanneledCommand(itemName, someCommand, theChannel, command.toString()); if (!theSocketChannel.isConnected() && !(useAddressMask && (((P) provider).getHost(itemName, someCommand).equals("*") || ((P) provider).getPortAsString(itemName, someCommand).equals("*")))) { logger.warn( "The channel for {} has a connection problem. Data will queued to the new channel when it is successfully set up.", theChannel.remote); if (!theSocketChannel.isConnectionPending() || !theSocketChannel.isOpen()) { Scheduler scheduler = null; try { scheduler = StdSchedulerFactory.getDefaultScheduler(); } catch (SchedulerException e1) { logger.error("An exception occurred while getting the Quartz scheduler: {}", e1.getMessage()); } JobDataMap map = new JobDataMap(); map.put("Channel", theChannel); map.put("Binding", this); JobDetail job = newJob(ReconnectJob.class) .withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), this.toString()) .usingJobData(map).build(); Trigger trigger = newTrigger() .withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), this.toString()) .startNow().build(); try { if (job != null && trigger != null) { if (!theChannel.isReconnecting) { theChannel.isReconnecting = true; scheduler.scheduleJob(job, trigger); } } } catch (SchedulerException e) { logger.error( "An exception occurred while scheduling a job with the Quartz Scheduler {}", e.getMessage()); } } } if (result) { List<Class<? extends State>> stateTypeList = provider.getAcceptedDataTypes(itemName, someCommand); State newState = createStateFromString(stateTypeList, command.toString()); if (newState != null) { eventPublisher.postUpdate(itemName, newState); } } } else { logger.error("there is no channel that services [itemName={}, command={}]", itemName, command); } } } }
From source file:org.openhab.binding.tcp.AbstractSocketChannelBinding.java
/** * Queues (writes) a ByteBuffer to a channel * * @param theChannel the network channel * @param byteBuffer the byte buffer/*from ww w. j a v a2 s . co m*/ * @param isBlockingWriteRead set to true if we have to wait for a response from the remote end (e.g. ACK message or alike) * @param timeOut time to wait for a response from the remote end * @return a ByteBuffer with the response, if blocking operation, or the original ByteBuffer in all other cases */ protected ByteBuffer writeBuffer(ByteBuffer theBuffer, Channel theChannel, boolean isBlockingWriteRead, long timeOut) { SocketChannel theSocketChannel = theChannel.channel; if (isBlockingWriteRead) { if (theBuffer != null) { if (theSocketChannel.isConnected() || queueUntilConnected) { writeQueue.add(new WriteBufferElement(theChannel, theBuffer, true)); } long currentElapsedTimeMillis = System.currentTimeMillis(); while (theChannel.buffer == null && (System.currentTimeMillis() - currentElapsedTimeMillis) < timeOut) { try { Thread.sleep(100); } catch (InterruptedException e) { logger.warn("Exception occurred while waiting waiting during a blocking buffer write"); } } ByteBuffer responseBuffer = null; synchronized (this) { responseBuffer = theChannel.buffer; theChannel.buffer = null; theChannel.isBlocking = false; } return responseBuffer; } else { return theBuffer; } } else { if (theBuffer != null) { if (theSocketChannel.isConnected() || queueUntilConnected) { writeQueue.add(new WriteBufferElement(theChannel, theBuffer, false)); } } return theBuffer; } }