-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.cs
83 lines (72 loc) · 2.82 KB
/
Server.cs
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
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using StrategicGame.Common;
namespace StrategicGame.Server {
using RemoteClient = RemoteSide<Command, StatePortion>;
class Server : IDisposable {
static readonly IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 4040);
World _world;
Action<string> _log;
List<RemoteClient> _remoteClients = new List<RemoteClient>();
public Server(Action<string> log) {
_world = World.RandomWorld(Consts.STEPS_PER_SECOND);
_log = log;
Log("Generated {0}", _world);
}
public void Execute() {
var acceptor = new ClientAcceptor(endPoint);
var clientCommands = new List<Command>();
while (true) {
IntroduceNewClients(acceptor);
RemoveDisconnectedClients();
FetchClientCommands(clientCommands);
var stateDelta = _world.Simulate(clientCommands);
clientCommands.Clear();
SendToClients(stateDelta);
Thread.Sleep(1000 / Consts.STEPS_PER_SECOND);
}
}
public void Dispose() {
foreach (var client in _remoteClients)
client.Dispose();
}
void IntroduceNewClients(ClientAcceptor acceptor) {
TcpClient client;
while ((client = acceptor.PullClient()) != null) {
var remoteClient = new RemoteClient(client, Command.Deserialize);
Log("Client connected: {0}", remoteClient.RemoteEndPoint);
remoteClient.WriteMessages(_world.InstantState);
_remoteClients.Add(remoteClient);
}
}
void RemoveDisconnectedClients() {
for (int i = _remoteClients.Count - 1; i >= 0; --i) {
var client = _remoteClients[i];
if (!client.Connected) {
Log("Client disconnected: {0}", client.RemoteEndPoint);
client.Dispose();
_remoteClients.RemoveAt(i);
}
}
}
void FetchClientCommands(List<Command> clientCommands) {
foreach (var client in _remoteClients) {
Command cmd;
while ((cmd = client.ReadMessage()) != null) {
Log("{0} says: {1}", client.RemoteEndPoint, cmd);
clientCommands.Add(cmd);
}
}
}
void SendToClients(List<StatePortion> state) {
foreach (var client in _remoteClients)
client.WriteMessages(state);
}
void Log(string message, params object[] args) {
_log(string.Format(message, args));
}
}
}