-
Notifications
You must be signed in to change notification settings - Fork 1
/
LLApiServer.cs
345 lines (317 loc) · 11.8 KB
/
LLApiServer.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
using UnityEngine.Networking;
using UnityEngine;
using System.Threading;
using System;
using System.Collections.Generic;
using UnityEngine.Networking.Types;
public class LLApiServer : IDisposable {
public int Port { get; private set; }
public ushort MaxConnections { get; private set; }
public ConnectionConfig Config { get; private set; }
public HostTopology Topology { get; private set; }
public int SocketId { get; private set; }
public bool isConnected { get; private set; }
public GameServer GameServer { get; private set; }
public ushort MaxMessages { get; private set; }
private Queue<InputMessage> InputMessagesQueue = new Queue<InputMessage>();
public delegate void SubjectDelegate(InputMessage message);
private Dictionary<Subjects, SubjectDelegate> SubjectHandlers = new Dictionary<Subjects, SubjectDelegate>();
private object lockHandlers = new object();
private Dictionary<int, LLApiConnection> Connections = new Dictionary<int, LLApiConnection>();
private object lockConnectionObject = new object();
private object lockPocessObject = new object();
private Thread[] ProcessWorkers;
private ushort workerProcessCount = 1;
private bool Disconnect = false;
private bool _stop = false;
private Queue<OutputMessage> OutputMessagesQueue = new Queue<OutputMessage>();
private object lockOutputObject = new object();
public LLApiServer(GameServer gameServer, int port, ushort maxConnections, ushort maxMessages)
{
GameServer = gameServer;
Port = port;
MaxConnections = maxConnections;
MaxMessages = maxMessages;
isConnected = false;
Config = new ConnectionConfig();
int ReliableChannelId = Config.AddChannel(QosType.Reliable);
int NonReliableChannelId = Config.AddChannel(QosType.Unreliable);
Topology = new HostTopology(Config, MaxConnections);
}
public void RegisterHandler(Subjects subject, SubjectDelegate handler){
lock (lockHandlers)
{
SubjectDelegate handlerDelegate;
if (SubjectHandlers.TryGetValue(subject, out handlerDelegate))
{
handlerDelegate += handler;
}
else
{
SubjectHandlers.Add(subject, handler);
}
}
}
public bool RemoveHandler(Subjects subject, SubjectDelegate handler)
{
lock (lockHandlers)
{
SubjectDelegate handlerDelegate;
if (!SubjectHandlers.TryGetValue(subject, out handlerDelegate))
{
return false;
}
handlerDelegate -= handler;
return true;
}
}
public bool SendMessage(int connectionId, NetworkWriter writer, out NetworkError Error)
{
return SendMessage(connectionId, writer, 0, out Error);
}
public bool SendMessage(int connectionId, NetworkWriter writer, int channel, out NetworkError Error)
{
byte error;
byte[] buffer = writer.ToArray();
NetworkTransport.Send(SocketId, connectionId, channel, buffer, buffer.Length, out error);
Error = (NetworkError)error;
if (Error != NetworkError.Ok)
{
return true;
}
else
{
return false;
}
}
public void Start()
{
Disconnect = false;
GlobalConfig gConfig = new GlobalConfig();
NetworkTransport.Init(gConfig);
SocketId = NetworkTransport.AddHost(Topology, Port);
ProcessWorkers = new Thread[workerProcessCount];
// Create and start a separate thread for each worker
for (int i = 0; i < workerProcessCount; i++)
{
ProcessWorkers[i] = new Thread(MessagesConsumer);
ProcessWorkers[i].Name = "LLApi Process Thread " + i;
ProcessWorkers[i].Start();
}
}
private void addConnection(LLApiConnection connection)
{
lock (lockConnectionObject)
{
Connections.Add(connection.ConnectionId, connection);
}
}
public bool TryGetConnection(int connectionId, out LLApiConnection connection)
{
connection = null;
lock (lockConnectionObject)
{
return Connections.TryGetValue(connectionId, out connection);
}
}
private bool removeConnection(int connectionId)
{
lock (lockConnectionObject)
{
return Connections.Remove(connectionId);
}
}
private void addInputMessageToQueue(InputMessage message)
{
lock (lockPocessObject)
{
if (message != null)
{
Debug.Log("Message Added to Queue : " + message.MsgSubject);
}
InputMessagesQueue.Enqueue(message);
Monitor.PulseAll(lockPocessObject);
}
}
public void addOutPutMessageToQueue(OutputMessage message)
{
lock (lockOutputObject)
{
OutputMessagesQueue.Enqueue(message);
}
}
private void MessagesConsumer()
{
try
{
while (true)
{
InputMessage message;
lock (lockPocessObject)
{
while (InputMessagesQueue.Count == 0)
{
Monitor.Wait(lockPocessObject);
}
message = InputMessagesQueue.Dequeue();
}
if (message == null) return;
lock (lockHandlers)
{
SubjectDelegate handlerDelegate;
if(SubjectHandlers.TryGetValue(message.MsgSubject, out handlerDelegate))
{
handlerDelegate.Invoke(message);
}
}
}
}
catch (Exception e)
{
Debug.LogException(e);
}
}
public void SendOutputMessages()
{
bool stopSending = false;
ushort messagesSended = 0;
while (!Disconnect && !stopSending)
{
OutputMessage message;
lock (lockOutputObject)
{
if (OutputMessagesQueue.Count == 0)
{
stopSending = true;
continue;
}
message = OutputMessagesQueue.Dequeue();
}
if (message == null) continue;
messagesSended += ManageOutputMessage(message);
if(messagesSended>= MaxMessages)
{
stopSending = true;
}
}
}
private ushort ManageOutputMessage(OutputMessage message)
{
NetworkError error;
ushort messagesSended = 0;
switch (message.Type)
{
case OutputMessage.MessageType.Reply:
SendMessage(message.ConnectionID, message.Data, message.ChannelID, out error);
messagesSended = 1;
break;
case OutputMessage.MessageType.All:
List<int> connectionIDS = GameServer.UserManager.getConnectedUsersConnectionsID();
foreach (int connectionID in connectionIDS)
{
SendMessage(connectionID, message.Data, message.ChannelID, out error);
}
messagesSended = (ushort)connectionIDS.Count;
break;
}
return messagesSended;
}
public void Listen()
{
bool stopListen = false;
ushort messagesReaded = 0;
while (!Disconnect && !stopListen)
{
messagesReaded++;
int recConnectionId;
int recChannelId;
byte[] recBuffer = new byte[1024];
int bufferSize = 1024;
int dataSize;
byte error;
NetworkReader reader;
InputMessage message;
NetworkEventType recNetworkEvent;
try {
recNetworkEvent = NetworkTransport.ReceiveFromHost(SocketId, out recConnectionId, out recChannelId, recBuffer, bufferSize, out dataSize, out error);
if (error != (byte)NetworkError.Ok)
{
Debug.Log("Error [" + (NetworkError)error + "] receiving a Message from : " + SocketId + " | conID : " + recConnectionId + " | channel : " + recChannelId);
}
else
{
switch (recNetworkEvent)
{
case NetworkEventType.Nothing:
stopListen = true;
break;
case NetworkEventType.ConnectEvent:
string address;
int remotePort;
NetworkID networkID;
NodeID nodeID;
NetworkTransport.GetConnectionInfo(SocketId, recConnectionId, out address, out remotePort, out networkID, out nodeID, out error);
if (error == (byte)NetworkError.Ok)
{
LLApiConnection connection = new LLApiConnection(recConnectionId, address, remotePort);
addConnection(connection);
}
reader = new NetworkReader(recBuffer);
message = new InputMessage(recConnectionId, SocketId, recChannelId, Subjects.Connect, reader, GameServer.getServerTime());
addInputMessageToQueue(message);
Debug.Log("New Connection: " + SocketId + "[" + address + ":" + remotePort + "] con: " + recConnectionId + " Size: " + dataSize);
break;
case NetworkEventType.DataEvent:
Debug.Log("Incoming message Dataevent received: " + SocketId + " con: " + recConnectionId + " Size: " + dataSize);
reader = new NetworkReader(recBuffer);
Subjects subject = (Subjects)reader.ReadUInt16();
message = new InputMessage(recConnectionId, SocketId, recChannelId, subject, reader, GameServer.getServerTime());
addInputMessageToQueue(message);
break;
case NetworkEventType.DisconnectEvent:
Debug.Log("Remote client event disconnected: " + SocketId + " con: " + recConnectionId + " Size: " + dataSize);
reader = new NetworkReader(recBuffer);
message = new InputMessage(recConnectionId, SocketId, recChannelId, Subjects.Disconnect, reader, GameServer.getServerTime());
addInputMessageToQueue(message);
removeConnection(recConnectionId);
break;
}
}
}catch(Exception e)
{
Debug.LogError("LLApiServer Error Receiving Data : " + e.Message);
Debug.LogException(e);
}
finally
{
if (messagesReaded >= MaxMessages)
{
stopListen = true;
}
}
}
}
public void Stop()
{
_stop = true;
Disconnect = true;
if (isConnected)
{
NetworkTransport.RemoveHost(SocketId);
Debug.Log("LLApiServer Shutting Down");
}
// Enqueue one null task per worker to make each exit.
for (int i = 0; i < ProcessWorkers.Length; i++)
{
addInputMessageToQueue(null);
}
foreach (Thread worker in ProcessWorkers) worker.Join();
}
public void Dispose()
{
if (!_stop)
{
Stop();
}
}
}