diff --git a/FizzyFacepunch/BidirectionalDictionary.cs b/FizzyFacepunch/BidirectionalDictionary.cs index 8f6dc277..62410a47 100644 --- a/FizzyFacepunch/BidirectionalDictionary.cs +++ b/FizzyFacepunch/BidirectionalDictionary.cs @@ -3,79 +3,79 @@ using System.Collections.Generic; namespace Mirror.FizzySteam { - public class BidirectionalDictionary : IEnumerable - { - private Dictionary t1ToT2Dict = new Dictionary(); - private Dictionary t2ToT1Dict = new Dictionary(); + public class BidirectionalDictionary : IEnumerable + { + private readonly Dictionary t1ToT2Dict = new Dictionary(); + private readonly Dictionary t2ToT1Dict = new Dictionary(); - public IEnumerable FirstTypes => t1ToT2Dict.Keys; - public IEnumerable SecondTypes => t2ToT1Dict.Keys; + public IEnumerable FirstTypes => t1ToT2Dict.Keys; + public IEnumerable SecondTypes => t2ToT1Dict.Keys; - public IEnumerator GetEnumerator() => t1ToT2Dict.GetEnumerator(); + public IEnumerator GetEnumerator() => t1ToT2Dict.GetEnumerator(); - public int Count => t1ToT2Dict.Count; + public int Count => t1ToT2Dict.Count; - public void Add(T1 key, T2 value) - { - t1ToT2Dict[key] = value; - t2ToT1Dict[value] = key; - } + public void Add(T1 key, T2 value) + { + t1ToT2Dict[key] = value; + t2ToT1Dict[value] = key; + } - public void Add(T2 key, T1 value) - { - t2ToT1Dict[key] = value; - t1ToT2Dict[value] = key; - } + public void Add(T2 key, T1 value) + { + t2ToT1Dict[key] = value; + t1ToT2Dict[value] = key; + } - public T2 Get(T1 key) => t1ToT2Dict[key]; + public T2 Get(T1 key) => t1ToT2Dict[key]; - public T1 Get(T2 key) => t2ToT1Dict[key]; + public T1 Get(T2 key) => t2ToT1Dict[key]; - public bool TryGetValue(T1 key, out T2 value) => t1ToT2Dict.TryGetValue(key, out value); + public bool TryGetValue(T1 key, out T2 value) => t1ToT2Dict.TryGetValue(key, out value); - public bool TryGetValue(T2 key, out T1 value) => t2ToT1Dict.TryGetValue(key, out value); + public bool TryGetValue(T2 key, out T1 value) => t2ToT1Dict.TryGetValue(key, out value); - public bool Contains(T1 key) => t1ToT2Dict.ContainsKey(key); + public bool Contains(T1 key) => t1ToT2Dict.ContainsKey(key); - public bool Contains(T2 key) => t2ToT1Dict.ContainsKey(key); + public bool Contains(T2 key) => t2ToT1Dict.ContainsKey(key); - public void Remove(T1 key) - { - if (Contains(key)) - { - T2 val = t1ToT2Dict[key]; - t1ToT2Dict.Remove(key); - t2ToT1Dict.Remove(val); - } - } - public void Remove(T2 key) - { - if (Contains(key)) - { - T1 val = t2ToT1Dict[key]; - t1ToT2Dict.Remove(val); - t2ToT1Dict.Remove(key); - } - } + public void Remove(T1 key) + { + if (Contains(key)) + { + var val = t1ToT2Dict[key]; + t1ToT2Dict.Remove(key); + t2ToT1Dict.Remove(val); + } + } + public void Remove(T2 key) + { + if (Contains(key)) + { + var val = t2ToT1Dict[key]; + t1ToT2Dict.Remove(val); + t2ToT1Dict.Remove(key); + } + } - public T1 this[T2 key] - { - get => t2ToT1Dict[key]; - set - { - t2ToT1Dict[key] = value; - t1ToT2Dict[value] = key; - } - } + public T1 this[T2 key] + { + get => t2ToT1Dict[key]; + set + { + t2ToT1Dict[key] = value; + t1ToT2Dict[value] = key; + } + } - public T2 this[T1 key] - { - get => t1ToT2Dict[key]; - set - { - t1ToT2Dict[key] = value; - t2ToT1Dict[value] = key; - } - } - } + public T2 this[T1 key] + { + get => t1ToT2Dict[key]; + set + { + t1ToT2Dict[key] = value; + t2ToT1Dict[value] = key; + } + } + } } \ No newline at end of file diff --git a/FizzyFacepunch/FizzyConnectionManager.cs b/FizzyFacepunch/FizzyConnectionManager.cs index b31ed637..8998542b 100644 --- a/FizzyFacepunch/FizzyConnectionManager.cs +++ b/FizzyFacepunch/FizzyConnectionManager.cs @@ -3,10 +3,7 @@ using System; public class FizzyConnectionManager : ConnectionManager { - public Action ForwardMessage; + public Action ForwardMessage; - public override void OnMessage(IntPtr data, int size, long messageNum, long recvTime, int channel) - { - ForwardMessage(data, size); - } + public override void OnMessage(IntPtr data, int size, long messageNum, long recvTime, int channel) => ForwardMessage(data, size); } \ No newline at end of file diff --git a/FizzyFacepunch/FizzyFacepunch.cs b/FizzyFacepunch/FizzyFacepunch.cs index 6575c605..26eb8113 100644 --- a/FizzyFacepunch/FizzyFacepunch.cs +++ b/FizzyFacepunch/FizzyFacepunch.cs @@ -1,303 +1,301 @@ using Steamworks; using System; -using System.Collections.Generic; using System.IO; using UnityEngine; namespace Mirror.FizzySteam { - [HelpURL("https://github.com/Chykary/FizzyFacepunch")] - public class FizzyFacepunch : Transport - { - private const string STEAM_SCHEME = "steam"; + [HelpURL("https://github.com/Chykary/FizzyFacepunch")] + public class FizzyFacepunch : Transport + { + private const string STEAM_SCHEME = "steam"; - private static IClient client; - private static IServer server; + private static IClient client; + private static IServer server; - [SerializeField] - public P2PSend[] Channels = new P2PSend[2] { P2PSend.Reliable, P2PSend.UnreliableNoDelay }; + [SerializeField] + public P2PSend[] Channels = new P2PSend[2] { P2PSend.Reliable, P2PSend.UnreliableNoDelay }; - [Tooltip("Timeout for connecting in seconds.")] - public int Timeout = 25; - [Tooltip("The Steam ID for your application.")] - public string SteamAppID = "480"; - [Tooltip("Allow or disallow P2P connections to fall back to being relayed through the Steam servers if a direct connection or NAT-traversal cannot be established.")] - public bool AllowSteamRelay = true; + [Tooltip("Timeout for connecting in seconds.")] + public int Timeout = 25; + [Tooltip("The Steam ID for your application.")] + public string SteamAppID = "480"; + [Tooltip("Allow or disallow P2P connections to fall back to being relayed through the Steam servers if a direct connection or NAT-traversal cannot be established.")] + public bool AllowSteamRelay = true; - [Tooltip("Use SteamSockets instead of the (deprecated) SteamNetworking. This will always use Relay.")] - public bool UseNextGenSteamNetworking = true; + [Tooltip("Use SteamSockets instead of the (deprecated) SteamNetworking. This will always use Relay.")] + public bool UseNextGenSteamNetworking = true; - [Tooltip("Check this if you want the transport to initialise Facepunch.")] - public bool InitFacepunch = true; + [Tooltip("Check this if you want the transport to initialise Facepunch.")] + public bool InitFacepunch = true; - [Header("Info")] - [Tooltip("This will display your Steam User ID when you start or connect to a server.")] - public ulong SteamUserID; + [Header("Info")] + [Tooltip("This will display your Steam User ID when you start or connect to a server.")] + public ulong SteamUserID; - public Action SetTransportError; + public Action SetTransportError; - private void Awake() - { - const string fileName = "steam_appid.txt"; - if (File.Exists(fileName)) - { - string content = File.ReadAllText(fileName); - if (content != SteamAppID) - { - File.WriteAllText(fileName, SteamAppID.ToString()); - Debug.Log($"Updating {fileName}. Previous: {content}, new SteamAppID {SteamAppID}"); - } - } - else - { - File.WriteAllText(fileName, SteamAppID.ToString()); - Debug.Log($"New {fileName} written with SteamAppID {SteamAppID}"); - } + private void Awake() + { + const string fileName = "steam_appid.txt"; + if (File.Exists(fileName)) + { + var content = File.ReadAllText(fileName); + if (content != SteamAppID) + { + File.WriteAllText(fileName, SteamAppID.ToString()); + Debug.Log($"Updating {fileName}. Previous: {content}, new SteamAppID {SteamAppID}"); + } + } + else + { + File.WriteAllText(fileName, SteamAppID.ToString()); + Debug.Log($"New {fileName} written with SteamAppID {SteamAppID}"); + } - Debug.Assert(Channels != null && Channels.Length > 0, "No channel configured for FizzySteamworks."); + Debug.Assert(Channels != null && Channels.Length > 0, "No channel configured for FizzySteamworks."); - if (InitFacepunch) - { - SteamClient.Init(uint.Parse(SteamAppID), true); - } + if (InitFacepunch) + { + SteamClient.Init(uint.Parse(SteamAppID), true); + } - Invoke(nameof(FetchSteamID), 1f); - } + Invoke(nameof(FetchSteamID), 1f); + } public override void ClientEarlyUpdate() - { - if (enabled && client != null && !client.Error) - { - client?.ReceiveData(); - } - } + { + if (enabled && client != null && !client.Error) + { + client?.ReceiveData(); + } + } - public override void ServerEarlyUpdate() - { - if (enabled) - { - server?.ReceiveData(); - } - } + public override void ServerEarlyUpdate() + { + if (enabled) + { + server?.ReceiveData(); + } + } - public override void ClientLateUpdate() - { - if (enabled && client != null && !client.Error) - { - client?.FlushData(); - } - } + public override void ClientLateUpdate() + { + if (enabled && client != null && !client.Error) + { + client?.FlushData(); + } + } - public override void ServerLateUpdate() - { - if (enabled) - { - server?.FlushData(); - } - } + public override void ServerLateUpdate() + { + if (enabled) + { + server?.FlushData(); + } + } - public override bool ClientConnected() => ClientActive() && client.Connected; - public override void ClientConnect(string address) - { - if (!SteamClient.IsValid) - { - Debug.LogError("SteamWorks not initialized. Client could not be started."); - OnClientDisconnected.Invoke(); - return; - } + public override bool ClientConnected() => ClientActive() && client.Connected; + public override void ClientConnect(string address) + { + if (!SteamClient.IsValid) + { + Debug.LogError("SteamWorks not initialized. Client could not be started."); + OnClientDisconnected.Invoke(); + return; + } - FetchSteamID(); + FetchSteamID(); - if (ServerActive()) - { - Debug.LogError("Transport already running as server!"); - return; - } + if (ServerActive()) + { + Debug.LogError("Transport already running as server!"); + return; + } - if (!ClientActive() || client.Error) - { - if (UseNextGenSteamNetworking) - { - Debug.Log($"Starting client [SteamSockets], target address {address}."); - client = NextClient.CreateClient(this, address); - } - else - { - Debug.Log($"Starting client [DEPRECATED SteamNetworking], target address {address}. Relay enabled: {AllowSteamRelay}"); - SteamNetworking.AllowP2PPacketRelay(AllowSteamRelay); - client = LegacyClient.CreateClient(this, address); - } - } - else - { - Debug.LogError("Client already running!"); - } - } + if (!ClientActive() || client.Error) + { + if (UseNextGenSteamNetworking) + { + Debug.Log($"Starting client [SteamSockets], target address {address}."); + client = NextClient.CreateClient(this, address); + } + else + { + Debug.Log($"Starting client [DEPRECATED SteamNetworking], target address {address}. Relay enabled: {AllowSteamRelay}"); + SteamNetworking.AllowP2PPacketRelay(AllowSteamRelay); + client = LegacyClient.CreateClient(this, address); + } + } + else + { + Debug.LogError("Client already running!"); + } + } - public override void ClientConnect(Uri uri) - { - if (uri.Scheme != STEAM_SCHEME) - throw new ArgumentException($"Invalid url {uri}, use {STEAM_SCHEME}://SteamID instead", nameof(uri)); + public override void ClientConnect(Uri uri) + { + if (uri.Scheme != STEAM_SCHEME) + { + throw new ArgumentException($"Invalid url {uri}, use {STEAM_SCHEME}://SteamID instead", nameof(uri)); + } - ClientConnect(uri.Host); - } + ClientConnect(uri.Host); + } - public override void ClientSend(ArraySegment segment, int channelId) - { - byte[] data = new byte[segment.Count]; - Array.Copy(segment.Array, segment.Offset, data, 0, segment.Count); - client.Send(data, channelId); - } + public override void ClientSend(ArraySegment segment, int channelId) + { + var data = new byte[segment.Count]; + Array.Copy(segment.Array, segment.Offset, data, 0, segment.Count); + client.Send(data, channelId); + } - public override void ClientDisconnect() - { - if (ClientActive()) - { - Shutdown(); - } - } - public bool ClientActive() => client != null; + public override void ClientDisconnect() + { + if (ClientActive()) + { + Shutdown(); + } + } + public bool ClientActive() => client != null; - public override bool ServerActive() => server != null; - public override void ServerStart() - { - if (!SteamClient.IsValid) - { - Debug.LogError("SteamWorks not initialized. Server could not be started."); - return; - } + public override bool ServerActive() => server != null; + public override void ServerStart() + { + if (!SteamClient.IsValid) + { + Debug.LogError("SteamWorks not initialized. Server could not be started."); + return; + } - FetchSteamID(); + FetchSteamID(); - if (ClientActive()) - { - Debug.LogError("Transport already running as client!"); - return; - } + if (ClientActive()) + { + Debug.LogError("Transport already running as client!"); + return; + } - if (!ServerActive()) - { - if (UseNextGenSteamNetworking) - { - Debug.Log($"Starting server [SteamSockets]."); - server = NextServer.CreateServer(this, NetworkManager.singleton.maxConnections); - } - else - { - Debug.Log($"Starting server [DEPRECATED SteamNetworking]. Relay enabled: {AllowSteamRelay}"); - SteamNetworking.AllowP2PPacketRelay(AllowSteamRelay); - server = LegacyServer.CreateServer(this, NetworkManager.singleton.maxConnections); - } - } - else - { - Debug.LogError("Server already started!"); - } - } + if (!ServerActive()) + { + if (UseNextGenSteamNetworking) + { + Debug.Log($"Starting server [SteamSockets]."); + server = NextServer.CreateServer(this, NetworkManager.singleton.maxConnections); + } + else + { + Debug.Log($"Starting server [DEPRECATED SteamNetworking]. Relay enabled: {AllowSteamRelay}"); + SteamNetworking.AllowP2PPacketRelay(AllowSteamRelay); + server = LegacyServer.CreateServer(this, NetworkManager.singleton.maxConnections); + } + } + else + { + Debug.LogError("Server already started!"); + } + } - public override Uri ServerUri() - { - var steamBuilder = new UriBuilder - { - Scheme = STEAM_SCHEME, - Host = SteamClient.SteamId.Value.ToString() - }; + public override Uri ServerUri() + { + var steamBuilder = new UriBuilder + { + Scheme = STEAM_SCHEME, + Host = SteamClient.SteamId.Value.ToString() + }; - return steamBuilder.Uri; - } + return steamBuilder.Uri; + } - public override void ServerSend(int connectionId, ArraySegment segment, int channelId) - { - if (ServerActive()) - { - byte[] data = new byte[segment.Count]; - Array.Copy(segment.Array, segment.Offset, data, 0, segment.Count); - server.Send(connectionId, data, channelId); - } - } - public override void ServerDisconnect(int connectionId) - { - if (ServerActive()) - { - server.Disconnect(connectionId); - } - } - public override string ServerGetClientAddress(int connectionId) => ServerActive() ? server.ServerGetClientAddress(connectionId) : string.Empty; - public override void ServerStop() - { - if (ServerActive()) - { - Shutdown(); - } - } + public override void ServerSend(int connectionId, ArraySegment segment, int channelId) + { + if (ServerActive()) + { + var data = new byte[segment.Count]; + Array.Copy(segment.Array, segment.Offset, data, 0, segment.Count); + server.Send(connectionId, data, channelId); + } + } + public override void ServerDisconnect(int connectionId) + { + if (ServerActive()) + { + server.Disconnect(connectionId); + } + } + public override string ServerGetClientAddress(int connectionId) => ServerActive() ? server.ServerGetClientAddress(connectionId) : string.Empty; + public override void ServerStop() + { + if (ServerActive()) + { + Shutdown(); + } + } - public override void Shutdown() - { - if (server != null) - { - server.Shutdown(); - server = null; - Debug.Log("Transport shut down - was server."); - } + public override void Shutdown() + { + if (server != null) + { + server.Shutdown(); + server = null; + Debug.Log("Transport shut down - was server."); + } - if (client != null) - { - client.Disconnect(); - client = null; - Debug.Log("Transport shut down - was client."); - } - } + if (client != null) + { + client.Disconnect(); + client = null; + Debug.Log("Transport shut down - was client."); + } + } - public override int GetMaxPacketSize(int channelId) - { - if (channelId >= Channels.Length) - { - Debug.LogError("Channel Id exceeded configured channels! Please configure more channels."); - return 1200; - } + public override int GetMaxPacketSize(int channelId) + { + if (channelId >= Channels.Length) + { + Debug.LogError("Channel Id exceeded configured channels! Please configure more channels."); + return 1200; + } - switch (Channels[channelId]) - { - case P2PSend.Unreliable: - case P2PSend.UnreliableNoDelay: - return 1200; - case P2PSend.Reliable: - case P2PSend.ReliableWithBuffering: - return 1048576; - default: - throw new NotSupportedException(); - } - } + switch (Channels[channelId]) + { + case P2PSend.Unreliable: + case P2PSend.UnreliableNoDelay: + return 1200; + case P2PSend.Reliable: + case P2PSend.ReliableWithBuffering: + return 1048576; + default: + throw new NotSupportedException(); + } + } - public override bool Available() - { - try - { - return SteamClient.IsValid; - } - catch - { - return false; - } - } + public override bool Available() + { + try + { + return SteamClient.IsValid; + } + catch + { + return false; + } + } - private void FetchSteamID() - { - if (SteamClient.IsValid) - { - if (UseNextGenSteamNetworking) - { - SteamNetworkingUtils.InitRelayNetworkAccess(); - } + private void FetchSteamID() + { + if (SteamClient.IsValid) + { + if (UseNextGenSteamNetworking) + { + SteamNetworkingUtils.InitRelayNetworkAccess(); + } - SteamUserID = SteamClient.SteamId; - } - } + SteamUserID = SteamClient.SteamId; + } + } - private void OnDestroy() - { - Shutdown(); - } - } + private void OnDestroy() => Shutdown(); + } } \ No newline at end of file diff --git a/FizzyFacepunch/FizzySocketManager.cs b/FizzyFacepunch/FizzySocketManager.cs index 510632ce..7c0d8fec 100644 --- a/FizzyFacepunch/FizzySocketManager.cs +++ b/FizzyFacepunch/FizzySocketManager.cs @@ -4,10 +4,7 @@ using System; public class FizzySocketManager : SocketManager { - public Action ForwardMessage; + public Action ForwardMessage; - public override void OnMessage(Connection connection, NetIdentity identity, IntPtr data, int size, long messageNum, long recvTime, int channel) - { - ForwardMessage(connection, data, size); - } + public override void OnMessage(Connection connection, NetIdentity identity, IntPtr data, int size, long messageNum, long recvTime, int channel) => ForwardMessage(connection, data, size); } \ No newline at end of file diff --git a/FizzyFacepunch/IClient.cs b/FizzyFacepunch/IClient.cs index d14c4507..f30c351c 100644 --- a/FizzyFacepunch/IClient.cs +++ b/FizzyFacepunch/IClient.cs @@ -1,12 +1,12 @@ namespace Mirror.FizzySteam { - public interface IClient - { - bool Connected { get; } - bool Error { get; } - void ReceiveData(); - void Disconnect(); - void FlushData(); - void Send(byte[] data, int channelId); - } + public interface IClient + { + bool Connected { get; } + bool Error { get; } + void ReceiveData(); + void Disconnect(); + void FlushData(); + void Send(byte[] data, int channelId); + } } \ No newline at end of file diff --git a/FizzyFacepunch/IServer.cs b/FizzyFacepunch/IServer.cs index 63ac08ed..a5b220bc 100644 --- a/FizzyFacepunch/IServer.cs +++ b/FizzyFacepunch/IServer.cs @@ -1,12 +1,12 @@ namespace Mirror.FizzySteam { - public interface IServer - { - void ReceiveData(); - void Send(int connectionId, byte[] data, int channelId); - void Disconnect(int connectionId); - void FlushData(); - string ServerGetClientAddress(int connectionId); - void Shutdown(); - } + public interface IServer + { + void ReceiveData(); + void Send(int connectionId, byte[] data, int channelId); + void Disconnect(int connectionId); + void FlushData(); + string ServerGetClientAddress(int connectionId); + void Shutdown(); + } } \ No newline at end of file diff --git a/FizzyFacepunch/LegacyClient.cs b/FizzyFacepunch/LegacyClient.cs index da87c9a4..83c9ded9 100644 --- a/FizzyFacepunch/LegacyClient.cs +++ b/FizzyFacepunch/LegacyClient.cs @@ -6,159 +6,156 @@ using UnityEngine; namespace Mirror.FizzySteam { - public class LegacyClient : LegacyCommon, IClient - { - public bool Error { get; private set; } - public bool Connected { get; private set; } + public class LegacyClient : LegacyCommon, IClient + { + public bool Error { get; private set; } + public bool Connected { get; private set; } - private event Action OnReceivedData; - private event Action OnConnected; - private event Action OnDisconnected; + private event Action OnReceivedData; + private event Action OnConnected; + private event Action OnDisconnected; - private TimeSpan ConnectionTimeout; + private TimeSpan ConnectionTimeout; - private SteamId hostSteamID = 0; - private TaskCompletionSource connectedComplete; - private CancellationTokenSource cancelToken; + private SteamId hostSteamID = 0; + private TaskCompletionSource connectedComplete; + private CancellationTokenSource cancelToken; - private LegacyClient(FizzyFacepunch transport) : base(transport) - { - ConnectionTimeout = TimeSpan.FromSeconds(Math.Max(1, transport.Timeout)); - } + private LegacyClient(FizzyFacepunch transport) : base(transport) => ConnectionTimeout = TimeSpan.FromSeconds(Math.Max(1, transport.Timeout)); - public static LegacyClient CreateClient(FizzyFacepunch transport, string host) - { - LegacyClient c = new LegacyClient(transport); + public static LegacyClient CreateClient(FizzyFacepunch transport, string host) + { + var c = new LegacyClient(transport); - c.OnConnected += () => transport.OnClientConnected.Invoke(); - c.OnDisconnected += () => transport.OnClientDisconnected.Invoke(); - c.OnReceivedData += (data, channel) => transport.OnClientDataReceived.Invoke(new ArraySegment(data), channel); + c.OnConnected += () => transport.OnClientConnected.Invoke(); + c.OnDisconnected += () => transport.OnClientDisconnected.Invoke(); + c.OnReceivedData += (data, channel) => transport.OnClientDataReceived.Invoke(new ArraySegment(data), channel); - if (SteamClient.IsValid) - { - c.Connect(host); - } - else - { - Debug.LogError("SteamWorks not initialized."); - c.OnConnectionFailed(new SteamId()); - } + if (SteamClient.IsValid) + { + c.Connect(host); + } + else + { + Debug.LogError("SteamWorks not initialized."); + c.OnConnectionFailed(new SteamId()); + } - return c; - } + return c; + } - private async void Connect(string host) - { - cancelToken = new CancellationTokenSource(); - try - { - hostSteamID = ulong.Parse(host); - connectedComplete = new TaskCompletionSource(); + private async void Connect(string host) + { + cancelToken = new CancellationTokenSource(); + try + { + hostSteamID = ulong.Parse(host); + connectedComplete = new TaskCompletionSource(); - OnConnected += SetConnectedComplete; - SendInternal(hostSteamID, InternalMessages.CONNECT); - Task connectedCompleteTask = connectedComplete.Task; - Task timeOutTask = Task.Delay(ConnectionTimeout, cancelToken.Token); + OnConnected += SetConnectedComplete; + SendInternal(hostSteamID, InternalMessages.CONNECT); + Task connectedCompleteTask = connectedComplete.Task; + var timeOutTask = Task.Delay(ConnectionTimeout, cancelToken.Token); - if (await Task.WhenAny(connectedCompleteTask, timeOutTask) != connectedCompleteTask) - { - if (cancelToken.IsCancellationRequested) - { - Debug.LogError($"The connection attempt was cancelled."); - } - else if (timeOutTask.IsCompleted) - { - Debug.LogError($"Connection to {host} timed out."); - } - OnConnected -= SetConnectedComplete; - Debug.LogError("Connection timed out."); - OnConnectionFailed(hostSteamID); - } + if (await Task.WhenAny(connectedCompleteTask, timeOutTask) != connectedCompleteTask) + { + if (cancelToken.IsCancellationRequested) + { + Debug.LogError($"The connection attempt was cancelled."); + } + else if (timeOutTask.IsCompleted) + { + Debug.LogError($"Connection to {host} timed out."); + } + OnConnected -= SetConnectedComplete; + Debug.LogError("Connection timed out."); + OnConnectionFailed(hostSteamID); + } - OnConnected -= SetConnectedComplete; - } - catch (FormatException) - { - Debug.LogError($"Connection string was not in the right format. Did you enter a SteamId?"); - Error = true; - } - catch (Exception ex) - { - Debug.LogError(ex.Message); - Error = true; - } - finally - { - if (Error) - { - OnConnectionFailed(new SteamId()); - } - } - } + OnConnected -= SetConnectedComplete; + } + catch (FormatException) + { + Debug.LogError($"Connection string was not in the right format. Did you enter a SteamId?"); + Error = true; + } + catch (Exception ex) + { + Debug.LogError(ex.Message); + Error = true; + } + finally + { + if (Error) + { + OnConnectionFailed(new SteamId()); + } + } + } - public void Disconnect() - { - Debug.LogError("Sending Disconnect message"); - SendInternal(hostSteamID, InternalMessages.DISCONNECT); - Dispose(); - cancelToken?.Cancel(); + public void Disconnect() + { + Debug.LogError("Sending Disconnect message"); + SendInternal(hostSteamID, InternalMessages.DISCONNECT); + Dispose(); + cancelToken?.Cancel(); - WaitForClose(hostSteamID); - } + WaitForClose(hostSteamID); + } - private void SetConnectedComplete() => connectedComplete.SetResult(connectedComplete.Task); + private void SetConnectedComplete() => connectedComplete.SetResult(connectedComplete.Task); - protected override void OnReceiveData(byte[] data, SteamId clientSteamID, int channel) - { - if (clientSteamID != hostSteamID) - { - Debug.LogError("Received a message from an unknown"); - return; - } + protected override void OnReceiveData(byte[] data, SteamId clientSteamID, int channel) + { + if (clientSteamID != hostSteamID) + { + Debug.LogError("Received a message from an unknown"); + return; + } - OnReceivedData.Invoke(data, channel); - } + OnReceivedData.Invoke(data, channel); + } - protected override void OnNewConnection(SteamId id) - { - if (hostSteamID == id) - { - SteamNetworking.AcceptP2PSessionWithUser(id); - } - else - { - Debug.LogError("P2P Acceptance Request from unknown host ID."); - } - } + protected override void OnNewConnection(SteamId id) + { + if (hostSteamID == id) + { + SteamNetworking.AcceptP2PSessionWithUser(id); + } + else + { + Debug.LogError("P2P Acceptance Request from unknown host ID."); + } + } - protected override void OnReceiveInternalData(InternalMessages type, SteamId clientSteamID) - { - switch (type) - { - case InternalMessages.ACCEPT_CONNECT: - if (!Connected) - { - Connected = true; - Debug.LogError("Connection established."); - OnConnected.Invoke(); - } - break; - case InternalMessages.DISCONNECT: - if (Connected) - { - Connected = false; - Debug.LogError("Disconnected."); - OnDisconnected.Invoke(); - } - break; - default: - Debug.LogError("Received unknown message type"); - break; - } - } + protected override void OnReceiveInternalData(InternalMessages type, SteamId clientSteamID) + { + switch (type) + { + case InternalMessages.ACCEPT_CONNECT: + if (!Connected) + { + Connected = true; + Debug.LogError("Connection established."); + OnConnected.Invoke(); + } + break; + case InternalMessages.DISCONNECT: + if (Connected) + { + Connected = false; + Debug.LogError("Disconnected."); + OnDisconnected.Invoke(); + } + break; + default: + Debug.LogError("Received unknown message type"); + break; + } + } - public void Send(byte[] data, int channelId) => Send(hostSteamID, data, channelId); - protected override void OnConnectionFailed(SteamId remoteId) => OnDisconnected.Invoke(); - public void FlushData() { } - } + public void Send(byte[] data, int channelId) => Send(hostSteamID, data, channelId); + protected override void OnConnectionFailed(SteamId remoteId) => OnDisconnected.Invoke(); + public void FlushData() { } + } } \ No newline at end of file diff --git a/FizzyFacepunch/LegacyCommon.cs b/FizzyFacepunch/LegacyCommon.cs index 674697f4..4d6cf3a4 100644 --- a/FizzyFacepunch/LegacyCommon.cs +++ b/FizzyFacepunch/LegacyCommon.cs @@ -5,121 +5,121 @@ using UnityEngine; namespace Mirror.FizzySteam { - public abstract class LegacyCommon - { - private P2PSend[] channels; - private int internal_ch => channels.Length; + public abstract class LegacyCommon + { + private readonly P2PSend[] channels; + private int internal_ch => channels.Length; - protected enum InternalMessages : byte - { - CONNECT, - ACCEPT_CONNECT, - DISCONNECT - } + protected enum InternalMessages : byte + { + CONNECT, + ACCEPT_CONNECT, + DISCONNECT + } - protected readonly FizzyFacepunch transport; + protected readonly FizzyFacepunch transport; - protected LegacyCommon(FizzyFacepunch transport) - { - channels = transport.Channels; + protected LegacyCommon(FizzyFacepunch transport) + { + channels = transport.Channels; - SteamNetworking.OnP2PSessionRequest += OnNewConnection; - SteamNetworking.OnP2PConnectionFailed += OnConnectFail; + SteamNetworking.OnP2PSessionRequest += OnNewConnection; + SteamNetworking.OnP2PConnectionFailed += OnConnectFail; - this.transport = transport; - } + this.transport = transport; + } - protected void WaitForClose(SteamId cSteamID) => transport.StartCoroutine(DelayedClose(cSteamID)); - private IEnumerator DelayedClose(SteamId cSteamID) - { - yield return null; - CloseP2PSessionWithUser(cSteamID); - } + protected void WaitForClose(SteamId cSteamID) => transport.StartCoroutine(DelayedClose(cSteamID)); + private IEnumerator DelayedClose(SteamId cSteamID) + { + yield return null; + CloseP2PSessionWithUser(cSteamID); + } - protected void Dispose() - { - SteamNetworking.OnP2PSessionRequest -= OnNewConnection; - SteamNetworking.OnP2PConnectionFailed -= OnConnectFail; - } + protected void Dispose() + { + SteamNetworking.OnP2PSessionRequest -= OnNewConnection; + SteamNetworking.OnP2PConnectionFailed -= OnConnectFail; + } - protected abstract void OnNewConnection(SteamId steamID); + protected abstract void OnNewConnection(SteamId steamID); - private void OnConnectFail(SteamId id, P2PSessionError err) - { - OnConnectionFailed(id); - CloseP2PSessionWithUser(id); + private void OnConnectFail(SteamId id, P2PSessionError err) + { + OnConnectionFailed(id); + CloseP2PSessionWithUser(id); - switch (err) - { - case P2PSessionError.NotRunningApp: - throw new Exception("Connection failed: The target user is not running the same game."); - case P2PSessionError.NoRightsToApp: - throw new Exception("Connection failed: The local user doesn't own the app that is running."); - case P2PSessionError.DestinationNotLoggedIn: - throw new Exception("Connection failed: Target user isn't connected to Steam."); - case P2PSessionError.Timeout: - throw new Exception("Connection failed: The connection timed out because the target user didn't respond."); - default: - throw new Exception("Connection failed: Unknown error."); - } - } + switch (err) + { + case P2PSessionError.NotRunningApp: + throw new Exception("Connection failed: The target user is not running the same game."); + case P2PSessionError.NoRightsToApp: + throw new Exception("Connection failed: The local user doesn't own the app that is running."); + case P2PSessionError.DestinationNotLoggedIn: + throw new Exception("Connection failed: Target user isn't connected to Steam."); + case P2PSessionError.Timeout: + throw new Exception("Connection failed: The connection timed out because the target user didn't respond."); + default: + throw new Exception("Connection failed: Unknown error."); + } + } - protected bool SendInternal(SteamId target, InternalMessages type) => SteamNetworking.SendP2PPacket(target, new byte[] { (byte)type }, 1, internal_ch); - protected void Send(SteamId host, byte[] msgBuffer, int channel) => SteamNetworking.SendP2PPacket(host, msgBuffer, msgBuffer.Length, channel, channels[Mathf.Min(channel, channels.Length - 1)]); - private bool Receive(out SteamId clientSteamID, out byte[] receiveBuffer, int channel) - { - if (SteamNetworking.IsP2PPacketAvailable(channel)) - { - var data = SteamNetworking.ReadP2PPacket(channel); + protected bool SendInternal(SteamId target, InternalMessages type) => SteamNetworking.SendP2PPacket(target, new byte[] { (byte)type }, 1, internal_ch); + protected void Send(SteamId host, byte[] msgBuffer, int channel) => SteamNetworking.SendP2PPacket(host, msgBuffer, msgBuffer.Length, channel, channels[Mathf.Min(channel, channels.Length - 1)]); + private bool Receive(out SteamId clientSteamID, out byte[] receiveBuffer, int channel) + { + if (SteamNetworking.IsP2PPacketAvailable(channel)) + { + var data = SteamNetworking.ReadP2PPacket(channel); - if (data != null) - { - receiveBuffer = data.Value.Data; - clientSteamID = data.Value.SteamId; - return true; - } - } + if (data != null) + { + receiveBuffer = data.Value.Data; + clientSteamID = data.Value.SteamId; + return true; + } + } - receiveBuffer = null; - clientSteamID = 0; - return false; - } + receiveBuffer = null; + clientSteamID = 0; + return false; + } - protected void CloseP2PSessionWithUser(SteamId clientSteamID) => SteamNetworking.CloseP2PSessionWithUser(clientSteamID); + protected void CloseP2PSessionWithUser(SteamId clientSteamID) => SteamNetworking.CloseP2PSessionWithUser(clientSteamID); - public void ReceiveData() - { - try - { - while (transport.enabled && Receive(out SteamId clientSteamID, out byte[] internalMessage, internal_ch)) - { - if (internalMessage.Length == 1) - { - OnReceiveInternalData((InternalMessages)internalMessage[0], clientSteamID); - return; - } - else - { - Debug.LogError("Incorrect package length on internal channel."); - } - } + public void ReceiveData() + { + try + { + while (transport.enabled && Receive(out var clientSteamID, out var internalMessage, internal_ch)) + { + if (internalMessage.Length == 1) + { + OnReceiveInternalData((InternalMessages)internalMessage[0], clientSteamID); + return; + } + else + { + Debug.LogError("Incorrect package length on internal channel."); + } + } - for (int chNum = 0; chNum < channels.Length; chNum++) - { - while (transport.enabled && Receive(out SteamId clientSteamID, out byte[] receiveBuffer, chNum)) - { - OnReceiveData(receiveBuffer, clientSteamID, chNum); - } - } - } - catch (Exception e) - { - Debug.LogException(e); - } - } + for (var chNum = 0; chNum < channels.Length; chNum++) + { + while (transport.enabled && Receive(out var clientSteamID, out var receiveBuffer, chNum)) + { + OnReceiveData(receiveBuffer, clientSteamID, chNum); + } + } + } + catch (Exception e) + { + Debug.LogException(e); + } + } - protected abstract void OnReceiveInternalData(InternalMessages type, SteamId clientSteamID); - protected abstract void OnReceiveData(byte[] data, SteamId clientSteamID, int channel); - protected abstract void OnConnectionFailed(SteamId remoteId); - } + protected abstract void OnReceiveInternalData(InternalMessages type, SteamId clientSteamID); + protected abstract void OnReceiveData(byte[] data, SteamId clientSteamID, int channel); + protected abstract void OnConnectionFailed(SteamId remoteId); + } } \ No newline at end of file diff --git a/FizzyFacepunch/LegacyServer.cs b/FizzyFacepunch/LegacyServer.cs index f6a7fff3..7a5b5240 100644 --- a/FizzyFacepunch/LegacyServer.cs +++ b/FizzyFacepunch/LegacyServer.cs @@ -5,160 +5,160 @@ using UnityEngine; namespace Mirror.FizzySteam { - public class LegacyServer : LegacyCommon, IServer - { - private event Action OnConnected; - private event Action OnReceivedData; - private event Action OnDisconnected; - private event Action OnReceivedError; + public class LegacyServer : LegacyCommon, IServer + { + private event Action OnConnected; + private event Action OnReceivedData; + private event Action OnDisconnected; + private event Action OnReceivedError; - private BidirectionalDictionary steamToMirrorIds; - private int maxConnections; - private int nextConnectionID; + private readonly BidirectionalDictionary steamToMirrorIds; + private readonly int maxConnections; + private int nextConnectionID; - public static LegacyServer CreateServer(FizzyFacepunch transport, int maxConnections) - { - LegacyServer s = new LegacyServer(transport, maxConnections); + public static LegacyServer CreateServer(FizzyFacepunch transport, int maxConnections) + { + var s = new LegacyServer(transport, maxConnections); - s.OnConnected += (id) => transport.OnServerConnected.Invoke(id); - s.OnDisconnected += (id) => transport.OnServerDisconnected.Invoke(id); - s.OnReceivedData += (id, data, channel) => transport.OnServerDataReceived.Invoke(id, new ArraySegment(data), channel); - s.OnReceivedError += (id, exception) => transport.OnServerError.Invoke(id, exception); + s.OnConnected += (id) => transport.OnServerConnected.Invoke(id); + s.OnDisconnected += (id) => transport.OnServerDisconnected.Invoke(id); + s.OnReceivedData += (id, data, channel) => transport.OnServerDataReceived.Invoke(id, new ArraySegment(data), channel); + s.OnReceivedError += (id, exception) => transport.OnServerError.Invoke(id, exception); - SteamNetworking.OnP2PSessionRequest = (steamid) => - { - Debug.LogError($"Incoming request from SteamId {steamid}."); - SteamNetworking.AcceptP2PSessionWithUser(steamid); - }; + SteamNetworking.OnP2PSessionRequest = (steamid) => + { + Debug.LogError($"Incoming request from SteamId {steamid}."); + SteamNetworking.AcceptP2PSessionWithUser(steamid); + }; - if (!SteamClient.IsValid) - { - Debug.LogError("SteamWorks not initialized."); - } + if (!SteamClient.IsValid) + { + Debug.LogError("SteamWorks not initialized."); + } - return s; - } + return s; + } - private LegacyServer(FizzyFacepunch transport, int maxConnections) : base(transport) - { - this.maxConnections = maxConnections; - steamToMirrorIds = new BidirectionalDictionary(); - nextConnectionID = 1; - } + private LegacyServer(FizzyFacepunch transport, int maxConnections) : base(transport) + { + this.maxConnections = maxConnections; + steamToMirrorIds = new BidirectionalDictionary(); + nextConnectionID = 1; + } - protected override void OnNewConnection(SteamId id) => SteamNetworking.AcceptP2PSessionWithUser(id); + protected override void OnNewConnection(SteamId id) => SteamNetworking.AcceptP2PSessionWithUser(id); - protected override void OnReceiveInternalData(InternalMessages type, SteamId clientSteamID) - { - switch (type) - { - case InternalMessages.CONNECT: - if (steamToMirrorIds.Count >= maxConnections) - { - SendInternal(clientSteamID, InternalMessages.DISCONNECT); - return; - } + protected override void OnReceiveInternalData(InternalMessages type, SteamId clientSteamID) + { + switch (type) + { + case InternalMessages.CONNECT: + if (steamToMirrorIds.Count >= maxConnections) + { + SendInternal(clientSteamID, InternalMessages.DISCONNECT); + return; + } - SendInternal(clientSteamID, InternalMessages.ACCEPT_CONNECT); + SendInternal(clientSteamID, InternalMessages.ACCEPT_CONNECT); - int connectionId = nextConnectionID++; - steamToMirrorIds.Add(clientSteamID, connectionId); - OnConnected.Invoke(connectionId); - Debug.LogError($"Client with SteamID {clientSteamID} connected. Assigning connection id {connectionId}"); - break; - case InternalMessages.DISCONNECT: - if (steamToMirrorIds.TryGetValue(clientSteamID, out int connId)) - { - OnDisconnected.Invoke(connId); - CloseP2PSessionWithUser(clientSteamID); - steamToMirrorIds.Remove(clientSteamID); - Debug.LogError($"Client with SteamID {clientSteamID} disconnected."); - } - else - { - OnReceivedError.Invoke(-1, new Exception("ERROR Unknown SteamID while receiving disconnect message.")); - } + var connectionId = nextConnectionID++; + steamToMirrorIds.Add(clientSteamID, connectionId); + OnConnected.Invoke(connectionId); + Debug.LogError($"Client with SteamID {clientSteamID} connected. Assigning connection id {connectionId}"); + break; + case InternalMessages.DISCONNECT: + if (steamToMirrorIds.TryGetValue(clientSteamID, out var connId)) + { + OnDisconnected.Invoke(connId); + CloseP2PSessionWithUser(clientSteamID); + steamToMirrorIds.Remove(clientSteamID); + Debug.LogError($"Client with SteamID {clientSteamID} disconnected."); + } + else + { + OnReceivedError.Invoke(-1, new Exception("ERROR Unknown SteamID while receiving disconnect message.")); + } - break; - default: - Debug.LogError("Received unknown message type"); - break; - } - } + break; + default: + Debug.LogError("Received unknown message type"); + break; + } + } - protected override void OnReceiveData(byte[] data, SteamId clientSteamID, int channel) - { - if (steamToMirrorIds.TryGetValue(clientSteamID, out int connectionId)) - { - OnReceivedData.Invoke(connectionId, data, channel); - } - else - { - CloseP2PSessionWithUser(clientSteamID); - Debug.LogError("Data received from steam client thats not known " + clientSteamID); - OnReceivedError.Invoke(-1, new Exception("ERROR Unknown SteamID")); - } - } + protected override void OnReceiveData(byte[] data, SteamId clientSteamID, int channel) + { + if (steamToMirrorIds.TryGetValue(clientSteamID, out var connectionId)) + { + OnReceivedData.Invoke(connectionId, data, channel); + } + else + { + CloseP2PSessionWithUser(clientSteamID); + Debug.LogError("Data received from steam client thats not known " + clientSteamID); + OnReceivedError.Invoke(-1, new Exception("ERROR Unknown SteamID")); + } + } - public void Disconnect(int connectionId) - { - if (steamToMirrorIds.TryGetValue(connectionId, out SteamId steamID)) - { - SendInternal(steamID, InternalMessages.DISCONNECT); - steamToMirrorIds.Remove(connectionId); - } - else - { - Debug.LogWarning("Trying to disconnect unknown connection id: " + connectionId); - } - } + public void Disconnect(int connectionId) + { + if (steamToMirrorIds.TryGetValue(connectionId, out var steamID)) + { + SendInternal(steamID, InternalMessages.DISCONNECT); + steamToMirrorIds.Remove(connectionId); + } + else + { + Debug.LogWarning("Trying to disconnect unknown connection id: " + connectionId); + } + } - public void Shutdown() - { - foreach (KeyValuePair client in steamToMirrorIds) - { - Disconnect(client.Value); - WaitForClose(client.Key); - } + public void Shutdown() + { + foreach (KeyValuePair client in steamToMirrorIds) + { + Disconnect(client.Value); + WaitForClose(client.Key); + } - SteamNetworking.OnP2PSessionRequest = null; - Dispose(); - } + SteamNetworking.OnP2PSessionRequest = null; + Dispose(); + } - public void Send(int connectionId, byte[] data, int channelId) - { - if (steamToMirrorIds.TryGetValue(connectionId, out SteamId steamId)) - { - Send(steamId, data, channelId); - } - else - { - Debug.LogError("Trying to send on unknown connection: " + connectionId); - OnReceivedError.Invoke(connectionId, new Exception("ERROR Unknown Connection")); - } - } + public void Send(int connectionId, byte[] data, int channelId) + { + if (steamToMirrorIds.TryGetValue(connectionId, out var steamId)) + { + Send(steamId, data, channelId); + } + else + { + Debug.LogError("Trying to send on unknown connection: " + connectionId); + OnReceivedError.Invoke(connectionId, new Exception("ERROR Unknown Connection")); + } + } - public string ServerGetClientAddress(int connectionId) - { - if (steamToMirrorIds.TryGetValue(connectionId, out SteamId steamId)) - { - return steamId.ToString(); - } - else - { - Debug.LogError("Trying to get info on unknown connection: " + connectionId); - OnReceivedError.Invoke(connectionId, new Exception("ERROR Unknown Connection")); - return string.Empty; - } - } + public string ServerGetClientAddress(int connectionId) + { + if (steamToMirrorIds.TryGetValue(connectionId, out var steamId)) + { + return steamId.ToString(); + } + else + { + Debug.LogError("Trying to get info on unknown connection: " + connectionId); + OnReceivedError.Invoke(connectionId, new Exception("ERROR Unknown Connection")); + return string.Empty; + } + } - protected override void OnConnectionFailed(SteamId remoteId) - { - int connectionId = steamToMirrorIds.TryGetValue(remoteId, out int connId) ? connId : nextConnectionID++; - OnDisconnected.Invoke(connectionId); - } + protected override void OnConnectionFailed(SteamId remoteId) + { + var connectionId = steamToMirrorIds.TryGetValue(remoteId, out var connId) ? connId : nextConnectionID++; + OnDisconnected.Invoke(connectionId); + } - public void FlushData() { } - } + public void FlushData() { } + } } \ No newline at end of file diff --git a/FizzyFacepunch/NextClient.cs b/FizzyFacepunch/NextClient.cs index 72a15eed..c9c46b4e 100644 --- a/FizzyFacepunch/NextClient.cs +++ b/FizzyFacepunch/NextClient.cs @@ -8,192 +8,186 @@ using UnityEngine; namespace Mirror.FizzySteam { - public class NextClient : NextCommon, IClient - { - public bool Connected { get; private set; } - public bool Error { get; private set; } + public class NextClient : NextCommon, IClient + { + public bool Connected { get; private set; } + public bool Error { get; private set; } - private TimeSpan ConnectionTimeout; + private TimeSpan ConnectionTimeout; - private event Action OnReceivedData; - private event Action OnConnected; - private event Action OnDisconnected; - private Action SetTransportError; + private event Action OnReceivedData; + private event Action OnConnected; + private event Action OnDisconnected; + private Action SetTransportError; - private CancellationTokenSource cancelToken; - private TaskCompletionSource connectedComplete; - private SteamId hostSteamID = 0; - private FizzyConnectionManager HostConnectionManager; - private Connection HostConnection => HostConnectionManager.Connection; - private List BufferedData; + private CancellationTokenSource cancelToken; + private TaskCompletionSource connectedComplete; + private SteamId hostSteamID = 0; + private FizzyConnectionManager HostConnectionManager; + private Connection HostConnection => HostConnectionManager.Connection; + private readonly List BufferedData; - private NextClient(FizzyFacepunch transport) - { - ConnectionTimeout = TimeSpan.FromSeconds(Math.Max(1, transport.Timeout)); - BufferedData = new List(); - } + private NextClient(FizzyFacepunch transport) + { + ConnectionTimeout = TimeSpan.FromSeconds(Math.Max(1, transport.Timeout)); + BufferedData = new List(); + } - public static NextClient CreateClient(FizzyFacepunch transport, string host) - { - NextClient c = new NextClient(transport); + public static NextClient CreateClient(FizzyFacepunch transport, string host) + { + var c = new NextClient(transport); - c.OnConnected += () => transport.OnClientConnected.Invoke(); - c.OnDisconnected += () => transport.OnClientDisconnected.Invoke(); - c.OnReceivedData += (data, ch) => transport.OnClientDataReceived.Invoke(new ArraySegment(data), ch); - c.SetTransportError = transport.SetTransportError; + c.OnConnected += () => transport.OnClientConnected.Invoke(); + c.OnDisconnected += () => transport.OnClientDisconnected.Invoke(); + c.OnReceivedData += (data, ch) => transport.OnClientDataReceived.Invoke(new ArraySegment(data), ch); + c.SetTransportError = transport.SetTransportError; - if (SteamClient.IsValid) - { - c.Connect(host); - } - else - { - c.SetTransportError("SteamWorks not initialized"); - Debug.LogError("SteamWorks not initialized"); - c.OnConnectionFailed(); - } + if (SteamClient.IsValid) + { + c.Connect(host); + } + else + { + c.SetTransportError("SteamWorks not initialized"); + Debug.LogError("SteamWorks not initialized"); + c.OnConnectionFailed(); + } - return c; - } + return c; + } - private async void Connect(string host) - { - cancelToken = new CancellationTokenSource(); - SteamNetworkingSockets.OnConnectionStatusChanged += OnConnectionStatusChanged; + private async void Connect(string host) + { + cancelToken = new CancellationTokenSource(); + SteamNetworkingSockets.OnConnectionStatusChanged += OnConnectionStatusChanged; - try - { - hostSteamID = UInt64.Parse(host); - connectedComplete = new TaskCompletionSource(); - OnConnected += SetConnectedComplete; - HostConnectionManager = SteamNetworkingSockets.ConnectRelay(hostSteamID); - HostConnectionManager.ForwardMessage = OnMessageReceived; - Task connectedCompleteTask = connectedComplete.Task; - Task timeOutTask = Task.Delay(ConnectionTimeout, cancelToken.Token); + try + { + hostSteamID = ulong.Parse(host); + connectedComplete = new TaskCompletionSource(); + OnConnected += SetConnectedComplete; + HostConnectionManager = SteamNetworkingSockets.ConnectRelay(hostSteamID); + HostConnectionManager.ForwardMessage = OnMessageReceived; + Task connectedCompleteTask = connectedComplete.Task; + var timeOutTask = Task.Delay(ConnectionTimeout, cancelToken.Token); - if (await Task.WhenAny(connectedCompleteTask, timeOutTask) != connectedCompleteTask) - { - if (cancelToken.IsCancellationRequested) - { - SetTransportError("The connection attempt was cancelled."); - Debug.LogError($"The connection attempt was cancelled."); - } - else if (timeOutTask.IsCompleted) - { - SetTransportError($"Connection to {host} timed out."); - Debug.LogError($"Connection to {host} timed out."); - } + if (await Task.WhenAny(connectedCompleteTask, timeOutTask) != connectedCompleteTask) + { + if (cancelToken.IsCancellationRequested) + { + SetTransportError("The connection attempt was cancelled."); + Debug.LogError($"The connection attempt was cancelled."); + } + else if (timeOutTask.IsCompleted) + { + SetTransportError($"Connection to {host} timed out."); + Debug.LogError($"Connection to {host} timed out."); + } - OnConnected -= SetConnectedComplete; - OnConnectionFailed(); - } + OnConnected -= SetConnectedComplete; + OnConnectionFailed(); + } - OnConnected -= SetConnectedComplete; - } - catch (FormatException) - { - SetTransportError("Connection string was not in the right format. Did you enter a SteamId?"); - Debug.LogError($"Connection string was not in the right format. Did you enter a SteamId?"); - Error = true; - OnConnectionFailed(); - } - catch (Exception ex) - { - SetTransportError(ex.Message); - Debug.LogError(ex.Message); - Error = true; - OnConnectionFailed(); - } - finally - { - if (Error) - { - Debug.LogError("Connection failed."); - OnConnectionFailed(); - } - } - } + OnConnected -= SetConnectedComplete; + } + catch (FormatException) + { + SetTransportError("Connection string was not in the right format. Did you enter a SteamId?"); + Debug.LogError($"Connection string was not in the right format. Did you enter a SteamId?"); + Error = true; + OnConnectionFailed(); + } + catch (Exception ex) + { + SetTransportError(ex.Message); + Debug.LogError(ex.Message); + Error = true; + OnConnectionFailed(); + } + finally + { + if (Error) + { + Debug.LogError("Connection failed."); + OnConnectionFailed(); + } + } + } - private void OnMessageReceived(IntPtr dataPtr, int size) - { - (byte[] data, int ch) = ProcessMessage(dataPtr, size); - if (Connected) - { - OnReceivedData(data, ch); - } - else - { - BufferedData.Add(() => OnReceivedData(data, ch)); - } - } + private void OnMessageReceived(IntPtr dataPtr, int size) + { + (var data, var ch) = ProcessMessage(dataPtr, size); + if (Connected) + { + OnReceivedData(data, ch); + } + else + { + BufferedData.Add(() => OnReceivedData(data, ch)); + } + } - private void OnConnectionStatusChanged(Connection conn, ConnectionInfo info) - { - ulong clientSteamID = info.Identity.SteamId; - if (info.State == ConnectionState.Connected) - { - Connected = true; - OnConnected.Invoke(); - Debug.LogError("Connection established."); + private void OnConnectionStatusChanged(Connection conn, ConnectionInfo info) + { + ulong clientSteamID = info.Identity.SteamId; + if (info.State == ConnectionState.Connected) + { + Connected = true; + OnConnected.Invoke(); + Debug.LogError("Connection established."); - if (BufferedData.Count > 0) - { - Debug.LogError($"{BufferedData.Count} received before connection was established. Processing now."); - { - foreach (Action a in BufferedData) - { - a(); - } - } - } - } - else if (info.State == ConnectionState.ClosedByPeer) - { - SetTransportError("connection closed by peer"); - Connected = false; - OnDisconnected.Invoke(); - Debug.LogError("Disconnected."); - conn.Close(false, 0, "Disconnected"); - } - else - { - Debug.LogError($"Connection state changed: {info.State.ToString()}"); - } - } + if (BufferedData.Count > 0) + { + Debug.LogError($"{BufferedData.Count} received before connection was established. Processing now."); + { + foreach (var a in BufferedData) + { + a(); + } + } + } + } + else if (info.State == ConnectionState.ClosedByPeer) + { + SetTransportError("connection closed by peer"); + Connected = false; + OnDisconnected.Invoke(); + Debug.LogError("Disconnected."); + conn.Close(false, 0, "Disconnected"); + } + else + { + Debug.LogError($"Connection state changed: {info.State.ToString()}"); + } + } - public void Disconnect() - { - cancelToken?.Cancel(); - SteamNetworkingSockets.OnConnectionStatusChanged -= OnConnectionStatusChanged; + public void Disconnect() + { + cancelToken?.Cancel(); + SteamNetworkingSockets.OnConnectionStatusChanged -= OnConnectionStatusChanged; - if (HostConnectionManager != null) - { - Debug.LogError("Sending Disconnect message"); - HostConnection.Close(false, 0, "Graceful disconnect"); - HostConnectionManager = null; - } - } + if (HostConnectionManager != null) + { + Debug.LogError("Sending Disconnect message"); + HostConnection.Close(false, 0, "Graceful disconnect"); + HostConnectionManager = null; + } + } - public void ReceiveData() - { - HostConnectionManager.Receive(MAX_MESSAGES); - } + public void ReceiveData() => HostConnectionManager.Receive(MAX_MESSAGES); - public void Send(byte[] data, int channelId) - { - Result res = SendSocket(HostConnection, data, channelId); + public void Send(byte[] data, int channelId) + { + var res = SendSocket(HostConnection, data, channelId); - if (res != Result.OK) - { - Debug.LogError($"Could not send: {res.ToString()}"); - } - } + if (res != Result.OK) + { + Debug.LogError($"Could not send: {res.ToString()}"); + } + } - private void SetConnectedComplete() => connectedComplete.SetResult(connectedComplete.Task); - private void OnConnectionFailed() => OnDisconnected.Invoke(); - public void FlushData() - { - HostConnection.Flush(); - } - } + private void SetConnectedComplete() => connectedComplete.SetResult(connectedComplete.Task); + private void OnConnectionFailed() => OnDisconnected.Invoke(); + public void FlushData() => HostConnection.Flush(); + } } \ No newline at end of file diff --git a/FizzyFacepunch/NextCommon.cs b/FizzyFacepunch/NextCommon.cs index d0db0f32..cb75ea83 100644 --- a/FizzyFacepunch/NextCommon.cs +++ b/FizzyFacepunch/NextCommon.cs @@ -7,32 +7,32 @@ using UnityEngine; public abstract class NextCommon { - protected const int MAX_MESSAGES = 256; + protected const int MAX_MESSAGES = 256; - protected Result SendSocket(Connection conn, byte[] data, int channelId) - { - Array.Resize(ref data, data.Length + 1); - data[data.Length - 1] = (byte)channelId; + protected Result SendSocket(Connection conn, byte[] data, int channelId) + { + Array.Resize(ref data, data.Length + 1); + data[data.Length - 1] = (byte)channelId; - GCHandle pinnedArray = GCHandle.Alloc(data, GCHandleType.Pinned); - IntPtr pData = pinnedArray.AddrOfPinnedObject(); - SendType sendFlag = channelId == Channels.Unreliable ? SendType.Unreliable : SendType.Reliable; - Result res = conn.SendMessage(pData, data.Length, sendFlag); - if (res != Result.OK) - { - Debug.LogWarning($"Send issue: {res}"); - } + var pinnedArray = GCHandle.Alloc(data, GCHandleType.Pinned); + var pData = pinnedArray.AddrOfPinnedObject(); + var sendFlag = channelId == Channels.Unreliable ? SendType.Unreliable : SendType.Reliable; + var res = conn.SendMessage(pData, data.Length, sendFlag); + if (res != Result.OK) + { + Debug.LogWarning($"Send issue: {res}"); + } - pinnedArray.Free(); - return res; - } + pinnedArray.Free(); + return res; + } - protected (byte[], int) ProcessMessage(IntPtr ptrs, int size) - { - byte[] managedArray = new byte[size]; - Marshal.Copy(ptrs, managedArray, 0, size); - int channel = managedArray[managedArray.Length - 1]; - Array.Resize(ref managedArray, managedArray.Length - 1); - return (managedArray, channel); - } + protected (byte[], int) ProcessMessage(IntPtr ptrs, int size) + { + var managedArray = new byte[size]; + Marshal.Copy(ptrs, managedArray, 0, size); + int channel = managedArray[managedArray.Length - 1]; + Array.Resize(ref managedArray, managedArray.Length - 1); + return (managedArray, channel); + } } \ No newline at end of file diff --git a/FizzyFacepunch/NextServer.cs b/FizzyFacepunch/NextServer.cs index 07b2dcac..6982bdc6 100644 --- a/FizzyFacepunch/NextServer.cs +++ b/FizzyFacepunch/NextServer.cs @@ -5,186 +5,183 @@ using UnityEngine; namespace Mirror.FizzySteam { - public class NextServer : NextCommon, IServer - { - private event Action OnConnected; - private event Action OnReceivedData; - private event Action OnDisconnected; - private event Action OnReceivedError; + public class NextServer : NextCommon, IServer + { + private event Action OnConnected; + private event Action OnReceivedData; + private event Action OnDisconnected; + private event Action OnReceivedError; - private BidirectionalDictionary connToMirrorID; - private BidirectionalDictionary steamIDToMirrorID; - private int maxConnections; - private int nextConnectionID; + private readonly BidirectionalDictionary connToMirrorID; + private readonly BidirectionalDictionary steamIDToMirrorID; + private readonly int maxConnections; + private int nextConnectionID; - private FizzySocketManager listenSocket; + private FizzySocketManager listenSocket; - private NextServer(int maxConnections) - { - this.maxConnections = maxConnections; - connToMirrorID = new BidirectionalDictionary(); - steamIDToMirrorID = new BidirectionalDictionary(); - nextConnectionID = 1; - SteamNetworkingSockets.OnConnectionStatusChanged += OnConnectionStatusChanged; - } + private NextServer(int maxConnections) + { + this.maxConnections = maxConnections; + connToMirrorID = new BidirectionalDictionary(); + steamIDToMirrorID = new BidirectionalDictionary(); + nextConnectionID = 1; + SteamNetworkingSockets.OnConnectionStatusChanged += OnConnectionStatusChanged; + } - public static NextServer CreateServer(FizzyFacepunch transport, int maxConnections) - { - NextServer s = new NextServer(maxConnections); + public static NextServer CreateServer(FizzyFacepunch transport, int maxConnections) + { + var s = new NextServer(maxConnections); - s.OnConnected += (id) => transport.OnServerConnected.Invoke(id); - s.OnDisconnected += (id) => transport.OnServerDisconnected.Invoke(id); - s.OnReceivedData += (id, data, ch) => transport.OnServerDataReceived.Invoke(id, new ArraySegment(data), ch); - s.OnReceivedError += (id, exception) => transport.OnServerError.Invoke(id, exception); + s.OnConnected += (id) => transport.OnServerConnected.Invoke(id); + s.OnDisconnected += (id) => transport.OnServerDisconnected.Invoke(id); + s.OnReceivedData += (id, data, ch) => transport.OnServerDataReceived.Invoke(id, new ArraySegment(data), ch); + s.OnReceivedError += (id, exception) => transport.OnServerError.Invoke(id, exception); - if (!SteamClient.IsValid) - { - Debug.LogError("SteamWorks not initialized."); - } + if (!SteamClient.IsValid) + { + Debug.LogError("SteamWorks not initialized."); + } - s.Host(); + s.Host(); - return s; - } + return s; + } - private void Host() - { - listenSocket = SteamNetworkingSockets.CreateRelaySocket(); - listenSocket.ForwardMessage = OnMessageReceived; - } + private void Host() + { + listenSocket = SteamNetworkingSockets.CreateRelaySocket(); + listenSocket.ForwardMessage = OnMessageReceived; + } - private void OnConnectionStatusChanged(Connection conn, ConnectionInfo info) - { - ulong clientSteamID = info.Identity.SteamId; - if (info.State == ConnectionState.Connecting) - { - if (connToMirrorID.Count >= maxConnections) - { - Debug.LogError($"Incoming connection {clientSteamID} would exceed max connection count. Rejecting."); - conn.Close(false, 0, "Max Connection Count"); - return; - } + private void OnConnectionStatusChanged(Connection conn, ConnectionInfo info) + { + ulong clientSteamID = info.Identity.SteamId; + if (info.State == ConnectionState.Connecting) + { + if (connToMirrorID.Count >= maxConnections) + { + Debug.LogError($"Incoming connection {clientSteamID} would exceed max connection count. Rejecting."); + conn.Close(false, 0, "Max Connection Count"); + return; + } - Result res; + Result res; - if ((res = conn.Accept()) == Result.OK) - { - Debug.LogError($"Accepting connection {clientSteamID}"); - } - else - { - Debug.LogError($"Connection {clientSteamID} could not be accepted: {res.ToString()}"); - } - } - else if (info.State == ConnectionState.Connected) - { - int connectionId = nextConnectionID++; - connToMirrorID.Add(conn, connectionId); - steamIDToMirrorID.Add(clientSteamID, connectionId); - OnConnected.Invoke(connectionId); - Debug.LogError($"Client with SteamID {clientSteamID} connected. Assigning connection id {connectionId}"); - } - else if (info.State == ConnectionState.ClosedByPeer) - { - if (connToMirrorID.TryGetValue(conn, out int connId)) - { - InternalDisconnect(connId, conn); - } - } - else - { - Debug.LogError($"Connection {clientSteamID} state changed: {info.State.ToString()}"); - } - } + if ((res = conn.Accept()) == Result.OK) + { + Debug.LogError($"Accepting connection {clientSteamID}"); + } + else + { + Debug.LogError($"Connection {clientSteamID} could not be accepted: {res.ToString()}"); + } + } + else if (info.State == ConnectionState.Connected) + { + var connectionId = nextConnectionID++; + connToMirrorID.Add(conn, connectionId); + steamIDToMirrorID.Add(clientSteamID, connectionId); + OnConnected.Invoke(connectionId); + Debug.LogError($"Client with SteamID {clientSteamID} connected. Assigning connection id {connectionId}"); + } + else if (info.State == ConnectionState.ClosedByPeer) + { + if (connToMirrorID.TryGetValue(conn, out var connId)) + { + InternalDisconnect(connId, conn); + } + } + else + { + Debug.LogError($"Connection {clientSteamID} state changed: {info.State.ToString()}"); + } + } - private void InternalDisconnect(int connId, Connection socket) - { - OnDisconnected.Invoke(connId); - socket.Close(false, 0, "Graceful disconnect"); - connToMirrorID.Remove(connId); - steamIDToMirrorID.Remove(connId); - Debug.LogError($"Client with SteamID {connId} disconnected."); - } + private void InternalDisconnect(int connId, Connection socket) + { + OnDisconnected.Invoke(connId); + socket.Close(false, 0, "Graceful disconnect"); + connToMirrorID.Remove(connId); + steamIDToMirrorID.Remove(connId); + Debug.LogError($"Client with SteamID {connId} disconnected."); + } - public void Disconnect(int connectionId) - { - if (connToMirrorID.TryGetValue(connectionId, out Connection conn)) - { - Debug.LogError($"Connection id {connectionId} disconnected."); - conn.Close(false, 0, "Disconnected by server"); - steamIDToMirrorID.Remove(connectionId); - connToMirrorID.Remove(connectionId); - OnDisconnected(connectionId); - } - else - { - Debug.LogWarning("Trying to disconnect unknown connection id: " + connectionId); - } - } + public void Disconnect(int connectionId) + { + if (connToMirrorID.TryGetValue(connectionId, out var conn)) + { + Debug.LogError($"Connection id {connectionId} disconnected."); + conn.Close(false, 0, "Disconnected by server"); + steamIDToMirrorID.Remove(connectionId); + connToMirrorID.Remove(connectionId); + OnDisconnected(connectionId); + } + else + { + Debug.LogWarning("Trying to disconnect unknown connection id: " + connectionId); + } + } - public void FlushData() - { - foreach (Connection conn in connToMirrorID.FirstTypes) - { - conn.Flush(); - } - } + public void FlushData() + { + foreach (var conn in connToMirrorID.FirstTypes) + { + conn.Flush(); + } + } - public void ReceiveData() - { - listenSocket.Receive(MAX_MESSAGES); - } + public void ReceiveData() => listenSocket.Receive(MAX_MESSAGES); - private void OnMessageReceived(Connection conn, IntPtr dataPtr, int size) - { - (byte[] data, int ch) = ProcessMessage(dataPtr, size); - OnReceivedData(connToMirrorID[conn], data, ch); - } + private void OnMessageReceived(Connection conn, IntPtr dataPtr, int size) + { + (var data, var ch) = ProcessMessage(dataPtr, size); + OnReceivedData(connToMirrorID[conn], data, ch); + } - public void Send(int connectionId, byte[] data, int channelId) - { - if (connToMirrorID.TryGetValue(connectionId, out Connection conn)) - { - Result res = SendSocket(conn, data, channelId); + public void Send(int connectionId, byte[] data, int channelId) + { + if (connToMirrorID.TryGetValue(connectionId, out var conn)) + { + var res = SendSocket(conn, data, channelId); - if (res == Result.NoConnection || res == Result.InvalidParam) - { - Debug.LogError($"Connection to {connectionId} was lost."); - InternalDisconnect(connectionId, conn); - } - else if (res != Result.OK) - { - Debug.LogError($"Could not send: {res.ToString()}"); - } - } - else - { - Debug.LogError("Trying to send on unknown connection: " + connectionId); - OnReceivedError.Invoke(connectionId, new Exception("ERROR Unknown Connection")); - } - } + if (res == Result.NoConnection || res == Result.InvalidParam) + { + Debug.LogError($"Connection to {connectionId} was lost."); + InternalDisconnect(connectionId, conn); + } + else if (res != Result.OK) + { + Debug.LogError($"Could not send: {res.ToString()}"); + } + } + else + { + Debug.LogError("Trying to send on unknown connection: " + connectionId); + OnReceivedError.Invoke(connectionId, new Exception("ERROR Unknown Connection")); + } + } - public string ServerGetClientAddress(int connectionId) - { - if (steamIDToMirrorID.TryGetValue(connectionId, out SteamId steamId)) - { - return steamId.ToString(); - } - else - { - Debug.LogError("Trying to get info on unknown connection: " + connectionId); - OnReceivedError.Invoke(connectionId, new Exception("ERROR Unknown Connection")); - return string.Empty; - } - } + public string ServerGetClientAddress(int connectionId) + { + if (steamIDToMirrorID.TryGetValue(connectionId, out var steamId)) + { + return steamId.ToString(); + } + else + { + Debug.LogError("Trying to get info on unknown connection: " + connectionId); + OnReceivedError.Invoke(connectionId, new Exception("ERROR Unknown Connection")); + return string.Empty; + } + } - public void Shutdown() - { - if (listenSocket != null) - { - SteamNetworkingSockets.OnConnectionStatusChanged -= OnConnectionStatusChanged; - listenSocket.Close(); - } - } - } + public void Shutdown() + { + if (listenSocket != null) + { + SteamNetworkingSockets.OnConnectionStatusChanged -= OnConnectionStatusChanged; + listenSocket.Close(); + } + } + } } \ No newline at end of file