J'ai ecrit un serveur pour ma lib JNAG ("Java Network API for Games",
http://www.javagaming.org/cgi-bin/JGNetForums/YaBB.cgi?board=Proposals;action=display;num=1100199605;start=0),
mais j'ai un probleme.
Dans ma classe serveur, j'ai un threat qui ecoute les demandes connections
en utilisant un selector.
J'ai pris le code depuis un bouquin qui avait l'air bien : "Java Network
Programming" de Oreilly, en gros j'ai recopie leur example qui est pourtant
tres court et simple, mais ce ^&#%$^#@%^* de selector mange tout le CPU a
attendre les connections rentrentes.
J'utilise le gestionnaire de tache de windows pour surveiller l'activitee du
CPU. J'ai fait un test avec Thread.sleep(20 * 1000), et dans ce cas la c'est
ok, ya pas d'utilisation du CPU detectee ... le thread dort. Je me dis qu'il
y a surement un moyen d'ecouter la socket en dormant (en laissant l'OS s'en
charger).
J'ai copie la portion de code en dessous. Si quelqu'un sait d'ou vient le
probleme ou peut me dire si c'est normal ou pas, ca m'aiderait vraiment
beaucoup.
Merci,
Vincent
// Create the server socket
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
ServerSocket serverSocket = serverSocketChannel.socket();
// Bind it to the current host on the specified port
InetSocketAddress address = new InetSocketAddress(port);
serverSocket.bind(address);
// Create the selector for a sleep-until-connect-requested behavior
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true)
{
// Listener the next incoming connections from a client
selector.select(); // <-- C'est ici .. le thread reste la a attendre
et mange le CPU.
// Here, a set of clients are trying to connect .. let's handle them
Set readyKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = readyKeys.iterator();
while (iterator.hasNext())
{
// Get a key from the map of the incoming connections
SelectionKey key = iterator.next();
iterator.remove(); // eat it :)
// Create and configure a Connection instance
SocketChannel clientSocketChannel = serverSocketChannel.accept();
C connection = createConnection(clientSocketChannel);
// Add it to the a queue for the thread which will process the
requests
newConnections.add(connection);
}
}