-
Notifications
You must be signed in to change notification settings - Fork 0
/
NetworkedCommanderClient.cs
270 lines (236 loc) · 8.22 KB
/
NetworkedCommanderClient.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
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
using System;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading;
using CSharpCTFStarter.Messages;
using CSharpCTFStarter.Messages.Client;
using CSharpCTFStarter.Messages.Server;
using CSharpCTFStarter.Objects;
using Newtonsoft.Json;
namespace CSharpCTFStarter
{
public class NetworkedCommanderClient
{
private readonly TcpClient _client;
private readonly ICommander _commander;
private readonly StreamReader _reader;
private readonly StreamWriter _writer;
private Game _game;
private NetworkedCommanderClient(TcpClient client, ICommander commander)
{
_client = client;
_commander = commander;
NetworkStream networkStream;
try
{
networkStream = _client.GetStream();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
_reader = new StreamReader(networkStream, Encoding.ASCII);
_writer = new StreamWriter(networkStream, Encoding.ASCII) { AutoFlush = true };
}
private void Run()
{
DoHandshaking();
Initialize();
while (true)
{
var line = ReadLine();
if (line == "<tick>") Tick();
else if (line == "<shutdown>")
{
_commander.ShutDown();
return;
}
else
{
throw new Exception("Expected <tick> or <shutdown>; received: " + line);
}
}
}
private void Tick()
{
var gameInfoJson = ReadLine();
var gameInfo = ReadJson<GameInfo>(gameInfoJson);
_game.Update(gameInfo);
_commander.Tick();
}
private void DoHandshaking()
{
Expect("<connect>");
var connectServerJson = ReadLine();
var connectServerMsg = ReadJson<ConnectServer>(connectServerJson);
const string EXPECTED_PROTOCOL_VERSION = "1.3";
if (EXPECTED_PROTOCOL_VERSION != connectServerMsg.protocolVersion)
{
throw new Exception(string.Format("Expected protocol version: {0}, server protocol version: {1}"
, EXPECTED_PROTOCOL_VERSION, connectServerMsg.protocolVersion));
}
var connectString = "<connect>\n" + WriteJson(new ConnectClient { commanderName = _commander.GetName() });
WriteLine(connectString);
}
private void Initialize()
{
Expect("<initialize>");
var levelInfoJson = ReadLine();
var levelInfo = ReadJson<LevelInfo>(levelInfoJson);
var gameInfoJson = ReadLine();
var gameInfo = ReadJson<GameInfo>(gameInfoJson);
_game = new Game(gameInfo, levelInfo, WriteAnyObject);
_commander.Initialize(_game);
WriteLine("<ready>");
}
private void Expect(string expected)
{
var msg = ReadLine();
if (msg != expected) throw new Exception("Expected: " + expected + "; got: " + msg);
}
private static T ReadJson<T>(string json)
{
return JsonConvert.DeserializeObject<Envelope<T>>(json).__value__;
}
private void WriteAnyObject(object obj)
{
string envelopeJson;
if (obj is Attack) envelopeJson = WriteJson((Attack)obj);
else if (obj is Charge) envelopeJson = WriteJson((Charge)obj);
else if (obj is Defend) envelopeJson = WriteJson((Defend)obj);
else if (obj is Move) envelopeJson = WriteJson((Move)obj);
else throw new Exception("Don't know how to write object: " + obj);
WriteLine("<command>\n" + envelopeJson);
}
private static string WriteJson<T>(T obj)
{
return JsonConvert.SerializeObject(new Envelope<T>(obj));
}
private string ReadLine()
{
string line;
try
{
line = _reader.ReadLine();
}
catch
{
_commander.ShutDown();
throw;
}
return line;
}
private void WriteLine(string line)
{
_writer.WriteLine(line);
}
public static int Main(string[] args)
{
string host = "localhost";
int port = 41041;
string commanderName = null;
if (args.Length == 1)
{
commanderName = args[0];
}
else if (args.Length == 3)
{
host = args[0];
port = int.Parse(args[1]);
commanderName = args[2];
}
else if (args.Length == 0)
{
// default commandername (null)
}
else if (args.Length == 2)
{
host = args[0];
port = int.Parse(args[1]);
// default commandername (null)
}
else
{
Console.WriteLine("Usage: CSharpCTFStarter [<hostname> <port>] [commander_name]");
Console.WriteLine("e.g. CSharpCTFStarter localhost 41041 My.MyCommander (Make sure that My.dll is present!)");
return 1;
}
var commander = commanderName == null
? LoadSingleCommander()
: LoadCommanderByName(commanderName);
if (commander == null)
{
Console.WriteLine("Unable to create commander");
return 1;
}
while (true)
{
Console.Write("Waiting for server ");
TcpClient tcpClient;
while (true)
{
Console.Write(".");
try
{
tcpClient = new TcpClient(host, port);
break;
}
catch
{
Thread.Sleep(2000);
}
}
Console.WriteLine("Connected!");
new NetworkedCommanderClient(tcpClient, commander).Run();
Console.WriteLine("Done");
tcpClient.Close();
}
}
private static ICommander LoadSingleCommander()
{
ICommander retVal = null;
var folder = new DirectoryInfo(Environment.CurrentDirectory);
foreach (var dll in folder.GetFiles("*.dll").Union(folder.GetFiles("*.exe")))
{
Assembly assembly;
try
{
assembly = Assembly.LoadFrom(dll.FullName);
}
catch
{
continue;
}
foreach (var type in assembly.GetTypes())
{
if (type == typeof(ICommander)) continue;
if (!typeof (ICommander).IsAssignableFrom(type)) continue;
if (retVal != null)
throw new Exception("Too many commander types present");
retVal = (ICommander) Activator.CreateInstance(type);
}
}
return retVal;
}
private static ICommander LoadCommanderByName(string commanderName)
{
var folder = new DirectoryInfo(Environment.CurrentDirectory);
foreach (var dll in folder.GetFiles("*.dll").Union(folder.GetFiles("*.exe")))
{
try
{
Assembly assembly = Assembly.LoadFrom(dll.FullName);
var commanderType = assembly.GetType(commanderName, false);
if (commanderType == null) continue;
return (ICommander)Activator.CreateInstance(commanderType);
}
catch { }
}
return null;
}
}
}