-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathServer.cs
362 lines (317 loc) · 11.5 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
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
using StardewValley;
using StardewValley.Quests;
using StardewValleyMP.Connections;
using StardewValleyMP.Interface;
using StardewValleyMP.Packets;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using SFarmer = StardewValley.Farmer;
namespace StardewValleyMP
{
// Anywhere in here 'Client' refers to the subclass, NOT the client-mode Client class
public class Server
{
public bool playing = false;
public bool delayUpdates = false;
public Server()
{
Multiplayer.sendFunc = broadcast;
}
private DateTime lastTimeSync;
public void update()
{
for (int i = 0; !delayUpdates && i < clients.Count; ++i )
{
clients[i].update();
if ( !clients[ i ].connected() )
{
clients.Remove( clients[ i ] );
--i;
continue;
}
}
if (Multiplayer.lobby) return;
if ( clients.Count == 0 )
{
ChatMenu.chat.Add(new ChatEntry(null, "No more clients."));
Multiplayer.mode = Mode.Singleplayer;
Multiplayer.server = null;
return;
}
if (playing && Game1.player != null)
{
Multiplayer.doMyPlayerUpdates(0);
if ((DateTime.Now - lastTimeSync).TotalMilliseconds >= 10000 /*&& Game1.timeOfDay % 100 == 0*/) // 10 seconds? Sure, why not
{
broadcast(new TimeSyncPacket());
lastTimeSync = DateTime.Now;
}
}/*
else if ( !playing && Game1.player != null )
{
bool othersReady = true;
foreach ( Server.Client client in clients )
{
othersReady = othersReady && ( client.stage == Client.NetStage.WaitingForStart );
}
if ( othersReady )
{
playing = true;
}
}*/
}
public void broadcast(Packet packet) { broadcast( packet, -1 ); } // Can't use default parameter because of passing as Action
public void broadcast(Packet packet, int except )
{
foreach ( Client client in clients )
{
if (client.id == except) continue;
client.send(packet);
}
}
public void getPlayerInfo()
{
Log.debug("Getting information on the clients.");
/*foreach ( Client client in clients )
{
client.send(new YourIDPacket(client.id));
}*/
// Wait for responses
foreach ( Client client in clients )
{
while ( client.stage != Client.NetStage.WaitingForStart )
{
client.update();
Thread.Sleep(10);
}
}
}
public void broadcastInfo()
{
Log.debug("Broadcasting world info.");
// World data packet is the same for everyone, so go ahead and prepare it
/*String saveFile = SaveGame.loaded.player.Name + "_" + SaveGame.loaded.uniqueIDForThisGame;
string worldPath = Path.Combine(new string[]
{
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"StardewValley",
"Saves",
saveFile,
saveFile
});
String xml = File.ReadAllText(worldPath);*/
MemoryStream tmp = new MemoryStream();
foreach ( var quest in SaveGame.loaded.player.questLog)
{
if (quest is SlayMonsterQuest)
(quest as SlayMonsterQuest).loadQuestInfo();
}
SaveGame.serializer.Serialize(tmp, SaveGame.loaded);
WorldDataPacket world = new WorldDataPacket(Encoding.UTF8.GetString(tmp.ToArray()));
foreach ( Client client in clients )
{
// Send other farmers first
OtherFarmerDataPacket others = new OtherFarmerDataPacket();
/*string savePath = Path.Combine(new string[]
{
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"StardewValley",
"Saves",
saveFile,
"SaveGameInfo"
});
String myXml = File.ReadAllText(savePath);*/
others.others.Add(0, Util.serialize<SFarmer>(SaveGame.loaded.player));
foreach ( Client other in clients )
{
if (client == other) continue;
others.others.Add(other.id, other.farmerXml );
}
client.send(others);
// Send world info
client.send(world);
client.stage = Client.NetStage.Playing;
}
lastTimeSync = DateTime.Now;
}
// Non-game stuff
// Client management
public List<Client> clients = new List<Client>();
public int currentlyAccepting { get; set; }
public void addClient(IConnection socket, bool askResend = false)
{
++currentlyAccepting;
Log.info("Got new client.");
Client client = new Client(this, (byte)getPlayerCount(), socket);
if (askResend)
{
client.send(new VersionPacket());
}
client.update();
while (client.stage == Client.NetStage.VerifyingVersion)
{
if (client.stageFailed)
{
Log.info("\tBad protocol version.");
return;
}
Thread.Sleep(10);
client.update();
}
clients.Add(client);
Log.trace("Finished accepting client");
}
public int getClientCount() { return clients.Count; }
public int getPlayerCount() { return clients.Count + 1; }
public class Client
{
public enum NetStage
{
VerifyingVersion,
WaitingForFarmerInfo,
WaitingForStart,
Playing,
}
private Server server;
public readonly byte id;
private IConnection socket;
private Thread receiver;
private BlockingCollection<Packet> toReceive = new BlockingCollection<Packet>( new ConcurrentQueue< Packet >());
public NetStage stage = NetStage.VerifyingVersion;
public bool stageFailed = false;
public string farmerXml = null;
public SFarmer farmer = null;
public int farmType = -1;
public bool sentId = false;
public IDictionary<string, GameLocation> addDuringLoading = new Dictionary<string, GameLocation>();
public Client(Server theServer, byte theId, IConnection theSocket)
{
server = theServer;
id = theId;
socket = theSocket;
receiver = new Thread( receiveAndQueue );
receiver.Start();
}
~Client()
{
if (socket != null)
{
socket.disconnect();
socket = null;
}
if (receiver != null)
{
receiver.Join();
receiver = null;
}
}
//public bool tempStopUpdating = false;
private Queue<Packet> packetDelay = new Queue<Packet>();
public void processDelayedPackets()
{
while (packetDelay.Count > 0)
{
packetDelay.Dequeue().process(server, this);
}
}
public bool connected()
{
return (socket != null);
}
public void update()
{
if (socket == null) return;
if (!socket.isConnected())
{
ChatMenu.chat.Add(new ChatEntry(null, ( farmer != null ? farmer.name : ( "Client " + id ) ) + " lost connection to the server."));
if ( farmer != null && farmer.currentLocation != null )
{
farmer.currentLocation.farmers.Remove(farmer);
}
socket = null;
return;
}
//if (tempStopUpdating) return;
if (stage != NetStage.WaitingForStart) processDelayedPackets();
try
{
while (toReceive.Count > 0)
{
Packet packet;
bool success = toReceive.TryTake(out packet);
if (!success) continue;
if (server.playing && stage == NetStage.WaitingForStart)
{
packetDelay.Enqueue(packet);
}
else packet.process(server, this);
}
}
catch ( Exception e )
{
Log.error("Exception receiving: " + e);
}
}
public void send( Packet packet )
{
#if false
try
{
using (MemoryStream s = new MemoryStream())
{
packet.writeTo(s);
byte[] bytes = s.GetBuffer();
stream.Write(bytes, 0, bytes.Length);
}
}
catch (Exception e)
{
Log.Async("Exception sending " + packet + " to client " + (farmer != null ? farmer.name : ("Client " + id)) + ": " + e);
}
#endif
#if NETWORKING_BENCHMARK
int bytes = packet.writeTo(stream);
Interlocked.Add(ref Multiplayer.serverToClientBytesTransferred, bytes);
Log.Async("Sent packet " + packet + " ( " + bytes + " bytes)");
#else
packet.writeTo(socket.getStream());
#endif
}
private void receiveAndQueue()
{
try
{
while (connected())
{
try
{
Packet packet = Packet.readFrom(socket.getStream());
toReceive.Add(packet);
}
catch ( Exception e )
{
Log.error("Exception while receiving: " + e);
socket.disconnect();
}
#if NETWORKING_BENCHMARK
using (MemoryStream tmpMs = new MemoryStream())
{
int bytes = packet.writeTo(tmpMs);
Interlocked.Add(ref Multiplayer.clientToServerBytesTransferred, bytes);
Log.Async("Received packet " + packet + " ( " + bytes + " bytes)");
}
#endif
}
}
catch ( Exception e )
{
}
}
}
}
}