下面列出了java.nio.channels.ClosedSelectorException#java.nio.channels.NotYetConnectedException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Sends the given message to the peer. Due to the asynchronousness of network programming, there is no guarantee
* the peer will have received it. Throws NotYetConnectedException if we are not yet connected to the remote peer.
* TODO: Maybe use something other than the unchecked NotYetConnectedException here
*/
public void sendMessage(Message message) throws NotYetConnectedException {
lock.lock();
try {
if (writeTarget == null)
throw new NotYetConnectedException();
} finally {
lock.unlock();
}
// TODO: Some round-tripping could be avoided here
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
serializer.serialize(message, out);
writeTarget.writeBytes(out.toByteArray());
} catch (IOException e) {
exceptionCaught(e);
}
}
public static int ioResult(String method, int err, NativeIoException resetCause,
ClosedChannelException closedCause) throws IOException {
// network stack saturated... try again later
if (err == ERRNO_EAGAIN_NEGATIVE || err == ERRNO_EWOULDBLOCK_NEGATIVE) {
return 0;
}
if (err == resetCause.expectedErr()) {
throw resetCause;
}
if (err == ERRNO_EBADF_NEGATIVE) {
throw closedCause;
}
if (err == ERRNO_ENOTCONN_NEGATIVE) {
throw new NotYetConnectedException();
}
if (err == ERRNO_ENOENT_NEGATIVE) {
throw new FileNotFoundException();
}
// TODO: We could even go further and use a pre-instantiated IOException for the other error codes, but for
// all other errors it may be better to just include a stack trace.
throw newIOException(method, err);
}
public void testReadWrite_NonBlock_ReaderNotConnected() throws Exception {
byte[] sourceArray = new byte[CAPACITY_NORMAL];
byte[] targetArray = new byte[CAPACITY_NORMAL];
for (int i = 0; i < sourceArray.length; i++) {
sourceArray[i] = (byte) i;
}
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
channel1.connect(channel2Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
// read
ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
try {
assertEquals(0, this.channel2.read(targetBuf));
fail();
} catch (NotYetConnectedException expected) {
}
}
@Override
protected void doWriteFileRegion(FileRegion region) throws Exception {
OutputStream os = this.os;
if (os == null) {
throw new NotYetConnectedException();
}
if (outChannel == null) {
outChannel = Channels.newChannel(os);
}
long written = 0;
for (;;) {
long localWritten = region.transferTo(outChannel, written);
if (localWritten == -1) {
checkEOF(region);
return;
}
written += localWritten;
if (written >= region.count()) {
return;
}
}
}
/**
* Shutdown the input side of the channel.
*/
//
void shutdownInput(boolean rdHup) {
if (!socket.isInputShutdown()) {
if (isAllowHalfClosure(config())) {
try {
socket.shutdown(true, false);
} catch (IOException ignored) {
// We attempted to shutdown and failed, which means the input has already effectively been
// shutdown.
fireEventAndClose(ChannelInputShutdownEvent.INSTANCE);
return;
} catch (NotYetConnectedException ignore) {
// We attempted to shutdown and failed, which means the input has already effectively been
// shutdown.
}
clearEpollIn();
pipeline().fireUserEventTriggered(ChannelInputShutdownEvent.INSTANCE);
} else {
close(voidPromise());
}
} else if (!rdHup) {
inputClosedSeenErrorOnRead = true;
pipeline().fireUserEventTriggered(ChannelInputShutdownReadComplete.INSTANCE);
}
}
public boolean send(JfxDebuggerConnector server, String data) throws NotYetConnectedException {
String resourceId = myServerIds.get(server);
WebSocket conn = myConnections.get(resourceId);
if (conn == null) {
return false;
}
if (LOG.isDebugEnabled()) System.out.println("sending to " + conn.getRemoteSocketAddress() + ": " + data);
try {
conn.send(data);
} catch (WebsocketNotConnectedException e) {
myConnections.put(resourceId, null);
return false;
}
return true;
}
private void initDebugger(int instanceId, @Nullable Runnable onStart) {
Platform.runLater(() -> {
myDebugger.setEnabled(true);
myDebugger.sendMessage("{\"id\" : -1, \"method\" : \"Network.enable\"}");
this.myDebugger.setMessageCallback(data -> {
try {
myServer.send(this, data);
} catch (NotYetConnectedException e) {
e.printStackTrace();
}
return null;
});
if (LOG.isDebugEnabled()) {
String remoteUrl = getDebugUrl();
System.out.println("Debug session created. Debug URL: " + remoteUrl);
LOG.debug("Debug session created. Debug URL: " + remoteUrl);
}
if (onStart != null) {
onStart.run();
}
});
}
/**
* Sends the given message to the peer. Due to the asynchronousness of network programming, there is no guarantee
* the peer will have received it. Throws NotYetConnectedException if we are not yet connected to the remote peer.
* TODO: Maybe use something other than the unchecked NotYetConnectedException here
*/
public void sendMessage(Message message) throws NotYetConnectedException {
lock.lock();
try {
if (writeTarget == null)
throw new NotYetConnectedException();
} finally {
lock.unlock();
}
// TODO: Some round-tripping could be avoided here
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
serializer.serialize(message, out);
writeTarget.writeBytes(out.toByteArray());
} catch (IOException e) {
exceptionCaught(e);
}
}
/**
* Marks the beginning of a read operation that might block.
*
* @param blocking true if configured blocking
* @param mustBeConnected true if the socket must be connected
* @return remote address if connected
* @throws ClosedChannelException if the channel is closed
* @throws NotYetConnectedException if mustBeConnected and not connected
* @throws IOException if socket not bound and cannot be bound
*/
private SocketAddress beginRead(boolean blocking, boolean mustBeConnected)
throws IOException
{
if (blocking) {
// set hook for Thread.interrupt
begin();
}
SocketAddress remote;
synchronized (stateLock) {
ensureOpen();
remote = remoteAddress;
if ((remote == null) && mustBeConnected)
throw new NotYetConnectedException();
if (localAddress == null)
bindInternal(null);
if (blocking)
readerThread = NativeThread.current();
}
return remote;
}
/**
* Marks the beginning of a write operation that might block.
* @param blocking true if configured blocking
* @param mustBeConnected true if the socket must be connected
* @return remote address if connected
* @throws ClosedChannelException if the channel is closed
* @throws NotYetConnectedException if mustBeConnected and not connected
* @throws IOException if socket not bound and cannot be bound
*/
private SocketAddress beginWrite(boolean blocking, boolean mustBeConnected)
throws IOException
{
if (blocking) {
// set hook for Thread.interrupt
begin();
}
SocketAddress remote;
synchronized (stateLock) {
ensureOpen();
remote = remoteAddress;
if ((remote == null) && mustBeConnected)
throw new NotYetConnectedException();
if (localAddress == null)
bindInternal(null);
if (blocking)
writerThread = NativeThread.current();
}
return remote;
}
@Override
public SocketChannel shutdownInput() throws IOException {
synchronized (stateLock) {
ensureOpen();
if (!isConnected())
throw new NotYetConnectedException();
if (!isInputClosed) {
Net.shutdown(fd, Net.SHUT_RD);
long thread = readerThread;
if (thread != 0)
NativeThread.signal(thread);
isInputClosed = true;
}
return this;
}
}
@Override
public SocketChannel shutdownOutput() throws IOException {
synchronized (stateLock) {
ensureOpen();
if (!isConnected())
throw new NotYetConnectedException();
if (!isOutputClosed) {
Net.shutdown(fd, Net.SHUT_WR);
long thread = writerThread;
if (thread != 0)
NativeThread.signal(thread);
isOutputClosed = true;
}
return this;
}
}
public void testReadWrite_Block_ReaderNotConnected() throws Exception {
byte[] sourceArray = new byte[CAPACITY_NORMAL];
byte[] targetArray = new byte[CAPACITY_NORMAL];
for (int i = 0; i < sourceArray.length; i++) {
sourceArray[i] = (byte) i;
}
// reader channel2 is not connected.
this.channel1.connect(channel2Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
// read
ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
try {
this.channel2.read(targetBuf);
fail();
} catch (NotYetConnectedException expected) {
}
}
public void testOpen() throws IOException {
java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1];
buf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
MockSocketChannel testMSChannel = new MockSocketChannel(null);
MockSocketChannel testMSChannelnotnull = new MockSocketChannel(
SelectorProvider.provider());
assertNull(testMSChannel.provider());
assertNotNull(testMSChannelnotnull.provider());
assertNotNull(this.channel1);
assertEquals(this.channel1.provider(), testMSChannelnotnull.provider());
try {
this.channel1.write(buf);
fail("Should throw NotYetConnectedException");
} catch (NotYetConnectedException e) {
// correct
}
}
public void testReadByteBufferArrayIntInt() throws IOException {
ByteBuffer[] readBuf = new ByteBuffer[2];
readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
InetSocketAddress ipAddr = datagramSocket1Address;
try {
this.channel1.read(readBuf, 0, 2);
fail("should throw NotYetConnectedException");
} catch (NotYetConnectedException e) {
// correct
}
this.channel1.connect(ipAddr);
assertTrue(this.channel1.isConnected());
this.channel1.configureBlocking(false);
// note : blocking-mode will make the read process endless!
assertEquals(0, this.channel1.read(readBuf, 0, 1));
assertEquals(0, this.channel1.read(readBuf, 0, 2));
datagramSocket1.close();
}
public void invokeMethod(String method, Object paramsObject,
@Nullable PendingRequestCallback callback)
throws NotYetConnectedException {
Util.throwIfNull(method);
Long requestId = (callback != null) ? preparePendingRequest(callback) : null;
// magic, can basically convert anything for some amount of runtime overhead...
JSONObject params = mObjectMapper.convertValue(paramsObject, JSONObject.class);
JsonRpcRequest message = new JsonRpcRequest(requestId, method, params);
String requestString;
JSONObject jsonObject = mObjectMapper.convertValue(message, JSONObject.class);
requestString = jsonObject.toString();
mPeer.sendText(requestString);
}
public void invokeMethod(String method, Object paramsObject,
@Nullable PendingRequestCallback callback)
throws NotYetConnectedException {
Util.throwIfNull(method);
Long requestId = (callback != null) ? preparePendingRequest(callback) : null;
// magic, can basically convert anything for some amount of runtime overhead...
JSONObject params = mObjectMapper.convertValue(paramsObject, JSONObject.class);
JsonRpcRequest message = new JsonRpcRequest(requestId, method, params);
String requestString;
JSONObject jsonObject = mObjectMapper.convertValue(message, JSONObject.class);
requestString = jsonObject.toString();
mPeer.sendText(requestString);
}
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
Throwable cause = e.getCause();
// do not print exception if it is BindException.
// we are trying to search available port below 1024. It is not good to
// print a flood
// of error logs during the searching.
if (cause instanceof java.net.BindException) {
return;
}
LOG.error("Exception on connection to " + getRemoteAddress(), e.getCause());
// close the channel unless we are connecting and it is
// NotYetConnectedException
if (!((cause instanceof NotYetConnectedException)
&& _connection.getConnectionState().equals(Connection.State.CONNECTING))) {
ctx.getChannel().close();
}
}
/**
* Sends the given message to the peer. Due to the asynchronousness of network programming, there is no guarantee
* the peer will have received it. Throws NotYetConnectedException if we are not yet connected to the remote peer.
* TODO: Maybe use something other than the unchecked NotYetConnectedException here
*/
public void sendMessage(Message message) throws NotYetConnectedException {
lock.lock();
try {
if (writeTarget == null)
throw new NotYetConnectedException();
} finally {
lock.unlock();
}
// TODO: Some round-tripping could be avoided here
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
serializer.serialize(message, out);
writeTarget.writeBytes(out.toByteArray());
} catch (IOException e) {
exceptionCaught(e);
}
}
@Override
protected void doWriteFileRegion(FileRegion region) throws Exception {
OutputStream os = this.os;
if (os == null) {
throw new NotYetConnectedException();
}
if (outChannel == null) {
outChannel = Channels.newChannel(os);
}
long written = 0;
for (;;) {
long localWritten = region.transferTo(outChannel, written);
if (localWritten == -1) {
checkEOF(region);
return;
}
written += localWritten;
if (written >= region.count()) {
return;
}
}
}
@Override
public void sendPing() throws NotYetConnectedException {
if (pingFrame == null) {
pingFrame = new PingFrame();
}
sendFrame(pingFrame);
}
private boolean ensureReceiveOpen() throws ClosedChannelException {
synchronized (stateLock) {
if (!isOpen())
throw new ClosedChannelException();
if (!isConnected())
throw new NotYetConnectedException();
else
return true;
}
}
private void ensureSendOpen() throws ClosedChannelException {
synchronized (stateLock) {
if (!isOpen())
throw new ClosedChannelException();
if (isShutdown)
throw new ClosedChannelException();
if (!isConnected())
throw new NotYetConnectedException();
}
}
/**
* Shutdown the input side of the channel.
*/
void shutdownInput(boolean readEOF) {
// We need to take special care of calling finishConnect() if readEOF is true and we not
// fullfilled the connectPromise yet. If we fail to do so the connectPromise will be failed
// with a ClosedChannelException as a close() will happen and so the FD is closed before we
// have a chance to call finishConnect() later on. Calling finishConnect() here will ensure
// we observe the correct exception in case of a connect failure.
if (readEOF && connectPromise != null) {
finishConnect();
}
if (!socket.isInputShutdown()) {
if (isAllowHalfClosure(config())) {
try {
socket.shutdown(true, false);
} catch (IOException ignored) {
// We attempted to shutdown and failed, which means the input has already effectively been
// shutdown.
fireEventAndClose(ChannelInputShutdownEvent.INSTANCE);
return;
} catch (NotYetConnectedException ignore) {
// We attempted to shutdown and failed, which means the input has already effectively been
// shutdown.
}
pipeline().fireUserEventTriggered(ChannelInputShutdownEvent.INSTANCE);
} else {
close(voidPromise());
}
} else if (!readEOF) {
inputClosedSeenErrorOnRead = true;
pipeline().fireUserEventTriggered(ChannelInputShutdownReadComplete.INSTANCE);
}
}
private boolean ensureReceiveOpen() throws ClosedChannelException {
synchronized (stateLock) {
if (!isOpen())
throw new ClosedChannelException();
if (!isConnected())
throw new NotYetConnectedException();
else
return true;
}
}
private void ensureSendOpen() throws ClosedChannelException {
synchronized (stateLock) {
if (!isOpen())
throw new ClosedChannelException();
if (isShutdown)
throw new ClosedChannelException();
if (!isConnected())
throw new NotYetConnectedException();
}
}
private boolean ensureReceiveOpen() throws ClosedChannelException {
synchronized (stateLock) {
if (!isOpen())
throw new ClosedChannelException();
if (!isConnected())
throw new NotYetConnectedException();
else
return true;
}
}
private void ensureSendOpen() throws ClosedChannelException {
synchronized (stateLock) {
if (!isOpen())
throw new ClosedChannelException();
if (isShutdown)
throw new ClosedChannelException();
if (!isConnected())
throw new NotYetConnectedException();
}
}
private boolean ensureReceiveOpen() throws ClosedChannelException {
synchronized (stateLock) {
if (!isOpen())
throw new ClosedChannelException();
if (!isConnected())
throw new NotYetConnectedException();
else
return true;
}
}
private void ensureSendOpen() throws ClosedChannelException {
synchronized (stateLock) {
if (!isOpen())
throw new ClosedChannelException();
if (isShutdown)
throw new ClosedChannelException();
if (!isConnected())
throw new NotYetConnectedException();
}
}