aboutsummaryrefslogtreecommitdiff
path: root/src/ch/epfl/xblast/server/Server.java
blob: 3f486c60c20c86fafa2007629aface570062de7d (plain)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package ch.epfl.xblast.server;

import ch.epfl.xblast.Lists;
import ch.epfl.xblast.PlayerAction;
import ch.epfl.xblast.PlayerID;
import ch.epfl.xblast.Time;
import ch.epfl.xblast.server.painter.BoardPainter;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.StandardProtocolFamily;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.*;

/**
 * The Server class.
 *
 * @author Pacien TRAN-GIRARD (261948)
 */
public class Server {

    /**
     * Default parameters of the server.
     */
    private static final long REFRESH_RATE = (long) (50 * 1E6); // nanosecond
    private static final int DEFAULT_EXPECTED_CLIENTS = PlayerID.values().length;
    public static final int DEFAULT_PORT = 2016;

    /**
     * ID of an observer.
     */
    public static final byte OBSERVER = -1;

    /**
     * Print a log message on the console.
     *
     * @param message message to be printed
     */
    private static void log(String message) {
        System.out.println("[LOG] " + message);
    }

    /**
     * A Channel.
     */
    private static class Channel {

        /**
         * Transform a list of bytes to an array of bytes.
         *
         * @param l the given list of bytes
         * @return the array built from the given list
         */
        private static byte[] toByteArray(List<Byte> l) {
            byte[] arr = new byte[l.size()];

            for (int i = 0; i < l.size(); ++i)
                arr[i] = l.get(i);

            return arr;
        }

        /**
         * Create the socket which will be listened.
         *
         * @param host hostname
         * @param port port to be listened
         * @return the socket build from the given params
         */
        private static InetSocketAddress listeningInterface(String host, int port) {
            if (Objects.isNull(host))
                return new InetSocketAddress(port);
            else
                return new InetSocketAddress(host, port);
        }

        /**
         * Open a UDP channel.
         *
         * @param iface listened socket
         * @return a UDP channel
         */
        private static DatagramChannel openChannel(InetSocketAddress iface) {
            try {
                DatagramChannel chan = DatagramChannel.open(StandardProtocolFamily.INET);
                chan.bind(iface);
                return chan;
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
                return null;
            }
        }

        /**
         * The UDP communication channel.
         */
        private final DatagramChannel channel;

        /**
         * Instantiates a new Channel.
         *
         * @param iface listened socket
         */
        Channel(InetSocketAddress iface) {
            this.channel = openChannel(iface);
        }

        /**
         * Instantiates a new Channel.
         *
         * @param host hostname
         * @param port port to be listened
         */
        Channel(String host, Integer port) {
            this(listeningInterface(host, Optional.ofNullable(port).orElse(DEFAULT_PORT)));
        }

        /**
         * Close the channel.
         */
        void closeChannel() {
            try {
                this.channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        /**
         * Accept the registration of a new client.
         *
         * @param registrations
         * @return a list of the clients.
         */
        List<SocketAddress> acceptRegistrations(int registrations) {
            List<SocketAddress> clients = new ArrayList<>(registrations);

            while (clients.size() < registrations) {
                SocketAddress client = this.acceptRegistration();
                if (!clients.contains(client))
                    clients.add(client);
            }

            return Collections.unmodifiableList(clients);
        }

        /**
         * Collect actions from the players.
         *
         * @return a list map containing the actions related to each player
         */
        Map<SocketAddress, PlayerAction> collectActions() {
            Map<SocketAddress, PlayerAction> actions = new HashMap<>();
            Optional<Map.Entry<SocketAddress, PlayerAction>> action;

            while (true) {
                action = this.receiveAction(false);
                if (!action.isPresent()) break;
                actions.put(action.get().getKey(), action.get().getValue());
            }

            return Collections.unmodifiableMap(actions);
        }

        /**
         * Send data through the socket.
         *
         * @param content data to be send
         * @param dst recepient of the data
         */
        void send(List<Byte> content, SocketAddress dst) {
            try {
                ByteBuffer buf = ByteBuffer.wrap(toByteArray(content));
                this.channel.send(buf, dst);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        /**
         * Receive a Byte from the socket.
         *
         * @param block
         * @return an Optional containing the received data
         */
        private Optional<Map.Entry<SocketAddress, Byte>> receiveByte(boolean block) {
            try {
                ByteBuffer buf = ByteBuffer.allocate(1);
                this.channel.configureBlocking(block);
                SocketAddress client = this.channel.receive(buf);

                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();
            }
        }

        /**
         * Receive a player action from the socket.
         *
         * @param block
         * @return an Optional containing the received player action
         */
        private Optional<Map.Entry<SocketAddress, PlayerAction>> receiveAction(boolean block) {
            try {
                Map.Entry<SocketAddress, Byte> actionByte = this.receiveByte(block).get();
                PlayerAction playerAction = PlayerAction.fromByte(actionByte.getValue());
                return Optional.of(new AbstractMap.SimpleImmutableEntry<>(actionByte.getKey(), playerAction));
            } catch (NoSuchElementException | IllegalArgumentException e) {
                return Optional.empty();
            }
        }

        /**
         * Accept an action from the socket.
         *
         * @return the accepted action
         */
        private Map.Entry<SocketAddress, PlayerAction> acceptAction() {
            Optional<Map.Entry<SocketAddress, PlayerAction>> action;

            do {
                action = this.receiveAction(true);
            } while (!action.isPresent());

            return action.get();
        }

        /**
         * Accept the registration of a player
         *
         * @return the address of the new player
         */
        private SocketAddress acceptRegistration() {
            Map.Entry<SocketAddress, PlayerAction> clientAction;

            do {
                clientAction = this.acceptAction();
            } while (clientAction.getValue() != PlayerAction.JOIN_GAME);
            return clientAction.getKey();
        }

    }

    /**
     * The communication channel.
     */
    private final Channel channel;

    /**
     * Required number of player to start a game (up to 4).
     */
    private final int expectedClients;

    /**
     * Maps of the players and their addresses.
     */
    private Map<SocketAddress, PlayerID> registeredClientsMap;
    private Map<PlayerID, SocketAddress> playersAddressMap;

    /**
     * Instantiates a new server.
     *
     * @param iface the interface to be listened
     * @param port the port to be listened
     * @param expectedClients required number of player to start a game
     */
    public Server(String iface, Integer port, Integer expectedClients) {
        this.channel = new Channel(iface, port);
        this.expectedClients = Optional.ofNullable(expectedClients).orElse(DEFAULT_EXPECTED_CLIENTS);
    }

    /**
     * Run the whole server.
     */
    public void run() {
        log("Starting the server...");
        this.acceptClientRegistrations();
        this.runGame();
        this.channel.closeChannel();
    }

    /**
     * Handle the registration of new clients.
     */
    private void acceptClientRegistrations() {
        List<SocketAddress> clients = this.channel.acceptRegistrations(this.expectedClients);
        this.registeredClientsMap = Lists.linearAdjustedMap(clients, Arrays.asList(PlayerID.values()));
        this.playersAddressMap = Lists.invertMap(this.registeredClientsMap);
    }

    /**
     * Launch the Game.
     */
    private void runGame() {
        GameState gameState = GameState.DEFAULT_GAME_STATE;
        while (!gameState.isGameOver()) {
            long computationStartTime = System.nanoTime();
            gameState = updateGameState(gameState);
            broadcastGameState(gameState);
            Time.sleep(REFRESH_RATE - (computationStartTime - System.nanoTime()));
        }

        if (gameState.winner().isPresent())
            log("Winner : PLAYER_" + gameState.winner());
        else
            log("There is no winner.");
    }

    /**
     * Update the given GameState to the next tick.
     *
     * @param gs the given GameState
     * @return the updated GameState
     */
    private GameState updateGameState(GameState gs) {
        Map<PlayerID, PlayerAction> events = Lists.traverseMaps(this.playersAddressMap, this.channel.collectActions());
        return gs.next(events);
    }

    /**
     * Send the GameState to every player.
     *
     * @param gs the GameState to be send.
     */
    private void broadcastGameState(GameState gs) {
        List<Byte> serialized = GameStateSerializer.serialize(BoardPainter.DEFAULT_BOARD_PAINTER, gs);

        for (Map.Entry<SocketAddress, PlayerID> client : this.registeredClientsMap.entrySet()) {
            byte activePlayer = Objects.nonNull(client) ? client.getValue().toByte() : OBSERVER;
            this.channel.send(Lists.prepended(serialized, activePlayer), client.getKey());
        }
    }

}