Reputation: 31
Have a listener implemented using AsynchronousServerSocketChannel. I open the channnel , bind to the port and start accepting connections. i am able to listen and read the messages. The problem event after closing the channel my listener still accepting data.
I close the server channel socket connection as below.
this.serverChannel.close();
this.serverChannel = null;
Here is the completion handler to accept connections
this.serverChannel
.accept(null,
new java.nio.channels.CompletionHandler<AsynchronousSocketChannel, Void>() {
@Override
public void completed(
AsynchronousSocketChannel result,
Void attachment) {
acceptConnections();
read(new HSLParsingContext(), result);
}
@Override
public void failed(Throwable exc, Void attachment) {
if (!(exc instanceof AsynchronousCloseException))
});
public void read(final HSLParsingContext context,
final AsynchronousSocketChannel channel) {
try {
channel.read(context.buffer, null,
new java.nio.channels.CompletionHandler<Integer, Void>() {
@Override
public void completed(Integer bytesRead, Void attachment) {
try {
HSLSysLogTcpListener.this.logger.infoFmt(
"Bytes received: %s ", bytesRead);
if (bytesRead > 0) {
messageHandler(context, false);
}
if (bytesRead == -1) {
// when nothing is there to read in the
// channel make sure there
// is nothing in the content buffer before
// closing the channel
if (context.content.length() > 0) {
messageHandler(context, true);
}
throw new EOFException();
}
// keep reading data asynchronously
read(context, channel);
} catch (Exception e) {
failed(e, null);
}
}
@Override
public void failed(Throwable e, Void attachment) {
logReadFailureAndClose(channel, e);
}
});
} catch (Throwable e) {
logReadFailureAndClose(channel, e);
}
I kind of feel that the AsynchronousSocketChannel than opened by the accept method is not closed. Hence i am receving the messages event after closing the AsynchronousServerSocketChannel .
Is there as way to close AsynchronousSocketChannel while closing the serversocketchannel.Please let me know the best was fully stop the AsynchronousServerSocketChannel and it asscoiated AsynchronousSocketChannel
Upvotes: 0
Views: 1810
Reputation: 311052
AsynchronousServerSocketChannel not closing the established connections
I agree. It doesn't. It isn't meant to do that. There's no reason why closing the server socket channel should close anything else.
If you want accepted sockets to be closed, you have to close them yourself, and you aren't. The close happens, or should happen, in logReadFailureAndClose()
, which you haven't posted. Closing the server socket channel has nothing to do with it. If you want to close everything at the same time you will need an up-to-date list of accepted sockets, and close them all when you close the server socket channel.
Upvotes: 3