use of java.nio.channels.NotYetConnectedException in project jdk8u_jdk by JetBrains.
the class Shutdown method doTest.
void doTest(SocketAddress peerAddress) {
SctpChannel channel = null;
ByteBuffer buffer = ByteBuffer.allocate(Util.SMALL_BUFFER);
MessageInfo info;
try {
channel = SctpChannel.open();
/* TEST 1: Verify NotYetConnectedException thrown */
debug("Test 1: NotYetConnectedException");
try {
channel.shutdown();
fail("shutdown not throwing expected NotYetConnectedException");
} catch (NotYetConnectedException unused) {
pass();
} catch (IOException ioe) {
unexpected(ioe);
}
channel.connect(peerAddress);
sentLatch.await();
channel.shutdown();
/* TEST 2: receive data sent before shutdown */
do {
debug("Test 2: invoking receive");
info = channel.receive(buffer, null, null);
if (info == null) {
fail("unexpected null from receive");
return;
}
} while (!info.isComplete());
buffer.flip();
check(info != null, "info is null");
check(info.bytes() == Util.SMALL_MESSAGE.getBytes("ISO-8859-1").length, "bytes received not equal to message length");
check(info.bytes() == buffer.remaining(), "bytes != remaining");
check(Util.compare(buffer, Util.SMALL_MESSAGE), "received message not the same as sent message");
buffer.clear();
/* TEST 3: receive notifications on the SCTP stack */
debug("Test 3: receive notifications");
while ((info = channel.receive(buffer, null, null)) != null && info.bytes() != -1) ;
/* TEST 4: If the channel is already shutdown then invoking this
* method has no effect. */
debug("Test 4: no-op");
try {
channel.shutdown();
pass();
} catch (IOException ioe) {
unexpected(ioe);
}
/* TEST 5: Further sends will throw ClosedChannelException */
debug("Test 5: ClosedChannelException");
info = MessageInfo.createOutgoing(null, 1);
try {
channel.send(buffer, info);
fail("shutdown not throwing expected ClosedChannelException");
} catch (ClosedChannelException unused) {
pass();
} catch (IOException ioe) {
unexpected(ioe);
}
/* TEST 6: getRemoteAddresses */
debug("Test 6: getRemoteAddresses");
try {
java.util.Set<SocketAddress> remoteAddrs = channel.getRemoteAddresses();
check(remoteAddrs.isEmpty(), "A shutdown channel should not have remote addresses");
} catch (IOException ioe) {
unexpected(ioe);
}
} catch (IOException ioe) {
unexpected(ioe);
} catch (InterruptedException ie) {
unexpected(ie);
} finally {
finishedLatch.countDown();
try {
if (channel != null)
channel.close();
} catch (IOException e) {
unexpected(e);
}
}
}
use of java.nio.channels.NotYetConnectedException in project kdeconnect-android by KDE.
the class LanLink method sendPackageInternal.
//Blocking, do not call from main thread
private boolean sendPackageInternal(NetworkPackage np, final Device.SendPackageStatusCallback callback, PublicKey key) {
if (socket == null) {
Log.e("KDE/sendPackage", "Not yet connected");
callback.onFailure(new NotYetConnectedException());
return false;
}
try {
//Prepare socket for the payload
final ServerSocket server;
if (np.hasPayload()) {
server = LanLinkProvider.openServerSocketOnFreePort(LanLinkProvider.PAYLOAD_TRANSFER_MIN_PORT);
JSONObject payloadTransferInfo = new JSONObject();
payloadTransferInfo.put("port", server.getLocalPort());
np.setPayloadTransferInfo(payloadTransferInfo);
} else {
server = null;
}
//Encrypt if key provided
if (key != null) {
np = RsaHelper.encrypt(np, key);
}
//Send body of the network package
try {
OutputStream writer = socket.getOutputStream();
writer.write(np.serialize().getBytes(StringsHelper.UTF8));
writer.flush();
} catch (Exception e) {
//main socket is broken, disconnect
disconnect();
throw e;
}
//Send payload
if (server != null) {
Socket payloadSocket = null;
OutputStream outputStream = null;
InputStream inputStream = null;
try {
//Wait a maximum of 10 seconds for the other end to establish a connection with our socket, close it afterwards
server.setSoTimeout(10 * 1000);
payloadSocket = server.accept();
//Convert to SSL if needed
if (socket instanceof SSLSocket) {
payloadSocket = SslHelper.convertToSslSocket(context, payloadSocket, getDeviceId(), true, false);
}
outputStream = payloadSocket.getOutputStream();
inputStream = np.getPayload();
Log.i("KDE/LanLink", "Beginning to send payload");
byte[] buffer = new byte[4096];
int bytesRead;
long size = np.getPayloadSize();
long progress = 0;
long timeSinceLastUpdate = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
//Log.e("ok",""+bytesRead);
progress += bytesRead;
outputStream.write(buffer, 0, bytesRead);
if (size > 0) {
if (timeSinceLastUpdate + 500 < System.currentTimeMillis()) {
//Report progress every half a second
long percent = ((100 * progress) / size);
callback.onProgressChanged((int) percent);
timeSinceLastUpdate = System.currentTimeMillis();
}
}
}
outputStream.flush();
outputStream.close();
Log.i("KDE/LanLink", "Finished sending payload (" + progress + " bytes written)");
} finally {
try {
server.close();
} catch (Exception e) {
}
try {
payloadSocket.close();
} catch (Exception e) {
}
try {
inputStream.close();
} catch (Exception e) {
}
try {
outputStream.close();
} catch (Exception e) {
}
}
}
callback.onSuccess();
return true;
} catch (Exception e) {
if (callback != null) {
callback.onFailure(e);
}
return false;
} finally {
//Make sure we close the payload stream, if any
InputStream stream = np.getPayload();
try {
stream.close();
} catch (Exception e) {
}
}
}
use of java.nio.channels.NotYetConnectedException in project webpieces by deanhiller.
the class Helper method read.
private static void read(SelectionKey key, SelectorManager2 mgr, BufferPool pool) throws IOException {
log.trace(() -> key.attachment() + "reading data");
WrapperAndListener struct = (WrapperAndListener) key.attachment();
DataListener in = struct.getDataHandler();
BasChannelImpl channel = (BasChannelImpl) struct.getChannel();
//pressure in RAM so just wait until they re-registerForReads and they will get the data then
if (!channel.isRegisteredForReads()) {
//do not process reads if we were unregistered
return;
}
ByteBuffer chunk = pool.nextBuffer(512);
try {
if (logBufferNextRead)
log.info(channel + "buffer=" + chunk);
int bytes = channel.readImpl(chunk);
if (logBufferNextRead) {
logBufferNextRead = false;
log.info(channel + "buffer2=" + chunk);
}
processBytes(key, chunk, bytes, mgr);
} catch (PortUnreachableException e) {
//this is a normal occurence when some writes out udp to a port that is not
//listening for udp!!! log as finer and fire to client to deal with it.
log.trace(() -> "Client sent data to a host or port that is not listening " + "to udp, or udp can't get through to that machine", e);
in.failure(channel, null, e);
} catch (NotYetConnectedException e) {
//this happens in udp when I disconnect after someone had already been streaming me
//data. It is supposed to stop listening but selector keeps firing.
log.error("Can't read until UDPChannel is connected", e);
in.failure(channel, null, e);
} catch (IOException e) {
//kept getting the following exception so I added this as protection
//NOTE: this exceptionn should never occur. read should be returning -1
//but for some reason is returning hte exception instead.
// WARNING: [server] Processing of key failed, closing channel
// java.io.IOException: An established connection was aborted by the software in your host machine
// at sun.nio.ch.SocketDispatcher.read0(Native Method)
// at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:25)
// at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:233)
// at sun.nio.ch.IOUtil.read(IOUtil.java:206)
// at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:207)
// at biz.xsoftware.impl.nio.cm.basic.TCPChannelImpl.readImpl(TCPChannelImpl.java:168)
// at biz.xsoftware.impl.nio.cm.basic.Helper.read(Helper.java:128)
// at biz.xsoftware.impl.nio.cm.basic.Helper.processKey(Helper.java:77)
// at biz.xsoftware.impl.nio.cm.basic.Helper.processKeys(Helper.java:43)
// at biz.xsoftware.impl.nio.cm.basic.SelectorManager2.runLoop(SelectorManager2.java:262)
// at biz.xsoftware.impl.nio.cm.basic.SelectorManager2$PollingThread.run
// (SelectorManager2.java:224)
//another one that landes here is the Connection reset by peer"....
// Jan 18, 2012 1:00:42 PM biz.xsoftware.impl.nio.cm.basic.Helper read
// INFO: [stserver] Exception
// java.io.IOException: Connection reset by peer
// at sun.nio.ch.FileDispatcher.read0(Native Method)
// at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
// at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:251)
// at sun.nio.ch.IOUtil.read(IOUtil.java:224)
// at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:254)
// at biz.xsoftware.impl.nio.cm.basic.chanimpl.SocketChannelImpl.read(SocketChannelImpl.java:65)
// at biz.xsoftware.impl.nio.cm.basic.BasTCPChannel.readImpl(BasTCPChannel.java:108)
// at biz.xsoftware.impl.nio.cm.basic.Helper.read(Helper.java:162)
// at biz.xsoftware.impl.nio.cm.basic.Helper.processKey(Helper.java:104)
// at biz.xsoftware.impl.nio.cm.basic.Helper.processKeys(Helper.java:51)
// at biz.xsoftware.impl.nio.cm.basic.SelectorManager2.selectorFired(SelectorManager2.java:253)
// at biz.xsoftware.impl.nio.cm.basic.nioimpl.SelectorImpl.runLoop(SelectorImpl.java:126)
// at biz.xsoftware.impl.nio.cm.basic.nioimpl.SelectorImpl$PollingThread.run(SelectorImpl.java:107)
//One other exception starts with "An existing connection was forcibly closed"
//in the case of SSL over TCP only, sometimes instead of reading off a -1, this will
//throw an IOException: "An existing connection was forcibly closed by the remote host"
//we also close UDPChannels as well on IOException. Not sure if this is good or not.
process(key, mgr, in, channel, chunk, e);
} catch (NioException e) {
Throwable cause = e.getCause();
if (cause instanceof IOException) {
IOException ioExc = (IOException) cause;
process(key, mgr, in, channel, chunk, ioExc);
} else
throw e;
}
}
Aggregations