aboutsummaryrefslogtreecommitdiff
path: root/src/ch/epfl/xblast/server/Server.java
blob: 0989d556c6ebdd28ecf95a9c01ba506f1c955792 (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
package ch.epfl.xblast.server;

import ch.epfl.xblast.Lists;
import ch.epfl.xblast.PlayerAction;
import ch.epfl.xblast.PlayerID;

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 {

    public static final int DEFAULT_PORT = 2016;
    private static final int DEFAULT_EXPECTED_CLIENTS = PlayerID.values().length;

    private static class Channel {

        private static InetSocketAddress listeningInterface(String host, int port) {
            if (Objects.isNull(host))
                return new InetSocketAddress(port);
            else
                return new InetSocketAddress(host, port);
        }

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

        private final DatagramChannel channel;

        Channel(InetSocketAddress iface) {
            this.channel = openChannel(iface);
        }

        Channel(String host, Integer port) {
            this(listeningInterface(host, Optional.ofNullable(port).orElse(DEFAULT_PORT)));
        }

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

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

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

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

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

        private Map.Entry<SocketAddress, PlayerAction> acceptAction() {
            Optional<Map.Entry<SocketAddress, PlayerAction>> action;

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

            return action.get();
        }

        private SocketAddress acceptRegistration() {
            Map.Entry<SocketAddress, PlayerAction> clientAction;

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

            return clientAction.getKey();
        }

    }

    private final Channel channel;
    private final int expectedClients;

    private Map<SocketAddress, PlayerID> registeredClientsMap;
    private Map<PlayerID, SocketAddress> playersAddressMap;

    public Server(String iface, Integer port, Integer expectedClients) {
        this.channel = new Channel(iface, port);
        this.expectedClients = Optional.ofNullable(expectedClients).orElse(DEFAULT_EXPECTED_CLIENTS);
    }

    public void run() {
        this.acceptClientRegistrations();
        this.runGame();
        this.channel.closeChannel();
    }

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

    private void runGame() {
        GameState gameState = GameState.DEFAULT_GAME_STATE;

        while (!gameState.isGameOver()) {
            gameState = updateGameState(updateGameState(gameState));
            // TODO: send updated game state to clients

            try {
                Thread.sleep(10000);
                // TODO: adapt sleeping time
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private GameState updateGameState(GameState gs) {
        Map<PlayerID, PlayerAction> events = Lists.traverseMaps(this.playersAddressMap, this.channel.collectActions());
        return gs.next(events);
    }

}