Skip to content

Commit 3865de1

Browse files
authored
refactor!: delete SocketTask and make StartServer/Client calls non-async (#1239)
1 parent 027f807 commit 3865de1

File tree

12 files changed

+109
-424
lines changed

12 files changed

+109
-424
lines changed

com.unity.netcode.adapter.utp/Runtime/UnityTransport.cs

Lines changed: 71 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using System;
2-
using System.Collections;
32
using System.Collections.Generic;
43
using UnityEngine;
54
using NetcodeNetworkEvent = Unity.Netcode.NetworkEvent;
@@ -57,6 +56,7 @@ private enum State
5756
private NetworkDriver m_Driver;
5857
private List<INetworkParameter> m_NetworkParameters;
5958
private byte[] m_MessageBuffer;
59+
private NetworkConnection m_ServerConnection;
6060
private ulong m_ServerClientId;
6161

6262
private NetworkPipeline m_UnreliableSequencedPipeline;
@@ -153,7 +153,7 @@ private NetworkPipeline SelectSendPipeline(NetworkDelivery delivery, int size)
153153
}
154154
}
155155

156-
private IEnumerator ClientBindAndConnect(SocketTask task)
156+
private bool ClientBindAndConnect()
157157
{
158158
var serverEndpoint = default(NetworkEndPoint);
159159

@@ -164,9 +164,7 @@ private IEnumerator ClientBindAndConnect(SocketTask task)
164164
if (m_RelayServerData.Equals(default(RelayServerData)))
165165
{
166166
Debug.LogError("You must call SetRelayServerData() at least once before calling StartRelayServer.");
167-
task.IsDone = true;
168-
task.Success = false;
169-
yield break;
167+
return false;
170168
}
171169

172170
m_NetworkParameters.Add(new RelayNetworkParameter { ServerData = m_RelayServerData });
@@ -178,66 +176,39 @@ private IEnumerator ClientBindAndConnect(SocketTask task)
178176

179177
InitDriver();
180178

181-
if (m_Driver.Bind(NetworkEndPoint.AnyIpv4) != 0)
179+
int result = m_Driver.Bind(NetworkEndPoint.AnyIpv4);
180+
if (result != 0)
182181
{
183182
Debug.LogError("Client failed to bind");
183+
return false;
184184
}
185-
else
186-
{
187-
while (!m_Driver.Bound)
188-
{
189-
yield return null;
190-
}
191-
192-
var serverConnection = m_Driver.Connect(serverEndpoint);
193-
m_ServerClientId = ParseClientId(serverConnection);
194185

195-
while (m_Driver.GetConnectionState(serverConnection) == NetworkConnection.State.Connecting)
196-
{
197-
yield return null;
198-
}
199-
200-
if (m_Driver.GetConnectionState(serverConnection) == NetworkConnection.State.Connected)
201-
{
202-
task.Success = true;
203-
m_State = State.Connected;
204-
}
205-
else
206-
{
207-
Debug.LogError("Client failed to connect to server");
208-
}
209-
}
186+
m_ServerConnection = m_Driver.Connect(serverEndpoint);
187+
m_ServerClientId = ParseClientId(m_ServerConnection);
210188

211-
task.IsDone = true;
189+
return true;
212190
}
213191

214-
private IEnumerator ServerBindAndListen(SocketTask task, NetworkEndPoint endPoint)
192+
private bool ServerBindAndListen(NetworkEndPoint endPoint)
215193
{
216194
InitDriver();
217195

218-
if (m_Driver.Bind(endPoint) != 0)
196+
int result = m_Driver.Bind(endPoint);
197+
if (result != 0)
219198
{
220199
Debug.LogError("Server failed to bind");
200+
return false;
221201
}
222-
else
223-
{
224-
while (!m_Driver.Bound)
225-
{
226-
yield return null;
227-
}
228202

229-
if (m_Driver.Listen() == 0)
230-
{
231-
task.Success = true;
232-
m_State = State.Listening;
233-
}
234-
else
235-
{
236-
Debug.LogError("Server failed to listen");
237-
}
203+
result = m_Driver.Listen();
204+
if (result != 0)
205+
{
206+
Debug.LogError("Server failed to listen");
207+
return false;
238208
}
239209

240-
task.IsDone = true;
210+
m_State = State.Listening;
211+
return true;
241212
}
242213

243214
private static RelayAllocationId ConvertFromAllocationIdBytes(byte[] allocationIdBytes)
@@ -306,22 +277,19 @@ public void SetConnectionData(string ipv4Address, ushort port)
306277
m_ServerPort = port;
307278
}
308279

309-
private IEnumerator StartRelayServer(SocketTask task)
280+
private bool StartRelayServer()
310281
{
311282
//This comparison is currently slow since RelayServerData does not implement a custom comparison operator that doesn't use
312283
//reflection, but this does not live in the context of a performance-critical loop, it runs once at initial connection time.
313284
if (m_RelayServerData.Equals(default(RelayServerData)))
314285
{
315286
Debug.LogError("You must call SetRelayServerData() at least once before calling StartRelayServer.");
316-
task.IsDone = true;
317-
task.Success = false;
318-
yield break;
287+
return false;
319288
}
320289
else
321290
{
322291
m_NetworkParameters.Add(new RelayNetworkParameter { ServerData = m_RelayServerData });
323-
324-
yield return ServerBindAndListen(task, NetworkEndPoint.AnyIpv4);
292+
return ServerBindAndListen(NetworkEndPoint.AnyIpv4);
325293
}
326294
}
327295

@@ -336,7 +304,7 @@ private bool AcceptConnection()
336304

337305
InvokeOnTransportEvent(NetcodeNetworkEvent.Connect,
338306
ParseClientId(connection),
339-
default(ArraySegment<byte>),
307+
default,
340308
Time.realtimeSinceStartup);
341309

342310
return true;
@@ -350,37 +318,53 @@ private bool ProcessEvent()
350318
switch (eventType)
351319
{
352320
case TransportNetworkEvent.Type.Connect:
353-
InvokeOnTransportEvent(NetcodeNetworkEvent.Connect,
354-
ParseClientId(networkConnection),
355-
default(ArraySegment<byte>),
356-
Time.realtimeSinceStartup);
357-
return true;
321+
{
322+
InvokeOnTransportEvent(NetcodeNetworkEvent.Connect,
323+
ParseClientId(networkConnection),
324+
default(ArraySegment<byte>),
325+
Time.realtimeSinceStartup);
358326

327+
m_State = State.Connected;
328+
return true;
329+
}
359330
case TransportNetworkEvent.Type.Disconnect:
360-
InvokeOnTransportEvent(NetcodeNetworkEvent.Disconnect,
361-
ParseClientId(networkConnection),
362-
default(ArraySegment<byte>),
363-
Time.realtimeSinceStartup);
364-
return true;
331+
{
332+
InvokeOnTransportEvent(NetcodeNetworkEvent.Disconnect,
333+
ParseClientId(networkConnection),
334+
default(ArraySegment<byte>),
335+
Time.realtimeSinceStartup);
365336

337+
if (m_ServerConnection.IsCreated)
338+
{
339+
m_ServerConnection = default;
340+
if (m_Driver.GetConnectionState(m_ServerConnection) == NetworkConnection.State.Connecting)
341+
{
342+
Debug.LogError("Client failed to connect to server");
343+
}
344+
}
345+
346+
m_State = State.Disconnected;
347+
return true;
348+
}
366349
case TransportNetworkEvent.Type.Data:
367-
var isBatched = reader.ReadByte();
368-
if (isBatched == 1)
369350
{
370-
while (reader.GetBytesRead() < reader.Length)
351+
var isBatched = reader.ReadByte();
352+
if (isBatched == 1)
353+
{
354+
while (reader.GetBytesRead() < reader.Length)
355+
{
356+
var payloadSize = reader.ReadInt();
357+
ReadData(payloadSize, ref reader, ref networkConnection);
358+
}
359+
}
360+
else // If is not batched, then read the entire buffer at once
371361
{
372362
var payloadSize = reader.ReadInt();
373363
ReadData(payloadSize, ref reader, ref networkConnection);
374364
}
375-
}
376-
else // If is not batched, then read the entire buffer at once
377-
{
378-
var payloadSize = reader.ReadInt();
379365

380-
ReadData(payloadSize, ref reader, ref networkConnection);
366+
return true;
381367
}
382-
383-
return true;
384368
}
385369

386370
return false;
@@ -428,7 +412,6 @@ private void Update()
428412
;
429413
}
430414
}
431-
432415
}
433416

434417
private void OnDestroy()
@@ -593,11 +576,9 @@ private unsafe void SendBatchedMessage(ulong clientId, ref NativeArray<byte> dat
593576
Debug.LogError($"Error sending the message {result}");
594577
}
595578

596-
private unsafe void SendMessageInstantly(ulong clientId, ArraySegment<byte> data,
597-
NetworkPipeline pipeline)
579+
private unsafe void SendMessageInstantly(ulong clientId, ArraySegment<byte> data, NetworkPipeline pipeline)
598580
{
599-
var payloadSize =
600-
data.Count + 1 + 4; // 1 byte to indicate if the message is batched and 4 for the payload size
581+
var payloadSize = data.Count + 1 + 4; // 1 byte to indicate if the message is batched and 4 for the payload size
601582
var result = m_Driver.BeginSend(pipeline, ParseClientId(clientId), out var writer, payloadSize);
602583
if (result == 0)
603584
{
@@ -656,37 +637,32 @@ private void SendBatchedMessageAndClearQueue(SendTarget sendTarget, SendQueue se
656637
sendQueue.Clear();
657638
}
658639

659-
public override SocketTasks StartClient()
640+
public override bool StartClient()
660641
{
661642
if (m_Driver.IsCreated)
662643
{
663-
return SocketTask.Fault.AsTasks();
644+
return false;
664645
}
665646

666-
var task = SocketTask.Working;
667-
StartCoroutine(ClientBindAndConnect(task));
668-
return task.AsTasks();
647+
return ClientBindAndConnect();
669648
}
670649

671-
public override SocketTasks StartServer()
650+
public override bool StartServer()
672651
{
673652
if (m_Driver.IsCreated)
674653
{
675-
return SocketTask.Fault.AsTasks();
654+
return false;
676655
}
677656

678-
var task = SocketTask.Working;
679657
switch (m_ProtocolType)
680658
{
681659
case ProtocolType.UnityTransport:
682-
StartCoroutine(ServerBindAndListen(task, NetworkEndPoint.Parse(m_ServerAddress, m_ServerPort)));
683-
break;
660+
return ServerBindAndListen(NetworkEndPoint.Parse(m_ServerAddress, m_ServerPort));
684661
case ProtocolType.RelayUnityTransport:
685-
StartCoroutine(StartRelayServer(task));
686-
break;
662+
return StartRelayServer();
663+
default:
664+
return false;
687665
}
688-
689-
return task.AsTasks();
690666
}
691667

692668
public override void Shutdown()

com.unity.netcode.adapter.utp/Tests/Editor/UnityTransportTests.cs

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@ public void BasicInitServer()
1212
UnityTransport transport = new GameObject().AddComponent<UnityTransport>();
1313
transport.Initialize();
1414

15-
var tasks = transport.StartServer();
16-
Assert.False(tasks.IsDone && !tasks.Success);
15+
Assert.True(transport.StartServer());
1716

1817
transport.Shutdown();
1918
}
@@ -25,8 +24,7 @@ public void BasicInitClient()
2524
UnityTransport transport = new GameObject().AddComponent<UnityTransport>();
2625
transport.Initialize();
2726

28-
var tasks = transport.StartClient();
29-
Assert.False(tasks.IsDone && !tasks.Success);
27+
Assert.True(transport.StartClient());
3028

3129
transport.Shutdown();
3230
}
@@ -39,8 +37,7 @@ public void NoRestartServer()
3937
transport.Initialize();
4038

4139
transport.StartServer();
42-
var tasks = transport.StartServer();
43-
Assert.True(tasks.IsDone && !tasks.AnySuccess);
40+
Assert.False(transport.StartServer());
4441

4542
transport.Shutdown();
4643
}
@@ -53,8 +50,7 @@ public void NoRestartClient()
5350
transport.Initialize();
5451

5552
transport.StartClient();
56-
var tasks = transport.StartClient();
57-
Assert.True(tasks.IsDone && !tasks.AnySuccess);
53+
Assert.False(transport.StartClient());
5854

5955
transport.Shutdown();
6056
}
@@ -64,15 +60,13 @@ public void NoRestartClient()
6460
public void NotBothServerAndClient()
6561
{
6662
UnityTransport transport;
67-
SocketTasks tasks;
6863

6964
// Start server then client.
7065
transport = new GameObject().AddComponent<UnityTransport>();
7166
transport.Initialize();
7267

7368
transport.StartServer();
74-
tasks = transport.StartClient();
75-
Assert.True(tasks.IsDone && !tasks.AnySuccess);
69+
Assert.False(transport.StartClient());
7670

7771
transport.Shutdown();
7872

@@ -81,12 +75,9 @@ public void NotBothServerAndClient()
8175
transport.Initialize();
8276

8377
transport.StartClient();
84-
tasks = transport.StartServer();
85-
Assert.True(tasks.IsDone && !tasks.AnySuccess);
78+
Assert.False(transport.StartServer());
8679

8780
transport.Shutdown();
8881
}
8982
}
9083
}
91-
92-

com.unity.netcode.adapter.utp/Tests/Runtime/ConnectionTests.cs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,6 @@ public IEnumerator ConnectMultipleClients()
9292
[UnityTest]
9393
public IEnumerator ServerDisconnectSingleClient()
9494
{
95-
9695
InitializeTransport(out m_Server, out m_ServerEvents);
9796
InitializeTransport(out m_Clients[0], out m_ClientsEvents[0]);
9897

@@ -152,7 +151,6 @@ public IEnumerator ServerDisconnectMultipleClients()
152151
[UnityTest]
153152
public IEnumerator ClientDisconnectSingleClient()
154153
{
155-
156154
InitializeTransport(out m_Server, out m_ServerEvents);
157155
InitializeTransport(out m_Clients[0], out m_ClientsEvents[0]);
158156

@@ -164,8 +162,6 @@ public IEnumerator ClientDisconnectSingleClient()
164162
m_Clients[0].DisconnectLocalClient();
165163

166164
yield return WaitForNetworkEvent(NetworkEvent.Disconnect, m_ServerEvents);
167-
168-
yield return null;
169165
}
170166

171167
// Check client disconnection with multiple clients.

0 commit comments

Comments
 (0)