Java Code Examples for java.nio.channels.SocketChannel#isConnected()
The following examples show how to use
java.nio.channels.SocketChannel#isConnected() .
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: GfxdTSocket.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
/** * Constructor that takes an already created socket. * * @param socket * Already created socket object * @param params * Socket parameters including buffer sizes and keep-alive settings * @param props * the system properties instance to use and initialize global socket * options like keepalive and buffer sizes that are not set in params * * @throws TTransportException * if there is an error setting up the streams */ public GfxdTSocket(SocketChannel socketChannel, boolean blocking, int timeout, SocketParameters params, SystemProperties props) throws TTransportException { this.socketChannel = socketChannel; if (!socketChannel.isConnected()) throw new TTransportException(TTransportException.NOT_OPEN, "Socket must already be connected"); try { socketChannel.configureBlocking(blocking); setProperties(socketChannel.socket(), timeout, params, props); this.inputStream = UnsafeHolder.newChannelBufferFramedInputStream( socketChannel, this.inputBufferSize); this.outputStream = UnsafeHolder.newChannelBufferOutputStream( socketChannel, this.outputBufferSize); this.framedWrites = false; } catch (IOException ioe) { close(); throw new TTransportException(TTransportException.NOT_OPEN, ioe); } }
Example 2
Source File: GfxdTSocket.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
/** * Constructor that takes an already created socket. * * @param socket * Already created socket object * @param params * Socket parameters including buffer sizes and keep-alive settings * @param props * the system properties instance to use and initialize global socket * options like keepalive and buffer sizes that are not set in params * * @throws TTransportException * if there is an error setting up the streams */ public GfxdTSocket(SocketChannel socketChannel, boolean blocking, int timeout, SocketParameters params, SystemProperties props) throws TTransportException { this.socketChannel = socketChannel; if (!socketChannel.isConnected()) throw new TTransportException(TTransportException.NOT_OPEN, "Socket must already be connected"); try { socketChannel.configureBlocking(blocking); setProperties(socketChannel.socket(), timeout, params, props); this.inputStream = UnsafeHolder.newChannelBufferFramedInputStream( socketChannel, this.inputBufferSize); this.outputStream = UnsafeHolder.newChannelBufferOutputStream( socketChannel, this.outputBufferSize); this.framedWrites = false; } catch (IOException ioe) { close(); throw new TTransportException(TTransportException.NOT_OPEN, ioe); } }
Example 3
Source File: SSLSocketChannel.java From nifi with Apache License 2.0 | 6 votes |
public SSLSocketChannel(final SSLEngine sslEngine, final SocketChannel socketChannel) throws IOException { if (!socketChannel.isConnected()) { throw new IllegalArgumentException("Cannot pass an un-connected SocketChannel"); } this.channel = socketChannel; this.socketAddress = socketChannel.getRemoteAddress(); final Socket socket = socketChannel.socket(); this.hostname = socket.getInetAddress().getHostName(); this.port = socket.getPort(); // don't set useClientMode or needClientAuth, use the engine as is and let the caller configure it this.engine = sslEngine; streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize())); streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize())); appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize())); }
Example 4
Source File: BlinkClient.java From Blink with Artistic License 2.0 | 5 votes |
public boolean connect(SocketAddress address) { mAddress = address; try { SocketChannel channel = SocketChannel.open(mAddress); boolean connected = channel.isConnected(); if (connected) { channel.configureBlocking(false); start(channel); } return connected; } catch (IOException e) { e.printStackTrace(); return false; } }
Example 5
Source File: XmppTcpTransportModule.java From Smack with Apache License 2.0 | 5 votes |
@Override public boolean isConnected() { SocketChannel socketChannel = XmppTcpTransportModule.this.socketChannel; if (socketChannel == null) { return false; } return socketChannel.isConnected(); }
Example 6
Source File: CloseAfterConnect.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(0)); InetAddress lh = InetAddress.getLocalHost(); final SocketChannel sc = SocketChannel.open(); final InetSocketAddress isa = new InetSocketAddress(lh, ssc.socket().getLocalPort()); // establish connection in another thread Runnable connector = new Runnable() { public void run() { try { sc.connect(isa); } catch (IOException ioe) { ioe.printStackTrace(); } } }; Thread thr = new Thread(connector); thr.start(); // wait for connect to be established and for thread to // terminate do { try { thr.join(); } catch (InterruptedException x) { } } while (thr.isAlive()); // check connection is established if (!sc.isConnected()) { throw new RuntimeException("SocketChannel not connected"); } // close channel - this triggered the bug as it attempted to signal // a thread that no longer exists sc.close(); // clean-up ssc.accept().close(); ssc.close(); }
Example 7
Source File: CloseAfterConnect.java From openjdk-8-source with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(0)); InetAddress lh = InetAddress.getLocalHost(); final SocketChannel sc = SocketChannel.open(); final InetSocketAddress isa = new InetSocketAddress(lh, ssc.socket().getLocalPort()); // establish connection in another thread Runnable connector = new Runnable() { public void run() { try { sc.connect(isa); } catch (IOException ioe) { ioe.printStackTrace(); } } }; Thread thr = new Thread(connector); thr.start(); // wait for connect to be established and for thread to // terminate do { try { thr.join(); } catch (InterruptedException x) { } } while (thr.isAlive()); // check connection is established if (!sc.isConnected()) { throw new RuntimeException("SocketChannel not connected"); } // close channel - this triggered the bug as it attempted to signal // a thread that no longer exists sc.close(); // clean-up ssc.accept().close(); ssc.close(); }
Example 8
Source File: TcpSquirtOutboundTransport.java From defense-solutions-proofs-of-concept with Apache License 2.0 | 4 votes |
private int moveDataIntoIndividualChannelBuffers() { byte[] dst = {}; synchronized( buffer ) { if (buffer.position() == 0) return 0; buffer.flip(); dst = new byte[buffer.remaining()]; buffer.get(dst); buffer.compact(); } for( SocketChannel chan : connectionBuffers.keySet() ) { if(!chan.isConnected()) { connectionBuffers.remove(chan); continue; } ByteBuffer connectionBuffer = connectionBuffers.get(chan); try { if( connectionBuffer.remaining() > dst.length ) { connectionBuffer.put(dst); haveDataInIndividualBuffers = true; } else { String remoteClientAddress = chan.toString(); log.error( "Overflow while trying to write to the output buffer associated with address "+remoteClientAddress+"."); } }catch(BufferOverflowException ex) { log.error( "Overflow while trying to write to an output buffer."); } } return dst.length; }
Example 9
Source File: TcpSquirtOutboundTransport.java From defense-solutions-proofs-of-concept with Apache License 2.0 | 4 votes |
private int moveDataIntoIndividualChannelBuffers() { byte[] dst = {}; synchronized( buffer ) { if (buffer.position() == 0) return 0; buffer.flip(); dst = new byte[buffer.remaining()]; buffer.get(dst); buffer.compact(); } for( SocketChannel chan : connectionBuffers.keySet() ) { if(!chan.isConnected()) { connectionBuffers.remove(chan); continue; } ByteBuffer connectionBuffer = connectionBuffers.get(chan); try { if( connectionBuffer.remaining() > dst.length ) { connectionBuffer.put(dst); haveDataInIndividualBuffers = true; } else { String remoteClientAddress = chan.toString(); log.error( "Overflow while trying to write to the output buffer associated with address "+remoteClientAddress+"."); } }catch(BufferOverflowException ex) { log.error( "Overflow while trying to write to an output buffer."); } } return dst.length; }
Example 10
Source File: CloseAfterConnect.java From jdk8u-jdk with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(0)); InetAddress lh = InetAddress.getLocalHost(); final SocketChannel sc = SocketChannel.open(); final InetSocketAddress isa = new InetSocketAddress(lh, ssc.socket().getLocalPort()); // establish connection in another thread Runnable connector = new Runnable() { public void run() { try { sc.connect(isa); } catch (IOException ioe) { ioe.printStackTrace(); } } }; Thread thr = new Thread(connector); thr.start(); // wait for connect to be established and for thread to // terminate do { try { thr.join(); } catch (InterruptedException x) { } } while (thr.isAlive()); // check connection is established if (!sc.isConnected()) { throw new RuntimeException("SocketChannel not connected"); } // close channel - this triggered the bug as it attempted to signal // a thread that no longer exists sc.close(); // clean-up ssc.accept().close(); ssc.close(); }
Example 11
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 12
Source File: CloseAfterConnect.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(0)); InetAddress lh = InetAddress.getLocalHost(); final SocketChannel sc = SocketChannel.open(); final InetSocketAddress isa = new InetSocketAddress(lh, ssc.socket().getLocalPort()); // establish connection in another thread Runnable connector = new Runnable() { public void run() { try { sc.connect(isa); } catch (IOException ioe) { ioe.printStackTrace(); } } }; Thread thr = new Thread(connector); thr.start(); // wait for connect to be established and for thread to // terminate do { try { thr.join(); } catch (InterruptedException x) { } } while (thr.isAlive()); // check connection is established if (!sc.isConnected()) { throw new RuntimeException("SocketChannel not connected"); } // close channel - this triggered the bug as it attempted to signal // a thread that no longer exists sc.close(); // clean-up ssc.accept().close(); ssc.close(); }
Example 13
Source File: CloseAfterConnect.java From jdk8u-jdk with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(0)); InetAddress lh = InetAddress.getLocalHost(); final SocketChannel sc = SocketChannel.open(); final InetSocketAddress isa = new InetSocketAddress(lh, ssc.socket().getLocalPort()); // establish connection in another thread Runnable connector = new Runnable() { public void run() { try { sc.connect(isa); } catch (IOException ioe) { ioe.printStackTrace(); } } }; Thread thr = new Thread(connector); thr.start(); // wait for connect to be established and for thread to // terminate do { try { thr.join(); } catch (InterruptedException x) { } } while (thr.isAlive()); // check connection is established if (!sc.isConnected()) { throw new RuntimeException("SocketChannel not connected"); } // close channel - this triggered the bug as it attempted to signal // a thread that no longer exists sc.close(); // clean-up ssc.accept().close(); ssc.close(); }
Example 14
Source File: CloseAfterConnect.java From openjdk-jdk8u with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(0)); InetAddress lh = InetAddress.getLocalHost(); final SocketChannel sc = SocketChannel.open(); final InetSocketAddress isa = new InetSocketAddress(lh, ssc.socket().getLocalPort()); // establish connection in another thread Runnable connector = new Runnable() { public void run() { try { sc.connect(isa); } catch (IOException ioe) { ioe.printStackTrace(); } } }; Thread thr = new Thread(connector); thr.start(); // wait for connect to be established and for thread to // terminate do { try { thr.join(); } catch (InterruptedException x) { } } while (thr.isAlive()); // check connection is established if (!sc.isConnected()) { throw new RuntimeException("SocketChannel not connected"); } // close channel - this triggered the bug as it attempted to signal // a thread that no longer exists sc.close(); // clean-up ssc.accept().close(); ssc.close(); }
Example 15
Source File: GelfTCPSender.java From xian with Apache License 2.0 | 4 votes |
@Override protected boolean isConnected(SocketChannel channel) { return channel.isConnected(); }
Example 16
Source File: CloseAfterConnect.java From jdk8u60 with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(0)); InetAddress lh = InetAddress.getLocalHost(); final SocketChannel sc = SocketChannel.open(); final InetSocketAddress isa = new InetSocketAddress(lh, ssc.socket().getLocalPort()); // establish connection in another thread Runnable connector = new Runnable() { public void run() { try { sc.connect(isa); } catch (IOException ioe) { ioe.printStackTrace(); } } }; Thread thr = new Thread(connector); thr.start(); // wait for connect to be established and for thread to // terminate do { try { thr.join(); } catch (InterruptedException x) { } } while (thr.isAlive()); // check connection is established if (!sc.isConnected()) { throw new RuntimeException("SocketChannel not connected"); } // close channel - this triggered the bug as it attempted to signal // a thread that no longer exists sc.close(); // clean-up ssc.accept().close(); ssc.close(); }
Example 17
Source File: SocketBasedConnector.java From tcMenu with Apache License 2.0 | 4 votes |
@Override public boolean isDeviceConnected() { SocketChannel sc = socketChannel.get(); return sc != null && sc.isConnected(); }
Example 18
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 19
Source File: TNonblockingSocket.java From incubator-retired-blur with Apache License 2.0 | 2 votes |
/** * Constructor that takes an already created socket. * * @param socketChannel Already created SocketChannel object * @throws IOException if there is an error setting up the streams */ public TNonblockingSocket(SocketChannel socketChannel) throws IOException { this(socketChannel, 0, null); if (!socketChannel.isConnected()) throw new IOException("Socket must already be connected"); }
Example 20
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); }