Skip to content

Commit 3f5d1f1

Browse files
committed
Add P2P connection state tracking and handshake protocol
1 parent 0c4ad0f commit 3f5d1f1

File tree

2 files changed

+103
-4
lines changed

2 files changed

+103
-4
lines changed

Assets/Scripts/EOSPeer2PeerManager.cs

Lines changed: 100 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,15 @@ public class EOSPeer2PeerManager : IEOSSubManager
8989

9090
public UIPeer2PeerParticleController ParticleController;
9191
public Transform parent;
92+
private enum PeerConnectionAppState
93+
{
94+
NotConnected,
95+
IceConnected,
96+
HandshakePending,
97+
FullyConnected
98+
}
99+
100+
private Dictionary<ProductUserId, PeerConnectionAppState> connectionStates = new();
92101

93102
#if UNITY_EDITOR
94103
void OnPlayModeChanged(UnityEditor.PlayModeStateChange modeChange)
@@ -126,7 +135,19 @@ public bool GetChatDataCache(out Dictionary<ProductUserId, ChatWithFriendData> C
126135
ChatDataCache = this.ChatDataCache;
127136
return ChatDataCacheDirty;
128137
}
138+
public void Initialize()
139+
{
140+
SubscribeToConnectionRequest();
141+
142+
var options = new AddNotifyPeerConnectionEstablishedOptions
143+
{
144+
LocalUserId = EOSManager.Instance.GetProductUserId()
145+
};
146+
147+
P2PHandle.AddNotifyPeerConnectionEstablished(ref options, null, OnPeerConnectionEstablished);
129148

149+
Debug.Log("EOSPeer2PeerManager initialized: connection listeners registered.");
150+
}
130151
private void RefreshNATType()
131152
{
132153
var options = new QueryNATTypeOptions();
@@ -188,6 +209,12 @@ public void SendMessage(ProductUserId friendId, messageData message)
188209
Debug.LogError("EOS P2PNAT SendMessage: bad input data: account id is wrong.");
189210
return;
190211
}
212+
if (!connectionStates.TryGetValue(friendId, out var state) || state != PeerConnectionAppState.FullyConnected)
213+
{
214+
Debug.LogWarning($"SendMessage: Cannot send to {friendId}, not fully connected (State={state}).");
215+
return;
216+
}
217+
191218
if (message.type == messageType.textMessage)
192219
{
193220
if (string.IsNullOrEmpty(message.textData))
@@ -283,6 +310,8 @@ public void SendMessage(ProductUserId friendId, messageData message)
283310

284311
public ProductUserId HandleReceivedMessages()
285312
{
313+
314+
286315
if (P2PHandle == null)
287316
{
288317
return null;
@@ -330,6 +359,21 @@ public ProductUserId HandleReceivedMessages()
330359
}
331360

332361
string message = System.Text.Encoding.UTF8.GetString(data);
362+
// --- Handshake protocol ---
363+
if (message == "hreq")
364+
{
365+
SendHandshakeAck(peerId);
366+
connectionStates[peerId] = PeerConnectionAppState.FullyConnected;
367+
Debug.Log($"Received handshake request from {peerId}. Sending ack and setting FullyConnected.");
368+
return null;
369+
}
370+
else if (message == "hack")
371+
{
372+
connectionStates[peerId] = PeerConnectionAppState.FullyConnected;
373+
Debug.Log($"Received handshake ack from {peerId}. Connection is now FullyConnected.");
374+
return null;
375+
}
376+
// --- End handshake ---
333377

334378
if (message.StartsWith("t"))
335379
{
@@ -371,9 +415,11 @@ public ProductUserId HandleReceivedMessages()
371415

372416
return peerId;
373417
}
374-
375-
376-
418+
else if (message == "ping")
419+
{
420+
Debug.Log($"EOS P2PNAT HandleReceivedMessages: received ping from {peerId}, ignoring.");
421+
return null;
422+
}
377423
else
378424
{
379425
Debug.LogErrorFormat("EOS P2PNAT HandleReceivedMessages: error while reading data, code: {0}", result);
@@ -442,11 +488,61 @@ private void OnIncomingConnectionRequest(ref OnIncomingConnectionRequestInfo dat
442488
};
443489

444490
Result result = P2PHandle.AcceptConnection(ref options);
445-
491+
SendHandshakeRequest(data.RemoteUserId);
446492
if (result != Result.Success)
447493
{
448494
Debug.LogErrorFormat("P2p (OnIncomingConnectionRequest): error while accepting connection, code: {0}", result);
449495
}
450496
}
497+
private void SendHandshakeRequest(ProductUserId remoteUserId)
498+
{
499+
SendRaw(remoteUserId, "hreq");
500+
connectionStates[remoteUserId] = PeerConnectionAppState.HandshakePending;
501+
}
502+
503+
private void SendHandshakeAck(ProductUserId remoteUserId)
504+
{
505+
SendRaw(remoteUserId, "hack");
506+
}
507+
508+
private void SendRaw(ProductUserId remoteUserId, string rawMessage)
509+
{
510+
SocketId socketId = new SocketId() { SocketName = "CHAT" };
511+
512+
SendPacketOptions options = new SendPacketOptions()
513+
{
514+
LocalUserId = EOSManager.Instance.GetProductUserId(),
515+
RemoteUserId = remoteUserId,
516+
SocketId = socketId,
517+
AllowDelayedDelivery = true,
518+
Channel = 0,
519+
Reliability = PacketReliability.ReliableOrdered,
520+
Data = new ArraySegment<byte>(Encoding.UTF8.GetBytes(rawMessage))
521+
};
522+
523+
var result = P2PHandle.SendPacket(ref options);
524+
if (result != Result.Success)
525+
{
526+
Debug.LogError($"SendRaw failed: {result}");
527+
}
528+
}
529+
private void OnPeerConnectionEstablished(ref OnPeerConnectionEstablishedInfo info)
530+
{
531+
Debug.Log($"[P2P] Connection established with {info.RemoteUserId}");
532+
533+
if (!connectionStates.ContainsKey(info.RemoteUserId))
534+
{
535+
connectionStates[info.RemoteUserId] = PeerConnectionAppState.IceConnected;
536+
SendHandshakeRequest(info.RemoteUserId);
537+
connectionStates[info.RemoteUserId] = PeerConnectionAppState.HandshakePending;
538+
}
539+
}
540+
public void SendTrigger(ProductUserId peerId)
541+
{
542+
if (!peerId.IsValid()) return;
543+
string trigger = "ping";
544+
SendRaw(peerId, trigger);
545+
}
451546
}
547+
452548
}

Assets/Scripts/StandardSamples/UI/Peer2Peer/UIPeer2PeerMenu.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,8 @@ public void ChatButtonOnClick(EpicAccountId userId)
169169
CurrentChatUserText.text = currentChatDisplayName;
170170

171171
ChatWindow.SetActive(true);
172+
Peer2PeerManager.Initialize();
173+
Peer2PeerManager.SendTrigger(currentChatProductUserId);
172174
}
173175
else
174176
{
@@ -206,6 +208,7 @@ public void IncomingChat(ProductUserId productUserId)
206208
CurrentChatUserText.text = currentChatDisplayName;
207209

208210
ChatWindow.SetActive(true);
211+
Peer2PeerManager.SendTrigger(productUserId);
209212
}
210213
else
211214
{

0 commit comments

Comments
 (0)