Java Code Examples for java.nio.channels.SocketChannel#isOpen()
The following examples show how to use
java.nio.channels.SocketChannel#isOpen() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractSession.java From Mycat2 with GNU General Public License v3.0 | 6 votes |
/** * todo: check that code is right * * @return */ public boolean checkOpen() { SocketChannel channel = channel(); boolean open = !hasClosed() && channel.isOpen() && channel.isConnected(); if (open) { ByteBuffer allocate = ByteBuffer.allocate(0); boolean close; try { close = -1 == channel.read(allocate); } catch (IOException e) { close = true; } if (close) { this.close(false, "check open"); return false; } return true; } return false; }
Example 2
Source File: RequestReader.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
public void sendReply(ByteBuffer reply) throws IOException { // for binary set the response opCode if (this.protocol == Protocol.BINARY) { reply.rewind(); reply.put(POSITION_OPCODE, oneRequest.get(POSITION_OPCODE)); reply.putInt(POSITION_OPAQUE, oneRequest.getInt(POSITION_OPAQUE)); if (ConnectionHandler.getLogger().finerEnabled()) { ConnectionHandler.getLogger().finer("sending reply:"+reply+" "+Command.buffertoString(reply)); } } SocketChannel channel = this.socket.getChannel(); if (channel == null || !channel.isOpen()) { throw new IllegalStateException("cannot write to channel"); } channel.write(reply); }
Example 3
Source File: ROSBridgeWebSocketClient.java From ROSBridgeClient with GNU General Public License v3.0 | 6 votes |
@Override public void closeBlocking() throws InterruptedException { super.closeBlocking(); try { Field channelField = this.getClass().getSuperclass().getDeclaredField("channel"); channelField.setAccessible(true); SocketChannel channel = (SocketChannel) channelField.get(this); if (channel != null && channel.isOpen()) { Socket socket = channel.socket(); if (socket != null) socket.close(); } } catch (Exception ex) { System.out.println("Exception in Websocket close hack."); ex.printStackTrace(); } }
Example 4
Source File: PeerConnectionFactory.java From bt with Apache License 2.0 | 6 votes |
private void closeQuietly(SocketChannel channel) { if (channel != null && channel.isOpen()) { try { channel.close(); } catch (IOException e1) { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Failed to close outgoing channel: {}. Reason: {} ({})", channel.getRemoteAddress(), e1.getClass().getName(), e1.getMessage()); } } catch (IOException e2) { // ignore } } } }
Example 5
Source File: ClearVolumeTCPServerSinkRunnable.java From clearvolume with GNU Lesser General Public License v3.0 | 6 votes |
private void sendVolumeToClient(SocketChannel lSocketChannel, Volume lVolumeToSend, boolean pReleaseOrForward) throws IOException { mByteBuffer = ClearVolumeSerialization.serialize( lVolumeToSend, mByteBuffer); mByteBuffer.rewind(); if (lSocketChannel.isConnected() && lSocketChannel.isOpen()) { while (mByteBuffer.hasRemaining()) lSocketChannel.write(mByteBuffer); if (pReleaseOrForward) { if (mClearVolumeTCPServerSink.getRelaySink() == null) lVolumeToSend.makeAvailableToManager(); else mClearVolumeTCPServerSink.getRelaySink() .sendVolume(lVolumeToSend); } } }
Example 6
Source File: RequestReader.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
public void sendException(Exception e) { SocketChannel channel = this.socket.getChannel(); if (channel == null || !channel.isOpen()) { throw new IllegalStateException("cannot write to channel"); } try { if (e instanceof ClientError) { channel.write(charsetASCII.encode(Reply.CLIENT_ERROR.toString())); } else { channel.write(charsetASCII.encode(Reply.ERROR.toString())); } } catch (IOException ex) { } }
Example 7
Source File: AsynchronousTlsChannel.java From tls-channel with MIT License | 5 votes |
/** * Initializes a new instance of this class. * * @param channelGroup group to associate new new channel to * @param tlsChannel existing TLS channel to be used asynchronously * @param socketChannel underlying socket * @throws ClosedChannelException if any of the underlying channels are closed. * @throws IllegalArgumentException is the socket is in blocking mode */ public AsynchronousTlsChannel( AsynchronousTlsChannelGroup channelGroup, TlsChannel tlsChannel, SocketChannel socketChannel) throws ClosedChannelException, IllegalArgumentException { if (!tlsChannel.isOpen() || !socketChannel.isOpen()) { throw new ClosedChannelException(); } if (socketChannel.isBlocking()) { throw new IllegalArgumentException("socket channel must be in non-blocking mode"); } this.group = channelGroup; this.tlsChannel = tlsChannel; this.registeredSocket = channelGroup.registerSocket(tlsChannel, socketChannel); }
Example 8
Source File: RequestReader.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
private Command readAsciiCommand() throws IOException { SocketChannel channel = this.socket.getChannel(); if (channel == null || !channel.isOpen()) { throw new IllegalStateException("cannot read from channel"); } buffer.clear(); channel.read(buffer); buffer.flip(); oneRequest = buffer.duplicate(); return Command.valueOf(readCommand(oneRequest)); }
Example 9
Source File: RequestReader.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
public void sendException(Exception e) { SocketChannel channel = this.socket.getChannel(); if (channel == null || !channel.isOpen()) { throw new IllegalStateException("cannot write to channel"); } try { if (e instanceof ClientError) { channel.write(charsetASCII.encode(Reply.CLIENT_ERROR.toString())); } else { channel.write(charsetASCII.encode(Reply.ERROR.toString())); } } catch (IOException ex) { } }
Example 10
Source File: NioSocketChannel.java From netty4.0.27Learn with Apache License 2.0 | 4 votes |
@Override public boolean isActive() { SocketChannel ch = javaChannel(); return ch.isOpen() && ch.isConnected(); }
Example 11
Source File: NioSocketChannel.java From netty-4.1.22 with Apache License 2.0 | 4 votes |
@Override public boolean isActive() { SocketChannel ch = javaChannel(); return ch.isOpen() && ch.isConnected(); }
Example 12
Source File: AbstractSocketChannelBinding.java From openhab1-addons with Eclipse Public License 2.0 | 4 votes |
/** * {@inheritDoc} */ @Override 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 && (provider.getHost(itemName, someCommand).equals("*") || provider.getPortAsString(itemName, someCommand).equals("*"))) { theChannel = channels.get(itemName, someCommand, provider.getDirection(itemName, someCommand), provider.getHost(itemName, someCommand), provider.getPortAsString(itemName, someCommand)); } else { theChannel = channels.get(itemName, someCommand, 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 && (provider.getHost(itemName, someCommand).equals("*") || provider.getPortAsString(itemName, someCommand).equals("*")))) { logger.warn( "The channel for {} has a connection problem. Data will be 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.warn("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.warn( "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.warn("There is no channel that services [itemName={}, command={}]", itemName, command); } } } }
Example 13
Source File: SocketIOWithTimeout.java From big-c with Apache License 2.0 | 4 votes |
/** * The contract is similar to {@link SocketChannel#connect(SocketAddress)} * with a timeout. * * @see SocketChannel#connect(SocketAddress) * * @param channel - this should be a {@link SelectableChannel} * @param endpoint * @throws IOException */ static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException { boolean blockingOn = channel.isBlocking(); if (blockingOn) { channel.configureBlocking(false); } try { if (channel.connect(endpoint)) { return; } long timeoutLeft = timeout; long endTime = (timeout > 0) ? (Time.now() + timeout): 0; while (true) { // we might have to call finishConnect() more than once // for some channels (with user level protocols) int ret = selector.select((SelectableChannel)channel, SelectionKey.OP_CONNECT, timeoutLeft); if (ret > 0 && channel.finishConnect()) { return; } if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - Time.now())) <= 0)) { throw new SocketTimeoutException( timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT)); } } } catch (IOException e) { // javadoc for SocketChannel.connect() says channel should be closed. try { channel.close(); } catch (IOException ignored) {} throw e; } finally { if (blockingOn && channel.isOpen()) { channel.configureBlocking(true); } } }
Example 14
Source File: NetworkHandler.java From RipplePower with Apache License 2.0 | 4 votes |
/** * Closes a peer connection and discards any pending messages * * @param peer * The peer being closed */ private void closeConnection(Peer peer) { PeerAddress address = peer.getAddress(); SocketChannel channel = peer.getChannel(); try { // // Disconnect the peer // peer.setInputBuffer(null); peer.setOutputBuffer(null); peer.setDeferredMessage(null); peer.getOutputList().clear(); if (address.isOutbound()) outboundCount--; address.setConnected(false); address.setOutbound(false); peer.setConnected(false); synchronized (connections) { connections.remove(peer); connectionMap.remove(address.getAddress()); } if (!address.isStatic()) { synchronized (BTCLoader.peerAddresses) { BTCLoader.peerAddresses.remove(address); BTCLoader.peerMap.remove(address); } } // // Ban the peer if necessary // synchronized (peer) { if (peer.getBanScore() >= BTCLoader.MAX_BAN_SCORE && !isBlacklisted(address.getAddress())) { peerBlacklist.add(new BlacklistEntry(address.getAddress(), -1)); BTCLoader.info(String.format("Peer address %s banned", address.getAddress().getHostAddress())); } } // // Notify listeners that a connection has ended // if (peer.getVersionCount() > 2) { for (ConnectionListener listener : connectionListeners) { listener.connectionEnded(peer, connections.size()); } } // // Close the channel // if (channel.isOpen()) channel.close(); BTCLoader.info(String.format("Connection closed with peer %s", address)); } catch (IOException exc) { BTCLoader.error(String.format("Error while closing socket channel with %s", address), exc); } }
Example 15
Source File: SocketIOWithTimeout.java From hadoop-gpu with Apache License 2.0 | 4 votes |
/** * The contract is similar to {@link SocketChannel#connect(SocketAddress)} * with a timeout. * * @see SocketChannel#connect(SocketAddress) * * @param channel - this should be a {@link SelectableChannel} * @param endpoint * @throws IOException */ static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException { boolean blockingOn = channel.isBlocking(); if (blockingOn) { channel.configureBlocking(false); } try { if (channel.connect(endpoint)) { return; } long timeoutLeft = timeout; long endTime = (timeout > 0) ? (System.currentTimeMillis() + timeout): 0; while (true) { // we might have to call finishConnect() more than once // for some channels (with user level protocols) int ret = selector.select((SelectableChannel)channel, SelectionKey.OP_CONNECT, timeoutLeft); if (ret > 0 && channel.finishConnect()) { return; } if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - System.currentTimeMillis())) <= 0)) { throw new SocketTimeoutException( timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT)); } } } catch (IOException e) { // javadoc for SocketChannel.connect() says channel should be closed. try { channel.close(); } catch (IOException ignored) {} throw e; } finally { if (blockingOn && channel.isOpen()) { channel.configureBlocking(true); } } }
Example 16
Source File: SocketIOWithTimeout.java From hadoop with Apache License 2.0 | 4 votes |
/** * The contract is similar to {@link SocketChannel#connect(SocketAddress)} * with a timeout. * * @see SocketChannel#connect(SocketAddress) * * @param channel - this should be a {@link SelectableChannel} * @param endpoint * @throws IOException */ static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException { boolean blockingOn = channel.isBlocking(); if (blockingOn) { channel.configureBlocking(false); } try { if (channel.connect(endpoint)) { return; } long timeoutLeft = timeout; long endTime = (timeout > 0) ? (Time.now() + timeout): 0; while (true) { // we might have to call finishConnect() more than once // for some channels (with user level protocols) int ret = selector.select((SelectableChannel)channel, SelectionKey.OP_CONNECT, timeoutLeft); if (ret > 0 && channel.finishConnect()) { return; } if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - Time.now())) <= 0)) { throw new SocketTimeoutException( timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT)); } } } catch (IOException e) { // javadoc for SocketChannel.connect() says channel should be closed. try { channel.close(); } catch (IOException ignored) {} throw e; } finally { if (blockingOn && channel.isOpen()) { channel.configureBlocking(true); } } }
Example 17
Source File: HASendService.java From database with GNU General Public License v2.0 | 4 votes |
/** * (Re-)open the {@link SocketChannel} if it is closed and this service is * still running. * * @return The {@link SocketChannel}. */ private SocketChannel reopenChannel() { /* * Synchronize on the socketChannel object to serialize attempts to open * the SocketChannel. */ synchronized (socketChannel) { int tryno = 0; SocketChannel sc = null; while ((((sc = socketChannel.get()) == null) || !sc.isOpen()) && isRunning()) { try { /* * (Re-)open the SocketChannel. * * TODO we may have to retry or play with the timeout for * the socket connect request since the downstream node may * see its pipelineAdd() after the upstream node sees its * pipelineChange() event. For example, given a pipeline * [A], when service B joins the pipeline using * [B.getActor().pipelineAdd()] the following are possible * sequences in which the events could be delivered to A and * B. * * Option 1: * * B.pipelineAdd(); A.pipelineChange(null,B); * * Option 2: * * A.pipelineChange(null,B); B.pipelineAdd(); * * In option (1), we should be able to connect immediately * since B will have already setup its receive service. * However, in option (2), we can not connect immediately * since B does not setup its receive service until after A * has seen the pipelineChange() event. */ socketChannel.set(sc = openChannel(addrNext.get())); if (log.isInfoEnabled()) log.info("Opened channel on try: " + tryno + ", addrNext=" + addrNext); } catch (IOException e) { if (log.isInfoEnabled()) log.info("Failed to open channel on try: " + tryno + ", addrNext=" + addrNext); if (tryno < retryMillis.length) { try { // sleep and retry. Thread.sleep(retryMillis[tryno]); tryno++; continue; } catch (InterruptedException e1) { // rethrow original exception. throw new RuntimeException(e); } } // do not wrap. throw new RuntimeException(e); } // catch } // while return socketChannel.get(); } // synchronized(socketChannel) }
Example 18
Source File: SocketIOWithTimeout.java From stratosphere with Apache License 2.0 | 4 votes |
/** * The contract is similar to {@link SocketChannel#connect(SocketAddress)} with a timeout. * * @see SocketChannel#connect(SocketAddress) * @param channel * - this should be a {@link SelectableChannel} * @param endpoint * @throws IOException */ static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException { boolean blockingOn = channel.isBlocking(); if (blockingOn) { channel.configureBlocking(false); } try { if (channel.connect(endpoint)) { return; } long timeoutLeft = timeout; long endTime = (timeout > 0) ? (System.currentTimeMillis() + timeout) : 0; while (true) { // we might have to call finishConnect() more than once // for some channels (with user level protocols) int ret = selector.select((SelectableChannel) channel, SelectionKey.OP_CONNECT, timeoutLeft); if (ret > 0 && channel.finishConnect()) { return; } if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - System.currentTimeMillis())) <= 0)) { throw new SocketTimeoutException(timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT)); } } } catch (IOException e) { // javadoc for SocketChannel.connect() says channel should be closed. try { channel.close(); } catch (IOException ignored) { } throw e; } finally { if (blockingOn && channel.isOpen()) { channel.configureBlocking(true); } } }
Example 19
Source File: NetOutput.java From NetKnight with Apache License 2.0 | 2 votes |
/** * 传递实际的数据 * * @param tcb */ private void transData(String ipAndPort, TCB tcb, Packet currentPacket, ByteBuffer dataBuffer, ByteBuffer responseBuffer) { //1.发送ACK码 2.传递真实数据 int payloadSize = dataBuffer.limit() - dataBuffer.position(); //对tcb加锁,防止其有变动 synchronized (tcb) { if (tcb.tcbStatus == TCB.TCB_STATUS_LAST_ACK) { //关闭通道 MyLog.logd(this, "close channel"); TCBCachePool.closeTCB(ipAndPort); return; } //无数据的直接ignore了 if (payloadSize == 0) { MyLog.logd(this, "-------ack has no data-------"); return; } MyLog.logd(this, "传递的payloadSize为:" + payloadSize); //发送完数据咯,那么就执行真正的数据访问 SelectionKey outKey = tcb.selectionKey; if (outKey == null) { MyLog.logd(this, "outKey 为 null"); return; } //监听读的状态咯 if (tcb.tcbStatus == TCB.TCB_STATUS_SYN_RECEIVED) { tcb.tcbStatus = TCB.TCB_STATUS_ESTABLISHED; } else if (tcb.tcbStatus == TCB.TCB_STATUS_ESTABLISHED) { MyLog.logd(this, "establish ing"); } else { MyLog.logd(this, "当前tcbStatus为" + tcb.tcbStatus); MyLog.logd(this, "连接还没建立好"); return; } SocketChannel outChannel = (SocketChannel) outKey.channel(); if (outChannel.isConnected() && outChannel.isOpen()) { MyLog.logd(this, "执行写channel操作"); try { while (dataBuffer.hasRemaining()) { outChannel.write(dataBuffer); } //记录发送数据 tcb.calculateTransBytes(payloadSize); } catch (IOException e) { e.printStackTrace(); MyLog.logd(this, "write data error"); //失败就告知连接中断 sendRST(tcb, ipAndPort, payloadSize, responseBuffer); } } else { MyLog.logd(this, "channel都没准备好"); } currentPacket.swapSourceAndDestination(); tcb.myAcknowledgementNum = currentPacket.tcpHeader.sequenceNumber + payloadSize; currentPacket.updateTCPBuffer(responseBuffer, (byte) Packet.TCPHeader.ACK, tcb.mySequenceNum, tcb.myAcknowledgementNum, 0); MyLog.logd(this, "transData responseBuffer limit:" + responseBuffer.limit() + " position:" + responseBuffer.position()); } PCapFilter.filterPacket(responseBuffer, tcb.getAppId()); //ack码 mOutputQueue.offer(responseBuffer); }
Example 20
Source File: GelfTCPSSLSender.java From xian with Apache License 2.0 | 2 votes |
protected boolean isConnected() throws IOException { SocketChannel socketChannel = channel(); return socketChannel != null && socketChannel.isOpen() && isConnected(socketChannel); }