下面列出了java.nio.channels.AsynchronousServerSocketChannel#accept() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/***************************************
* Opens and connects a {@link Channel} to the {@link SocketAddress} of this
* step and then performs the channel operation asynchronously.
*
* @param rSuspension The coroutine suspension to be resumed when the
* operation is complete
*/
private void acceptAsync(Suspension<Void> rSuspension)
{
try
{
AsynchronousServerSocketChannel rChannel =
getServerSocketChannel(rSuspension.continuation());
rChannel.accept(
null,
new AcceptCallback(rRequestHandler, rSuspension));
}
catch (Exception e)
{
rSuspension.fail(e);
}
}
/**
*
* @param exc
* @param tioServer
* @author tanyaowu
*/
@Override
public void failed(Throwable exc, TioServer tioServer) {
AsynchronousServerSocketChannel serverSocketChannel = tioServer.getServerSocketChannel();
serverSocketChannel.accept(tioServer, this);
log.error("[" + tioServer.getServerNode() + "]监听出现异常", exc);
}
private boolean startServer() throws Exception
{
final AsynchronousServerSocketChannel server_channel = AsynchronousServerSocketChannel.open();
server_channel.setOption(StandardSocketOptions.SO_REUSEADDR, Boolean.TRUE);
try
{
server_channel.bind(address);
}
catch (BindException ex)
{
// Address in use, there is already a server
return false;
}
client_handler = new CompletionHandler<>()
{
@Override
public void completed(final AsynchronousSocketChannel client_channel, Void Null)
{
// Start thread to handle this client..
handleClient(client_channel);
// Accept another client
server_channel.accept(null, client_handler);
}
@Override
public void failed(final Throwable ex, Void Null)
{
logger.log(Level.WARNING, "Application server connection error", ex);
}
};
// Accept initial client
logger.log(Level.INFO, "Listening for arguments on TCP " + address.getPort());
server_channel.accept(null, client_handler);
return true;
}
/**
* @see java.nio.channels.CompletionHandler#failed(java.lang.Throwable, java.lang.Object)
*
* @param exc
* @param aioServer
* @重写人: tanyaowu
* @重写时间: 2016年11月16日 下午1:28:05
*
*/
@Override
public void failed(Throwable exc, AioServer<SessionContext, P, R> aioServer)
{
AsynchronousServerSocketChannel serverSocketChannel = aioServer.getServerSocketChannel();
serverSocketChannel.accept(aioServer, this);
log.error("[" + aioServer.getServerNode() + "]监听出现异常", exc);
}