You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
2.7 KiB
87 lines
2.7 KiB
using System.Collections; |
|
using System.Collections.Generic; |
|
using Unity.Collections; |
|
using Unity.Networking.Transport; |
|
using Unity.Networking.Transport.Utilities; |
|
using UnityEngine; |
|
|
|
namespace GameCore.Network |
|
{ |
|
[CreateAssetMenu(menuName = "GameCore/Network/" + nameof(NetworkDriverAsset), |
|
fileName = nameof(NetworkDriverAsset))] |
|
public class NetworkDriverAsset : ScriptableObject |
|
{ |
|
public uint port = 7777; |
|
|
|
[Header("Simulator Settings")] public bool useSimulator; |
|
public int packetDelayMs = 500; |
|
public int packetJitterMs = 300; |
|
public int packetDropPercentage = 10; |
|
|
|
private NetworkDriver CreateDriver() |
|
{ |
|
var settings = new NetworkSettings(Allocator.Temp); |
|
settings.WithNetworkConfigParameters(disconnectTimeoutMS: 5000); |
|
settings.WithReliableStageParameters(32); |
|
settings.WithSimulatorStageParameters(32, NetworkParameterConstants.MaxConnectAttempts, |
|
packetDelayMs: packetDelayMs, packetJitterMs: packetJitterMs, |
|
packetDropPercentage: packetDropPercentage); |
|
|
|
var driver = NetworkDriver.Create(settings); |
|
|
|
if (useSimulator) |
|
{ |
|
driver.CreatePipeline(typeof(SimulatorPipelineStageInSend)); |
|
driver.CreatePipeline(typeof(ReliableSequencedPipelineStage), typeof(SimulatorPipelineStageInSend)); |
|
} |
|
else |
|
{ |
|
driver.CreatePipeline(typeof(ReliableSequencedPipelineStage)); |
|
} |
|
|
|
return driver; |
|
} |
|
|
|
public NetworkDriver CreateServerDriver(string address) |
|
{ |
|
var driver = CreateDriver(); |
|
var ok = false; |
|
try |
|
{ |
|
if (!NetworkEndPoint.TryParse(address, (ushort)port, out var endpoint)) |
|
{ |
|
return default; |
|
} |
|
|
|
if (driver.Bind(endpoint) != 0) |
|
{ |
|
Debug.Log("Failed to bind to " + endpoint); |
|
return default; |
|
} |
|
|
|
ok = true; |
|
driver.Listen(); |
|
return driver; |
|
} |
|
finally |
|
{ |
|
if (!ok) |
|
driver.Dispose(); |
|
} |
|
} |
|
|
|
public NetworkDriver CreateClientDriver(string address, out NetworkConnection connection) |
|
{ |
|
var driver = CreateDriver(); |
|
if (!NetworkEndPoint.TryParse(address, (ushort)port, out var endpoint)) |
|
{ |
|
connection = default; |
|
driver.Dispose(); |
|
return default; |
|
} |
|
|
|
connection = driver.Connect(endpoint); |
|
return driver; |
|
} |
|
} |
|
} |