Vorrei scrivere un server asincrono utilizzando Java 7 e NIO 2.Come dovrei usare AsynchronousServerSocketChannel per accettare le connessioni?
Ma come dovrei usare AsynchronousServerSocketChannel
?
E.g. se comincio con:
final AsynchronousServerSocketChannel server =
AsynchronousServerSocketChannel.open().bind(
new InetSocketAddress(port));
Poi quando faccio server.accept()
, il programma termina perché questa chiamata è asincrona . E se inserisco quel codice in un ciclo infinito, viene lanciato un AcceptPendingException
.
Qualche suggerimento su come scrivere un semplice server asincrono usando AsynchronousServerSocketChannel
?
Ecco il mio esempio completo (simile all'esempio nella 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();
}
}
}
È possibile utilizzare quadro Netty che è specialmente per l'applicazione client-server. Utilizza anche Java NIO. È facile e veloce lo sviluppo del server. passare attraverso http://netty.io/ –
@Optimus: so di netty, ma non è rilevante per questa domanda. – Jonas