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
|
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 {
public static final int DEFAULT_PORT = 2016;
private static final long REFRESH_RATE = (long) (50 * 1E6); // nanosecond
private static final int DEFAULT_EXPECTED_CLIENTS = PlayerID.values().length;
public static final byte OBSERVER = -1;
private static class Channel {
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;
}
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);
}
void send(List<Byte> content, SocketAddress dst) {
try {
ByteBuffer buf = ByteBuffer.wrap(toByteArray(content));
this.channel.send(buf, dst);
} catch (IOException e) {
e.printStackTrace();
}
}
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()) {
long computationStartTime = System.nanoTime();
gameState = updateGameState(updateGameState(gameState));
broadcastGameState(gameState);
Time.sleep(REFRESH_RATE - (computationStartTime - System.nanoTime()));
}
}
private GameState updateGameState(GameState gs) {
Map<PlayerID, PlayerAction> events = Lists.traverseMaps(this.playersAddressMap, this.channel.collectActions());
return gs.next(events);
}
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());
}
}
}
|