From 33bc4cab3f2a00db14e6d055d6cd55781c9dd2b4 Mon Sep 17 00:00:00 2001 From: Pacien TRAN-GIRARD Date: Wed, 11 May 2016 18:44:21 +0200 Subject: Implement game state broadcasting --- src/ch/epfl/xblast/server/Server.java | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/ch/epfl/xblast/server/Server.java b/src/ch/epfl/xblast/server/Server.java index 6d8db2c..4929dd9 100644 --- a/src/ch/epfl/xblast/server/Server.java +++ b/src/ch/epfl/xblast/server/Server.java @@ -3,6 +3,7 @@ package ch.epfl.xblast.server; import ch.epfl.xblast.Lists; import ch.epfl.xblast.PlayerAction; import ch.epfl.xblast.PlayerID; +import ch.epfl.xblast.server.painter.BoardPainter; import java.io.IOException; import java.net.InetSocketAddress; @@ -26,6 +27,15 @@ public class Server { private static class Channel { + private static byte[] toByteArray(List l) { + byte[] arr = new byte[l.size()]; + + for (int i = 0; i < l.size(); ++i) + arr[i] = l.get(i); + + return arr; + } + private static InetSocketAddress listeningInterface(String host, int port) { if (Objects.isNull(host)) return new InetSocketAddress(port); @@ -88,6 +98,15 @@ public class Server { return Collections.unmodifiableMap(actions); } + void send(List content, SocketAddress dst) { + try { + ByteBuffer buf = ByteBuffer.wrap(toByteArray(content)); + this.channel.send(buf, dst); + } catch (IOException e) { + e.printStackTrace(); + } + } + private Optional> receiveByte(boolean block) { try { ByteBuffer buf = ByteBuffer.allocate(1); @@ -171,9 +190,8 @@ public class Server { while (!gameState.isGameOver()) { long computationStartTime = System.nanoTime(); - gameState = updateGameState(updateGameState(gameState)); - + broadcastGameState(gameState); delay(REFRESH_RATE - (computationStartTime - System.nanoTime())); } } @@ -183,4 +201,13 @@ public class Server { return gs.next(events); } + private void broadcastGameState(GameState gs) { + List serialized = GameStateSerializer.serialize(BoardPainter.DEFAULT_BOARD_PAINTER, gs); + + for (Map.Entry client : this.registeredClientsMap.entrySet()) { + byte activePlayer = Objects.nonNull(client) ? client.getValue().toByte() : PlayerID.OBSERVER; + this.channel.send(Lists.prepended(serialized, activePlayer), client.getKey()); + } + } + } -- cgit v1.2.3