1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
public class Server {
private int portDealer;
private int portParticipants;
private ServerSocketChannel createServerChannel(Selector selector, int port) {
try {
//création d'un canal serveur
ServerSocketChannel ssc = ServerSocketChannel.open();
//le configurer en mode non bloquant
ssc.configureBlocking(false);
//configuration de la socket sous jacente
ServerSocket ss = ssc.socket();
ss.bind(new InetSocketAddress(port));
//configuration du selector
ssc.register(selector, ssc.validOps());
return ssc;
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
return null;
}
public void startServer(Dealer dealerThread){
try {
Selector select = Selector.open();
//création des cannaux non bloquant pour Dealer/Participant
ServerSocketChannel sscDealer = createServerChannel(select, portDealer);
ServerSocketChannel sscParticipants = createServerChannel(select, portParticipants);
while (true) {
System.out.println("Attente ...");
select.select();
Iterator<SelectionKey> it = select.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
if (key.isAcceptable()) {
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
Socket socket = ssc.socket().accept();
dealerThread.setDealerSocket(socket);
Thread dealer = new Thread(dealerThread);
dealer.start();
}
it.remove();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
} |
Partager