Me gustaría escribir un servidor asíncrono con Java 7 y NIO 2.¿Cómo debo usar AsynchronousServerSocketChannel para aceptar conexiones?
Pero, ¿cómo debo usar AsynchronousServerSocketChannel
?
E.g. si comienzo con:
final AsynchronousServerSocketChannel server =
AsynchronousServerSocketChannel.open().bind(
new InetSocketAddress(port));
Entonces cuando hago server.accept()
, el programa termina porque esa llamada es asíncrona. Y si pongo ese código en un bucle infinito, se arroja un AcceptPendingException
.
¿Alguna sugerencia sobre cómo escribir un servidor asincrónico simple usando AsynchronousServerSocketChannel
?
Aquí está mi ejemplo completo (similar al ejemplo en el JavaDoc):
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
public class AsyncServer {
public static void main(String[] args) {
int port = 8060;
try {
final AsynchronousServerSocketChannel server =
AsynchronousServerSocketChannel.open().bind(
new InetSocketAddress(port));
System.out.println("Server listening on " + port);
server.accept("Client connection",
new CompletionHandler<AsynchronousSocketChannel, Object>() {
public void completed(AsynchronousSocketChannel ch, Object att) {
System.out.println("Accepted a connection");
// accept the next connection
server.accept("Client connection", this);
// handle this connection
//TODO handle(ch);
}
public void failed(Throwable exc, Object att) {
System.out.println("Failed to accept connection");
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
Puede utilizar marco Netty que es especialmente para aplicaciones cliente-servidor. También usa java NIO. Es un desarrollo fácil y rápido del servidor. ir a través de http://netty.io/ –
@Optimus: sé de netty, pero eso no es relevante para esta pregunta. – Jonas