-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathEOSPeer2PeerManager.cs
More file actions
580 lines (494 loc) · 20.8 KB
/
EOSPeer2PeerManager.cs
File metadata and controls
580 lines (494 loc) · 20.8 KB
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
/*
* Copyright (c) 2026 Epic Games Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace PlayEveryWare.EpicOnlineServices.Samples
{
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using Epic.OnlineServices;
using Epic.OnlineServices.P2P;
using PlayEveryWare.EpicOnlineServices.Utility;
/// <summary>
/// Struct <c>ChatEntry</c> is used to store cached chat data in <c>UIPeer2PeerMenu</c>.
/// </summary>
public struct ChatEntry
{
/// <value>True if message was from local user</value>
public bool isOwnEntry;
/// <value> Cache for message entry </value>
public string Message;
}
/// <summary>
/// Struct <c>ChatWithFriendData</c> is used to store cached friend chat data in <c>UIPeer2PeerMenu</c>.
/// </summary>
public struct ChatWithFriendData
{
/// <value> Queue of cached <c>ChatEntry</c> objects </value>
public Queue<ChatEntry> ChatLines;
/// <value> <c>FriendId</c> of remote friend </value>
public ProductUserId FriendId;
/// <summary> Constructor for creating a new local cache of chat entries.</summary>
/// <param name="FriendId"><c>ProductUserId</c> of remote friend</param>
public ChatWithFriendData(ProductUserId FriendId)
{
this.FriendId = FriendId;
ChatLines = new Queue<ChatEntry>();
}
}
/// <summary>
/// Class <c>EOSPeer2PeerManager</c> is a simplified wrapper for EOS [P2P Interface](https://dev.epicgames.com/docs/services/en-US/Interfaces/P2P/index.html).
/// </summary>
public enum messageType
{
textMessage,
coordinatesMessage
};
public struct messageData
{
public messageType type;
public string textData;
public float xPos;
public float yPos;
};
public class EOSPeer2PeerManager : IEOSSubManager
{
private P2PInterface P2PHandle;
private ulong ConnectionNotificationId;
private ulong ConnectionEstablishedNotificationId;
private ulong ConnectionInterruptedNotificationId;
private Dictionary<ProductUserId, ChatWithFriendData> ChatDataCache;
private bool ChatDataCacheDirty;
public UIPeer2PeerParticleController ParticleController;
public Transform parent;
private enum PeerConnectionAppState
{
NotConnected,
IceConnected,
HandshakePending,
FullyConnected
}
private Dictionary<ProductUserId, PeerConnectionAppState> connectionStates = new();
private string Request = "hreq";
private string Acknowledgement = "hack";
private string Ping = "ping";
#if UNITY_EDITOR
void OnPlayModeChanged(UnityEditor.PlayModeStateChange modeChange)
{
if (modeChange == UnityEditor.PlayModeStateChange.ExitingPlayMode)
{
//prevent attempts to call native EOS code while exiting play mode, which crashes the editor
P2PHandle = null;
}
}
#endif
public EOSPeer2PeerManager()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.playModeStateChanged -= OnPlayModeChanged;
UnityEditor.EditorApplication.playModeStateChanged += OnPlayModeChanged;
#endif
P2PHandle = EOSManager.Instance.GetEOSPlatformInterface().GetP2PInterface();
ChatDataCache = new Dictionary<ProductUserId, ChatWithFriendData>();
ChatDataCacheDirty = true;
}
#if UNITY_EDITOR
~EOSPeer2PeerManager()
{
UnityEditor.EditorApplication.playModeStateChanged -= OnPlayModeChanged;
}
#endif
public bool GetChatDataCache(out Dictionary<ProductUserId, ChatWithFriendData> ChatDataCache)
{
ChatDataCache = this.ChatDataCache;
return ChatDataCacheDirty;
}
public void Initialize()
{
SubscribeToConnectionRequest();
var localUserId = EOSManager.Instance.GetProductUserId();
var establishedOptions = new AddNotifyPeerConnectionEstablishedOptions
{
LocalUserId = localUserId
};
ConnectionEstablishedNotificationId = P2PHandle.AddNotifyPeerConnectionEstablished(ref establishedOptions, null, OnPeerConnectionEstablished);
var interruptedOptions = new AddNotifyPeerConnectionInterruptedOptions
{
LocalUserId = localUserId,
SocketId = null
};
ConnectionInterruptedNotificationId = P2PHandle.AddNotifyPeerConnectionInterrupted(ref interruptedOptions, null, OnPeerConnectionInterrupted);
Debug.Log("EOSPeer2PeerManager initialized: connection listeners registered.");
}
private void RefreshNATType()
{
var options = new QueryNATTypeOptions();
P2PHandle.QueryNATType(ref options, null, OnRefreshNATTypeFinished);
}
public NATType GetNATType()
{
var options = new GetNATTypeOptions();
Result result = P2PHandle.GetNATType(ref options, out NATType natType);
if (result == Result.NotFound)
{
return NATType.Unknown;
}
if (result != Result.Success)
{
Debug.LogErrorFormat("EOS P2PNAT GetNatType: error while retrieving NAT Type: {0}", result);
return NATType.Unknown;
}
return natType;
}
public void OnLoggedIn()
{
RefreshNATType();
SubscribeToConnectionRequest();
}
public void OnLoggedOut()
{
UnsubscribeFromConnectionRequests();
if (ConnectionEstablishedNotificationId != 0)
{
P2PHandle.RemoveNotifyPeerConnectionEstablished(ConnectionEstablishedNotificationId);
ConnectionEstablishedNotificationId = 0;
}
if (ConnectionInterruptedNotificationId != 0)
{
P2PHandle.RemoveNotifyPeerConnectionInterrupted(ConnectionInterruptedNotificationId);
ConnectionInterruptedNotificationId = 0;
}
}
private void OnRefreshNATTypeFinished(ref OnQueryNATTypeCompleteInfo data)
{
//if (data == null)
//{
// Debug.LogError("P2P (OnRefreshNATTypeFinished): data is null");
// return;
//}
if (data.ResultCode != Result.Success)
{
Debug.LogErrorFormat("P2p (OnRefreshNATTypeFinished): RefreshNATType error: {0}", data.ResultCode);
return;
}
Debug.Log("P2p (OnRefreshNATTypeFinished): RefreshNATType Completed");
}
public void SendMessage(ProductUserId friendId, messageData message)
{
if (!friendId.IsValid())
{
Debug.LogError("EOS P2PNAT SendMessage: bad input data: account id is wrong.");
return;
}
if (!connectionStates.TryGetValue(friendId, out var state) || state != PeerConnectionAppState.FullyConnected)
{
Debug.LogWarning($"SendMessage: Cannot send to {friendId}, not fully connected (State={state}).");
return;
}
if (message.type == messageType.textMessage)
{
if (string.IsNullOrEmpty(message.textData))
{
Debug.LogError("EOS P2PNAT SendMessage: bad input data message is empty.");
return;
}
// Update Cache
ChatEntry chatEntry = new ChatEntry()
{
isOwnEntry = true,
Message = message.textData
};
if (ChatDataCache.TryGetValue(friendId, out ChatWithFriendData chatData))
{
chatData.ChatLines.Enqueue(chatEntry);
ChatDataCacheDirty = true;
}
else
{
ChatWithFriendData newChatData = new ChatWithFriendData(friendId);
newChatData.ChatLines.Enqueue(chatEntry);
ChatDataCache.Add(friendId, newChatData);
ChatDataCacheDirty = true;
}
// Send Message
SocketId socketId = new SocketId()
{
SocketName = "CHAT"
};
SendPacketOptions options = new SendPacketOptions()
{
LocalUserId = EOSManager.Instance.GetProductUserId(),
RemoteUserId = friendId,
SocketId = socketId,
AllowDelayedDelivery = true,
Channel = 0,
Reliability = PacketReliability.ReliableOrdered,
Data = new ArraySegment<byte>(Encoding.UTF8.GetBytes("t" + message.textData))
};
Result result = P2PHandle.SendPacket(ref options);
if (result != Result.Success)
{
Debug.LogErrorFormat("EOS P2PNAT SendMessage: error while sending data, code: {0}", result);
return;
}
Debug.Log("EOS P2PNAT SendMessage: Message successfully sent to user.");
}
else if (message.type == messageType.coordinatesMessage)
{
string rawData = ("m" + message.xPos.ToString() + "," + message.yPos.ToString());
// Send Message
SocketId socketId = new SocketId()
{
SocketName = "CHAT"
};
SendPacketOptions options = new SendPacketOptions()
{
LocalUserId = EOSManager.Instance.GetProductUserId(),
RemoteUserId = friendId,
SocketId = socketId,
AllowDelayedDelivery = true,
Channel = 0,
Reliability = PacketReliability.ReliableOrdered,
Data = new ArraySegment<byte>(Encoding.UTF8.GetBytes(rawData))
};
Result result = P2PHandle.SendPacket(ref options);
if (result != Result.Success)
{
Debug.LogErrorFormat("EOS P2PNAT SendMessage: error while sending data, code: {0}", result);
return;
}
}
else
{
Debug.Log("EOS P2PNAT SendMessage: Message content was not valid.");
}
}
public ProductUserId HandleReceivedMessages()
{
if (P2PHandle == null)
{
return null;
}
ReceivePacketOptions options = new ReceivePacketOptions()
{
LocalUserId = EOSManager.Instance.GetProductUserId(),
MaxDataSizeBytes = 4096,
RequestedChannel = null
};
var getNextReceivedPacketSizeOptions = new GetNextReceivedPacketSizeOptions
{
LocalUserId = EOSManager.Instance.GetProductUserId(),
RequestedChannel = null
};
P2PHandle.GetNextReceivedPacketSize(ref getNextReceivedPacketSizeOptions, out uint nextPacketSizeBytes);
if (nextPacketSizeBytes == 0)
{
return null;
}
byte[] data = new byte[nextPacketSizeBytes];
var dataSegment = new ArraySegment<byte>(data);
ProductUserId peerId = null;
SocketId socketId = default;
Result result = P2PHandle.ReceivePacket(ref options, ref peerId, ref socketId, out byte outChannel, dataSegment, out uint bytesWritten);
if (result == Result.NotFound)
{
// no packets
return null;
}
else if (result == Result.Success)
{
//Do something with chat output
Debug.LogFormat("Message received: peerId={0}, socketId={1}, data={2}", peerId, socketId, Encoding.UTF8.GetString(data));
if (!peerId.IsValid())
{
Debug.LogErrorFormat("EOS P2PNAT HandleReceivedMessages: ProductUserId peerId is not valid!");
return null;
}
string message = System.Text.Encoding.UTF8.GetString(data);
// --- Handshake protocol ---
if (message == Request)
{
SendHandshakeAck(peerId);
connectionStates[peerId] = PeerConnectionAppState.FullyConnected;
Debug.Log($"Received handshake request from {peerId}. Sending ack and setting FullyConnected.");
return null;
}
else if (message == Acknowledgement)
{
connectionStates[peerId] = PeerConnectionAppState.FullyConnected;
Debug.Log($"Received handshake ack from {peerId}. Connection is now FullyConnected.");
return null;
}
// --- End handshake ---
if (message.StartsWith("t"))
{
ChatEntry newMessage = new ChatEntry()
{
isOwnEntry = false,
Message = message.Substring(1)
};
if (ChatDataCache.TryGetValue(peerId, out ChatWithFriendData chatData))
{
// Update existing chat
chatData.ChatLines.Enqueue(newMessage);
ChatDataCacheDirty = true;
return peerId;
}
else
{
ChatWithFriendData newChat = new ChatWithFriendData(peerId);
newChat.ChatLines.Enqueue(newMessage);
// New Chat Request
ChatDataCache.Add(peerId, newChat);
return peerId;
}
}
else if (message.StartsWith("m"))
{
message = message.Substring(1);
string[] coords = message.Split(',');
int xPos = Int32.Parse(coords[0]);
int yPos = Int32.Parse(coords[1]);
Debug.Log("EOS P2PNAT HandleReceivedMessages: Mouse position Recieved at " + xPos + ", " + yPos);
ParticleController.SpawnParticles(xPos, yPos);
return peerId;
}
else if (message == Ping)
{
Debug.Log($"EOS P2PNAT HandleReceivedMessages: received ping from {peerId}, ignoring.");
return null;
}
else
{
Debug.LogErrorFormat("EOS P2PNAT HandleReceivedMessages: error while reading data, code: {0}", result);
return null;
}
}
return null;
}
private void SubscribeToConnectionRequest()
{
if (ConnectionNotificationId == 0)
{
SocketId socketId = new SocketId()
{
SocketName = "CHAT"
};
AddNotifyPeerConnectionRequestOptions options = new AddNotifyPeerConnectionRequestOptions()
{
LocalUserId = EOSManager.Instance.GetProductUserId(),
SocketId = socketId
};
ConnectionNotificationId = P2PHandle.AddNotifyPeerConnectionRequest(ref options, null, OnIncomingConnectionRequest);
if (ConnectionNotificationId == 0)
{
Debug.Log("EOS P2PNAT SubscribeToConnectionRequests: could not subscribe, bad notification id returned.");
}
}
}
private void UnsubscribeFromConnectionRequests()
{
if (ConnectionNotificationId != 0)//check to prevent warnings when done unnecessarily during p2p startup
{
P2PHandle.RemoveNotifyPeerConnectionRequest(ConnectionNotificationId);
ConnectionNotificationId = 0;
}
}
private void OnIncomingConnectionRequest(ref OnIncomingConnectionRequestInfo data)
{
//if (data == null)
//{
// Debug.LogError("P2P (OnIncomingConnectionRequest): data is null");
// return;
//}
if (!(bool)data.SocketId?.SocketName.Equals("CHAT"))
{
Debug.LogError("P2p (OnIncomingConnectionRequest): bad socket id");
return;
}
SocketId socketId = new SocketId()
{
SocketName = "CHAT"
};
AcceptConnectionOptions options = new AcceptConnectionOptions()
{
LocalUserId = EOSManager.Instance.GetProductUserId(),
RemoteUserId = data.RemoteUserId,
SocketId = socketId
};
Result result = P2PHandle.AcceptConnection(ref options);
SendHandshakeRequest(data.RemoteUserId);
if (result != Result.Success)
{
Debug.LogErrorFormat("P2p (OnIncomingConnectionRequest): error while accepting connection, code: {0}", result);
}
}
private void SendHandshakeRequest(ProductUserId remoteUserId)
{
SendRaw(remoteUserId, "hreq");
connectionStates[remoteUserId] = PeerConnectionAppState.HandshakePending;
}
private void SendHandshakeAck(ProductUserId remoteUserId)
{
SendRaw(remoteUserId, "hack");
}
private void SendRaw(ProductUserId remoteUserId, string rawMessage)
{
SocketId socketId = new SocketId() { SocketName = "CHAT" };
SendPacketOptions options = new SendPacketOptions()
{
LocalUserId = EOSManager.Instance.GetProductUserId(),
RemoteUserId = remoteUserId,
SocketId = socketId,
AllowDelayedDelivery = true,
Channel = 0,
Reliability = PacketReliability.ReliableOrdered,
Data = new ArraySegment<byte>(Encoding.UTF8.GetBytes(rawMessage))
};
var result = P2PHandle.SendPacket(ref options);
if (result != Result.Success)
{
Debug.LogError($"SendRaw failed: {result}");
}
}
private void OnPeerConnectionEstablished(ref OnPeerConnectionEstablishedInfo info)
{
Debug.Log($"[P2P] Connection established with {LoggingUtils.Redact(info.RemoteUserId)} | type={info.ConnectionType} network={info.NetworkType}");
if (!connectionStates.ContainsKey(info.RemoteUserId))
{
connectionStates[info.RemoteUserId] = PeerConnectionAppState.IceConnected;
SendHandshakeRequest(info.RemoteUserId);
connectionStates[info.RemoteUserId] = PeerConnectionAppState.HandshakePending;
}
}
private void OnPeerConnectionInterrupted(ref OnPeerConnectionInterruptedInfo info)
{
Debug.LogWarning($"[P2P] Connection interrupted with {LoggingUtils.Redact(info.RemoteUserId)} on socket '{info.SocketId?.SocketName}' - EOS will attempt auto-recovery");
}
public void SendTrigger(ProductUserId peerId)
{
if (!peerId.IsValid()) return;
string trigger = "ping";
SendRaw(peerId, trigger);
}
}
}