-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathEnetUnityClient.cs
420 lines (367 loc) · 13 KB
/
EnetUnityClient.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
using DarkRift.Dispatching;
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using UnityEngine;
namespace DarkRift.Client.Unity
{
[AddComponentMenu("DarkRift/EnetClient")]
public sealed class EnetUnityClient : MonoBehaviour
{
/// <summary>
/// The IP address this client connects to.
/// </summary>
public IPAddress Address
{
get { return IPAddress.Parse(address); }
set { address = value.ToString(); }
}
[SerializeField]
[Tooltip("The address of the server to connect to.")]
string address = IPAddress.Loopback.ToString(); //Unity requires a serializable backing field so use string
/// <summary>
/// The port this client connects to.
/// </summary>
public ushort Port
{
get { return port; }
set { port = value; }
}
[SerializeField]
[Tooltip("The port the server is listening on.")]
ushort port = 4296;
/// <summary>
/// The IP version to connect with.
/// </summary>
public IPVersion IPVersion
{
get { return ipVersion; }
set { ipVersion = value; }
}
[SerializeField]
[Tooltip("The IP protocol version to connect using.")] //Declared in custom editor
IPVersion ipVersion = IPVersion.IPv4;
[SerializeField]
[Tooltip("Indicates whether the client will connect to the server in the Start method.")]
bool autoConnect = true;
[SerializeField]
[Tooltip("Specifies that DarkRift should take care of multithreading and invoke all events from Unity's main thread.")]
volatile bool invokeFromDispatcher = true;
[SerializeField]
[Tooltip("Specifies whether DarkRift should log all data to the console.")]
volatile bool sniffData = false;
[SerializeField]
[Tooltip("Specifies whether the client should receive messages in Update(), FixedUpdate() or manually")]
UpdateMode updateMode;
#region Cache settings
/// <summary>
/// The maximum number of <see cref="DarkRiftWriter"/> instances stored per thread.
/// </summary>
public int MaxCachedWriters
{
get
{
return maxCachedWriters;
}
}
[SerializeField]
[Tooltip("The maximum number of DarkRiftWriter instances stored per thread.")]
int maxCachedWriters = 2;
/// <summary>
/// The maximum number of <see cref="DarkRiftReader"/> instances stored per thread.
/// </summary>
public int MaxCachedReaders
{
get
{
return maxCachedReaders;
}
}
[SerializeField]
[Tooltip("The maximum number of DarkRiftReader instances stored per thread.")]
int maxCachedReaders = 2;
/// <summary>
/// The maximum number of <see cref="Message"/> instances stored per thread.
/// </summary>
public int MaxCachedMessages
{
get
{
return maxCachedMessages;
}
}
[SerializeField]
[Tooltip("The maximum number of Message instances stored per thread.")]
int maxCachedMessages = 8;
/// <summary>
/// The maximum number of <see cref="System.Net.Sockets.SocketAsyncEventArgs"/> instances stored per thread.
/// </summary>
public int MaxCachedSocketAsyncEventArgs
{
get
{
return maxCachedSocketAsyncEventArgs;
}
}
[SerializeField]
[Tooltip("The maximum number of SocketAsyncEventArgs instances stored per thread.")]
int maxCachedSocketAsyncEventArgs = 32;
/// <summary>
/// The maximum number of <see cref="ActionDispatcherTask"/> instances stored per thread.
/// </summary>
public int MaxCachedActionDispatcherTasks
{
get
{
return maxCachedActionDispatcherTasks;
}
}
[SerializeField]
[Tooltip("The maximum number of ActionDispatcherTask instances stored per thread.")]
int maxCachedActionDispatcherTasks = 16;
#endregion
/// <summary>
/// Event fired when a message is received.
/// </summary>
public event EventHandler<MessageReceivedEventArgs> MessageReceived;
/// <summary>
/// Event fired when we disconnect form the server.
/// </summary>
public event EventHandler<DisconnectedEventArgs> Disconnected;
/// <summary>
/// The ID the client has been assigned.
/// </summary>
public ushort ID
{
get
{
return Client.ID;
}
}
/// <summary>
/// Returns whether or not this client is connected to the server.
/// </summary>
[Obsolete("User ConnectionState instead.")]
public bool Connected
{
get
{
return Client.Connected;
}
}
/// <summary>
/// Returns the state of the connection with the server.
/// </summary>
public ConnectionState ConnectionState
{
get
{
return Client.ConnectionState;
}
}
/// <summary>
/// The actual client connecting to the server.
/// </summary>
/// <value>The client.</value>
public DarkRiftClient Client
{
get
{
return client;
}
}
DarkRiftClient client;
/// <summary>
/// The dispatcher for moving work to the main thread.
/// </summary>
public Dispatcher Dispatcher { get; private set; }
private EnetClientConnection enetConnnection;
void Awake()
{
client = new DarkRiftClient(maxCachedWriters, maxCachedReaders, maxCachedMessages, maxCachedSocketAsyncEventArgs, maxCachedActionDispatcherTasks);
//Setup dispatcher
Dispatcher = new Dispatcher(true);
//Setup routing for events
Client.MessageReceived += Client_MessageReceived;
Client.Disconnected += Client_Disconnected;
}
IEnumerator Start()
{
yield return new WaitForSeconds(1);
//If auto connect is true then connect to the server
if (autoConnect)
//Connect(Address, port, ipVersion);
ConnectInBackground(Address, port, IPVersion.IPv4);
}
void Update()
{
if (updateMode == UpdateMode.Update)
{
ReceiveMessages();
}
}
void FixedUpdate()
{
if (updateMode == UpdateMode.FixedUpdate)
{
ReceiveMessages();
}
}
/// <summary>
/// Call this to manually receive messages
/// </summary>
public void ReceiveMessages()
{
if (enetConnnection == null)
{
return;
}
enetConnnection.PerformUpdate();
Dispatcher.ExecuteDispatcherTasks();
}
void OnDestroy()
{
//Remove resources
Close();
Debug.Log("Destroy");
}
void OnApplicationQuit()
{
//Remove resources
Close();
Debug.Log("Quit");
}
/// <summary>
/// Connects to a remote server.
/// </summary>
/// <param name="ip">The IP address of the server.</param>
/// <param name="port">The port of the server.</param>
public void Connect(IPAddress ip, int port, IPVersion ipVersion)
{
enetConnnection = new EnetClientConnection(ip.ToString(), port);
client.Connect(enetConnnection);
//Client.Connect(ip, port, ipVersion);
if (ConnectionState == ConnectionState.Connected)
Debug.Log("Connected to " + ip + " on port " + port + " using " + ipVersion + ".");
else
Debug.Log("Connection failed to " + ip + " on port " + port + " using " + ipVersion + ".");
}
/// <summary>
/// Connects to a remote asynchronously.
/// </summary>
/// <param name="ip">The IP address of the server.</param>
/// <param name="port">The port of the server.</param>
/// <param name="callback">The callback to make when the connection attempt completes.</param>
public void ConnectInBackground(IPAddress ip, int port, IPVersion ipVersion, DarkRiftClient.ConnectCompleteHandler callback = null)
{
enetConnnection = new EnetClientConnection(ip.ToString(), port);
Client.ConnectInBackground(enetConnnection,
delegate (Exception e)
{
if (callback != null)
{
if (invokeFromDispatcher)
Dispatcher.InvokeAsync(() => callback(e));
else
callback.Invoke(e);
}
if (ConnectionState == ConnectionState.Connected)
Debug.Log("Connected to " + ip + " on port " + port + " using " + ipVersion + ".");
else
Debug.Log("Connection failed to " + ip + " on port " + port + " using " + ipVersion + ".");
}
);
}
/// <summary>
/// Sends a message to the server.
/// </summary>
/// <param name="message">The message template to send.</param>
/// <returns>Whether the send was successful.</returns>
public bool SendMessage(Message message, SendMode sendMode)
{
return Client.SendMessage(message, sendMode);
}
/// <summary>
/// Invoked when DarkRift receives a message from the server.
/// </summary>
/// <param name="sender">THe client that received the message.</param>
/// <param name="e">The arguments for the event.</param>
void Client_MessageReceived(object sender, MessageReceivedEventArgs e)
{
//If we're handling multithreading then pass the event to the dispatcher
if (invokeFromDispatcher)
{
if (sniffData)
Debug.Log("Message Received"); //TODO more information!
Dispatcher.InvokeAsync(
() =>
{
EventHandler<MessageReceivedEventArgs> handler = MessageReceived;
if (handler != null)
{
handler.Invoke(sender, e);
}
}
);
}
else
{
if (sniffData)
Debug.Log("Message Received"); //TODO more information!
EventHandler<MessageReceivedEventArgs> handler = MessageReceived;
if (handler != null)
{
handler.Invoke(sender, e);
}
}
}
void Client_Disconnected(object sender, DisconnectedEventArgs e)
{
//If we're handling multithreading then pass the event to the dispatcher
if (invokeFromDispatcher)
{
if (!e.LocalDisconnect)
Debug.Log("Disconnected from server, error: " + e.Error);
Dispatcher.InvokeAsync(
() =>
{
EventHandler<DisconnectedEventArgs> handler = Disconnected;
if (handler != null)
{
handler.Invoke(sender, e);
}
}
);
}
else
{
if (!e.LocalDisconnect)
Debug.Log("Disconnected from server, error: " + e.Error);
EventHandler<DisconnectedEventArgs> handler = Disconnected;
if (handler != null)
{
handler.Invoke(sender, e);
}
}
}
/// <summary>
/// Disconnects this client from the server.
/// </summary>
/// <returns>Whether the disconnect was successful.</returns>
public bool Disconnect()
{
return Client.Disconnect();
}
/// <summary>
/// Closes this client.
/// </summary>
public void Close()
{
Client.MessageReceived -= Client_MessageReceived;
Client.Disconnected -= Client_Disconnected;
Client.Dispose();
Dispatcher.Dispose();
}
}
}