From 42098c03b4296e440e2825b7d41965da72a6f970 Mon Sep 17 00:00:00 2001 From: Pacien TRAN-GIRARD Date: Wed, 11 May 2016 15:38:15 +0200 Subject: Implement action collection --- src/ch/epfl/xblast/server/Server.java | 43 +++++++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 4 deletions(-) (limited to 'src/ch') diff --git a/src/ch/epfl/xblast/server/Server.java b/src/ch/epfl/xblast/server/Server.java index 10d5a85..58f3c07 100644 --- a/src/ch/epfl/xblast/server/Server.java +++ b/src/ch/epfl/xblast/server/Server.java @@ -41,14 +41,27 @@ public class Server { } } - private static Optional> receiveAction(DatagramChannel chan, boolean block) { + private static Optional> receiveByte(DatagramChannel chan, boolean block) { try { ByteBuffer buf = ByteBuffer.allocate(1); chan.configureBlocking(block); SocketAddress client = chan.receive(buf); - PlayerAction action = PlayerAction.fromByte(buf.get(0)); - return Optional.of(new AbstractMap.SimpleImmutableEntry<>(client, action)); - } catch (IOException | IllegalArgumentException e) { + + if (Objects.isNull(client) || buf.position() == 0) + throw new IOException(); + + return Optional.of(new AbstractMap.SimpleImmutableEntry<>(client, buf.get(0))); + } catch (IOException e) { + return Optional.empty(); + } + } + + private static Optional> receiveAction(DatagramChannel chan, boolean block) { + try { + Map.Entry actionByte = receiveByte(chan, block).get(); + PlayerAction playerAction = PlayerAction.fromByte(actionByte.getValue()); + return Optional.of(new AbstractMap.SimpleImmutableEntry<>(actionByte.getKey(), playerAction)); + } catch (NoSuchElementException | IllegalArgumentException e) { return Optional.empty(); } } @@ -63,6 +76,19 @@ public class Server { return action.get(); } + private static Map collectActions(DatagramChannel chan) { + Map actions = new HashMap<>(); + Optional> action; + + while (true) { + action = receiveAction(chan, false); + if (!action.isPresent()) break; + actions.put(action.get().getKey(), action.get().getValue()); + } + + return Collections.unmodifiableMap(actions); + } + private static SocketAddress acceptRegistration(DatagramChannel chan) { Map.Entry clientAction; @@ -100,6 +126,15 @@ public class Server { this.registeredClients = Lists.linearAdjustedMap(clients, Arrays.asList(PlayerID.values())); System.out.println(this.registeredClients); + + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + Map actions = collectActions(chan); + System.out.println(actions); } } -- cgit v1.2.3