forked from FizzCube/FizzySteamyMirror
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Server.cs
329 lines (276 loc) · 11.8 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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using Steamworks;
using System.Threading.Tasks;
namespace Mirror.FizzySteam
{
internal class SteamClient
{
public enum ConnectionState
{
CONNECTED,
DISCONNECTING,
}
public CSteamID steamID;
public ConnectionState state;
public int connectionID;
public float timeIdle = 0;
public SteamClient(ConnectionState state, CSteamID steamID, int connectionID)
{
this.state = state;
this.steamID = steamID;
this.connectionID = connectionID;
this.timeIdle = 0;
}
}
internal class SteamConnectionMap : IEnumerable<KeyValuePair<int, SteamClient>>
{
public readonly Dictionary<CSteamID, SteamClient> fromSteamID = new Dictionary<CSteamID, SteamClient>();
public readonly Dictionary<int, SteamClient> fromConnectionID = new Dictionary<int, SteamClient>();
public SteamConnectionMap()
{
}
public int Count
{
get { return fromSteamID.Count; }
}
public SteamClient Add(CSteamID steamID, int connectionID, SteamClient.ConnectionState state)
{
var newClient = new SteamClient(state, steamID, connectionID);
fromSteamID.Add(steamID, newClient);
fromConnectionID.Add(connectionID, newClient);
return newClient;
}
public void Remove(SteamClient steamClient)
{
fromSteamID.Remove(steamClient.steamID);
fromConnectionID.Remove(steamClient.connectionID);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<KeyValuePair<int, SteamClient>> GetEnumerator()
{
return fromConnectionID.GetEnumerator();
}
}
public class Server : Common
{
enum ConnectionState : byte
{
OFFLINE,
LISTENING
}
public event Action<int> OnConnected;
public event Action<int, byte[], int> OnReceivedData;
public event Action<int> OnDisconnected;
public event Action<int, Exception> OnReceivedError;
private ConnectionState state = ConnectionState.OFFLINE;
private SteamConnectionMap steamConnectionMap;
private int nextConnectionID;
private int maxConnections;
public bool Listening { get { return state == ConnectionState.LISTENING; } private set { if (value) state = ConnectionState.LISTENING; } }
public bool Offline
{
get { return state == ConnectionState.OFFLINE; }
private set
{
if (value)
{
state = ConnectionState.OFFLINE;
deinitialise();
}
}
}
public async void Listen(int maxConnections = int.MaxValue)
{
Debug.Log("Listen Start");
//todo check we are not already listening ?
initialise();
Listening = true;
this.maxConnections = maxConnections;
InternalReceiveLoop();
await ReceiveLoop();
Debug.Log("Listen Stop");
}
protected override void OnNewConnectionInternal(P2PSessionRequest_t result)
{
Debug.Log("OnNewConnectionInternal in server");
SteamNetworking.AcceptP2PSessionWithUser(result.m_steamIDRemote);
}
//start a async loop checking for internal messages and processing them. This includes internal connect negotiation and disconnect requests so runs outside "connected"
private async void InternalReceiveLoop()
{
Debug.Log("InternalReceiveLoop Start");
uint readPacketSize;
CSteamID clientSteamID;
try
{
while (!Offline)
{
while (ReceiveInternal(out readPacketSize, out clientSteamID))
{
Debug.Log("InternalReceiveLoop - data");
if (readPacketSize != 1)
{
continue;
}
Debug.Log("InternalReceiveLoop - received " + receiveBufferInternal[0]);
switch (receiveBufferInternal[0])
{
//requesting to connect to us
case (byte)InternalMessages.CONNECT:
if(steamConnectionMap.Count >= maxConnections)
{
SendInternal(clientSteamID, disconnectMsgBuffer);
continue;
//too many connections, reject
}
SendInternal(clientSteamID, acceptConnectMsgBuffer);
int connectionId = nextConnectionID++;
steamConnectionMap.Add(clientSteamID, connectionId, SteamClient.ConnectionState.CONNECTED);
OnConnected?.Invoke(connectionId);
break;
//asking us to disconnect
case (byte)InternalMessages.DISCONNECT:
try
{
SteamClient steamClient = steamConnectionMap.fromSteamID[clientSteamID];
steamConnectionMap.Remove(steamClient);
OnDisconnected?.Invoke(steamClient.connectionID);
CloseP2PSessionWithUser(steamClient.steamID);
}
catch (KeyNotFoundException)
{
//we have no idea who this connection is
Debug.LogError("Trying to disconnect a client thats not known SteamID " + clientSteamID);
OnReceivedError?.Invoke(-1, new Exception("ERROR Unknown SteamID"));
}
break;
}
}
//not got a message - wait a bit more
await Task.Delay(TimeSpan.FromSeconds(secondsBetweenPolls));
}
}
catch (ObjectDisposedException) { }
Debug.Log("InternalReceiveLoop Stop");
}
private async Task ReceiveLoop()
{
Debug.Log("ReceiveLoop Start");
uint readPacketSize;
CSteamID clientSteamID;
try
{
byte[] receiveBuffer;
while (!Offline)
{
for (int i = 0; i < channels.Length; i++) {
while (Receive(out readPacketSize, out clientSteamID, out receiveBuffer, i)) {
if (readPacketSize == 0) {
continue;
}
try {
int connectionId = steamConnectionMap.fromSteamID[clientSteamID].connectionID;
// we received some data, raise event
OnReceivedData?.Invoke(connectionId, receiveBuffer,i);
} catch (KeyNotFoundException) {
CloseP2PSessionWithUser(clientSteamID);
//we have no idea who this connection is
Debug.LogError("Data received from steam client thats not known " + clientSteamID);
OnReceivedError?.Invoke(-1, new Exception("ERROR Unknown SteamID"));
}
}
}
//not got a message - wait a bit more
await Task.Delay(TimeSpan.FromSeconds(secondsBetweenPolls));
}
}
catch (ObjectDisposedException) { }
Debug.Log("ReceiveLoop Stop");
}
// check if the server is running
public bool Active
{
get { return Listening; }
}
public void Stop()
{
Debug.LogWarning("Server Stop");
// only if started
if (!Active) return;
Offline = true;
deinitialise();
Debug.Log("Server Stop Finished");
}
// disconnect (kick) a client
public bool Disconnect(int connectionId)
{
try
{
SteamClient steamClient = steamConnectionMap.fromConnectionID[connectionId];
Disconnect(steamClient);
return true;
}
catch (KeyNotFoundException)
{
//we have no idea who this connection is
Debug.LogWarning("Trying to disconnect a connection thats not known " + connectionId);
}
return false;
}
private async void Disconnect(SteamClient steamClient)
{
if(steamClient.state != SteamClient.ConnectionState.CONNECTED)
{
return;
}
SendInternal(steamClient.steamID, disconnectMsgBuffer);
steamClient.state = SteamClient.ConnectionState.DISCONNECTING;
//Wait a short time before calling steams disconnect function so the message has time to go out
await Task.Delay(100);
steamConnectionMap.Remove(steamClient);
OnDisconnected?.Invoke(steamClient.connectionID);
CloseP2PSessionWithUser(steamClient.steamID);
}
public bool Send(List<int> connectionIds, byte[] data, int channelId = 0) {
for (int i = 0; i < connectionIds.Count; i++) {
try {
SteamClient steamClient = steamConnectionMap.fromConnectionID[connectionIds[i]];
//will default to reliable at channel 0 if sent on an unknown channel
Send(steamClient.steamID, data, channelToSendType(channelId), channelId >= channels.Length ? 0 : channelId);
} catch (KeyNotFoundException) {
//we have no idea who this connection is
Debug.LogError("Tryign to Send on a connection thats not known " + connectionIds[i]);
OnReceivedError?.Invoke(connectionIds[i], new Exception("ERROR Unknown Connection"));
}
}
return true;
}
public string ServerGetClientAddress(int connectionId)
{
try
{
SteamClient steamClient = steamConnectionMap.fromConnectionID[connectionId];
return steamClient.steamID.ToString();
}
catch (KeyNotFoundException)
{
//we have no idea who this connection is
Debug.LogError("Trying to get info on an unknown connection " + connectionId);
OnReceivedError?.Invoke(connectionId, new Exception("ERROR Unknown Connection"));
}
return null;
}
protected override void initialise()
{
base.initialise();
nextConnectionID = 1;
steamConnectionMap = new SteamConnectionMap();
}
}
}