From 607177d9b4809f6a11db028d172eb17ba8e94765 Mon Sep 17 00:00:00 2001 From: Alven Date: Tue, 2 May 2023 16:18:08 +0500 Subject: [PATCH 1/3] Adds UTP_TRANSPORT_2_0_ABOVE define in FishyUnityTransport.asmdef --- .../FishyUnityTransport/FishyUnityTransport.asmdef | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Assets/FishNet/Plugins/FishyUnityTransport/FishyUnityTransport.asmdef b/Assets/FishNet/Plugins/FishyUnityTransport/FishyUnityTransport.asmdef index b507ccd..b6b6db5 100644 --- a/Assets/FishNet/Plugins/FishyUnityTransport/FishyUnityTransport.asmdef +++ b/Assets/FishNet/Plugins/FishyUnityTransport/FishyUnityTransport.asmdef @@ -15,6 +15,12 @@ "precompiledReferences": [], "autoReferenced": true, "defineConstraints": [], - "versionDefines": [], + "versionDefines": [ + { + "name": "com.unity.transport", + "expression": "2.0.0-exp", + "define": "UTP_TRANSPORT_2_0_ABOVE" + } + ], "noEngineReferences": false } \ No newline at end of file From ae1460a5b3005e416116029cd392774f29898e2a Mon Sep 17 00:00:00 2001 From: Alven Date: Tue, 2 May 2023 16:21:39 +0500 Subject: [PATCH 2/3] Simplifying and fix bugs related to connection state changes --- .../FishyUnityTransport/Core/ClientSocket.cs | 64 +++++----- .../FishyUnityTransport/Core/CommonSocket.cs | 87 ++++++-------- .../FishyUnityTransport/Core/SendTarget.cs | 10 +- .../FishyUnityTransport/Core/ServerSocket.cs | 68 +++++------ .../FishyUnityTransport.cs | 111 +++++++----------- 5 files changed, 152 insertions(+), 188 deletions(-) diff --git a/Assets/FishNet/Plugins/FishyUnityTransport/Core/ClientSocket.cs b/Assets/FishNet/Plugins/FishyUnityTransport/Core/ClientSocket.cs index fd0d5fd..68018ab 100644 --- a/Assets/FishNet/Plugins/FishyUnityTransport/Core/ClientSocket.cs +++ b/Assets/FishNet/Plugins/FishyUnityTransport/Core/ClientSocket.cs @@ -17,7 +17,7 @@ namespace FishNet.Transporting.FishyUnityTransport [Serializable] internal class ClientSocket : CommonSocket { - private ulong _clientId; + private NetworkConnection _connection; private string _serverCommonName; private string _clientCaCertificate; @@ -37,7 +37,7 @@ public void SetClientSecrets(string serverCommonName, string caCertificate = nul public bool StartConnection() { - if (Driver.IsCreated || State != LocalConnectionState.Stopped) + if (Driver.IsCreated) { if (Transport.NetworkManager.CanLog(LoggingType.Error)) Debug.LogError("Attempting to start a client that is already active."); @@ -56,8 +56,6 @@ public bool StartConnection() Driver.Dispose(); } - // SetLocalConnectionState(LocalConnectionState.Started, false); - return false; } @@ -93,25 +91,38 @@ private bool ClientBindAndConnect() return false; } - NetworkConnection connection = Driver.Connect(serverEndpoint); - _clientId = ParseClientId(connection); + _connection = Driver.Connect(serverEndpoint); return true; } public void SendToServer(byte channelId, ArraySegment segment) { - Send(channelId, segment, _clientId); + Send(channelId, segment, _connection); } public bool StopClient() { - if (!DisconnectLocalClient()) return false; + LocalConnectionState state = State; + if (State is LocalConnectionState.Stopped or LocalConnectionState.Stopping) return false; + + SetLocalConnectionState(LocalConnectionState.Stopping); + + FlushSendQueuesForClientId(_connection); + + if (_connection.Disconnect(Driver) != 0) + { + SetLocalConnectionState(state); + return false; + } Shutdown(); + + SetLocalConnectionState(LocalConnectionState.Stopped); + return true; } - protected override void HandleDisconnectEvent(ulong clientId) + protected override void HandleDisconnectEvent(NetworkConnection connection) { // Handle cases where we're a client receiving a Disconnect event. The // meaning of the event depends on our current state. If we were connected @@ -120,44 +131,39 @@ protected override void HandleDisconnectEvent(ulong clientId) if (State == LocalConnectionState.Started) { SetLocalConnectionState(LocalConnectionState.Stopped); - // m_ServerClientId = default; + _connection = default; } else if (State == LocalConnectionState.Stopped) { Debug.LogError("Failed to connect to server."); - // m_ServerClientId = default; + _connection = default; } } - public bool DisconnectLocalClient() + protected override void Shutdown() { - if (State is LocalConnectionState.Stopped or LocalConnectionState.Stopping) return false; - - SetLocalConnectionState(LocalConnectionState.Stopping); - - FlushSendQueuesForClientId(_clientId); - - if (ParseClientId(_clientId).Disconnect(Driver) != 0) return false; - ReliableReceiveQueues.Remove(_clientId); - ClearSendQueuesForClientId(_clientId); - - SetLocalConnectionState(LocalConnectionState.Stopped); - - return true; + base.Shutdown(); + _connection = default; } protected override void SetLocalConnectionState(LocalConnectionState state) { State = state; - Transport.HandleClientConnectionState(state, _clientId, Transport.Index); + if (Transport) + { + Transport.HandleClientConnectionState(state, _connection, Transport.Index); + } } - protected override void OnPushMessageFailure(int channelId, ArraySegment payload, ulong clientId) + protected override void OnPushMessageFailure(int channelId, ArraySegment payload, NetworkConnection connection) { - DisconnectLocalClient(); + if (connection == _connection) + { + StopClient(); + } } - protected override void HandleReceivedData(ArraySegment message, Channel channel, ulong clientId) + protected override void HandleReceivedData(ArraySegment message, Channel channel, NetworkConnection connection) { Transport.HandleClientReceivedData(message, channel, Transport.Index); } diff --git a/Assets/FishNet/Plugins/FishyUnityTransport/Core/CommonSocket.cs b/Assets/FishNet/Plugins/FishyUnityTransport/Core/CommonSocket.cs index c18dd6c..c758fc2 100644 --- a/Assets/FishNet/Plugins/FishyUnityTransport/Core/CommonSocket.cs +++ b/Assets/FishNet/Plugins/FishyUnityTransport/Core/CommonSocket.cs @@ -20,7 +20,7 @@ namespace FishNet.Transporting.FishyUnityTransport { - internal abstract class CommonSocket + internal abstract class CommonSocket : IDisposable { protected FishyUnityTransport Transport; protected NetworkManager NetworkManager; @@ -44,7 +44,7 @@ internal abstract class CommonSocket /// /// SendQueue dictionary is used to batch events instead of sending them immediately. /// - protected readonly Dictionary ReliableReceiveQueues = new(); + protected readonly Dictionary ReliableReceiveQueues = new(); #endregion @@ -75,7 +75,7 @@ protected void InitializeNetworkSettings() #endif #endif } - + #region Iterate Incoming /// @@ -92,7 +92,7 @@ internal void IterateIncoming() { Debug.LogError("Transport failure! Relay allocation needs to be recreated, and NetworkManager restarted. " + "Use NetworkManager.OnTransportFailure to be notified of such events programmatically."); - + // TODO // InvokeOnTransportEvent(TransportFailure); return; @@ -111,17 +111,16 @@ private bool AcceptConnection() return false; } - Transport.HandleRemoteConnectionState(RemoteConnectionState.Started, ParseClientId(connection), Transport.Index); + Transport.HandleRemoteConnectionState(RemoteConnectionState.Started, connection, Transport.Index); return true; } - protected virtual void HandleDisconnectEvent(ulong clientId) { } + protected virtual void HandleDisconnectEvent(NetworkConnection connection) { } private bool ProcessEvent() { NetworkEvent.Type eventType = Driver.PopEvent(out NetworkConnection networkConnection, out DataStreamReader reader, out NetworkPipeline pipeline); - ulong clientId = ParseClientId(networkConnection); switch (eventType) { case NetworkEvent.Type.Connect: @@ -131,16 +130,16 @@ private bool ProcessEvent() } case NetworkEvent.Type.Disconnect: { - ReliableReceiveQueues.Remove(clientId); - ClearSendQueuesForClientId(clientId); + ReliableReceiveQueues.Remove(networkConnection); + ClearSendQueuesForClientId(networkConnection); - HandleDisconnectEvent(clientId); + HandleDisconnectEvent(networkConnection); return true; } case NetworkEvent.Type.Data: { - ReceiveMessages(clientId, pipeline, reader); + ReceiveMessages(networkConnection, pipeline, reader); return true; } } @@ -165,16 +164,6 @@ public void IterateOutgoing() } } - protected static unsafe ulong ParseClientId(NetworkConnection utpConnectionId) - { - return *(ulong*)&utpConnectionId; - } - - protected static unsafe NetworkConnection ParseClientId(ulong clientId) - { - return *(NetworkConnection*)&clientId; - } - /// /// Returns this drivers max header size based on the requested channel. /// @@ -185,7 +174,7 @@ public int GetMaxHeaderSize(Channel channel) return State == LocalConnectionState.Started ? Driver.MaxHeaderSize(SelectSendPipeline(channel)) : 0; } - private void DisposeInternals() + public void Dispose() { if (Driver.IsCreated) { @@ -205,7 +194,7 @@ private void DisposeInternals() /// /// Sends a message via the transport /// - public void Send(int channelId, ArraySegment payload, ulong clientId) + public void Send(int channelId, ArraySegment payload, NetworkConnection connection) { if (State != LocalConnectionState.Started) return; @@ -217,7 +206,7 @@ public void Send(int channelId, ArraySegment payload, ulong clientId) return; } - var sendTarget = new SendTarget(clientId, pipeline); + var sendTarget = new SendTarget(connection, pipeline); if (!_sendQueue.TryGetValue(sendTarget, out BatchedSendQueue queue)) { // timeout. The idea being that if the send queue contains enough reliable data that @@ -233,7 +222,7 @@ public void Send(int channelId, ArraySegment payload, ulong clientId) // the only case where a full send queue causes a connection loss. Full unreliable // send queues are dealt with by flushing it out to the network or simply dropping // new messages if that fails. - + int maxCapacity = Transport.MaxSendQueueSize > 0 ? Transport.MaxSendQueueSize : Transport.DisconnectTimeoutMS * FishyUnityTransport.MaxReliableThroughput; queue = new BatchedSendQueue(Math.Max(maxCapacity, Transport.MaxPayloadSize)); @@ -250,9 +239,9 @@ public void Send(int channelId, ArraySegment payload, ulong clientId) // this point they're bound to become desynchronized. Debug.LogError($"Couldn't add payload of size {payload.Count} to reliable send queue. " + - $"Closing connection {Transport.ClientIdToTransportId(clientId)} as reliability guarantees can't be maintained."); + $"Closing connection {Transport.ConnectionToTransportId(connection)} as reliability guarantees can't be maintained."); - OnPushMessageFailure(channelId, payload, clientId); + OnPushMessageFailure(channelId, payload, connection); } else { @@ -270,7 +259,7 @@ public void Send(int channelId, ArraySegment payload, ulong clientId) } } - protected abstract void OnPushMessageFailure(int channelId, ArraySegment payload, ulong clientId); + protected abstract void OnPushMessageFailure(int channelId, ArraySegment payload, NetworkConnection connection); /// /// Send all queued messages @@ -296,16 +285,16 @@ private struct SendBatchedMessagesJob : IJob public void Execute() { - ulong clientId = Target.ClientId; - NetworkConnection connection = ParseClientId(clientId); + NetworkConnection connection = Target.Connection; NetworkPipeline pipeline = Target.NetworkPipeline; while (!Queue.IsEmpty) { int result = Driver.BeginSend(pipeline, connection, out DataStreamWriter writer); - if (result != (int)StatusCode.Success) + + if ((StatusCode)result != StatusCode.Success) { - Debug.LogError($"Error sending message:{result}, {FishyUnityTransport.ParseClientIdToTransportId(clientId)}"); + Debug.LogError($"Error sending the message to client {FishyUnityTransport.ParseTransportId(connection)} with code: {(StatusCode)result}"); return; } @@ -330,9 +319,9 @@ public void Execute() // and we'll retry sending them later). Otherwise log the error and remove the // message from the queue (we don't want to resend it again since we'll likely // just get the same error again). - if (result != (int)StatusCode.NetworkSendQueueFull) + if ((StatusCode)result != StatusCode.NetworkSendQueueFull) { - Debug.LogError($"Error sending the message: {result}, {FishyUnityTransport.ParseClientIdToTransportId(clientId)}"); + Debug.LogError($"Error sending the message to client {FishyUnityTransport.ParseTransportId(connection)} with code: {(StatusCode)result}"); Queue.Consume(written); } @@ -345,19 +334,19 @@ public void Execute() /// /// Returns a message from the transport /// - private void ReceiveMessages(ulong clientId, NetworkPipeline pipeline, DataStreamReader dataReader) + private void ReceiveMessages(NetworkConnection connection, NetworkPipeline pipeline, DataStreamReader dataReader) { BatchedReceiveQueue queue; if (pipeline == _reliableSequencedPipeline) { - if (ReliableReceiveQueues.TryGetValue(clientId, out queue)) + if (ReliableReceiveQueues.TryGetValue(connection, out queue)) { queue.PushReader(dataReader); } else { queue = new BatchedReceiveQueue(dataReader); - ReliableReceiveQueues[clientId] = queue; + ReliableReceiveQueues[connection] = queue; } } else @@ -376,19 +365,19 @@ private void ReceiveMessages(ulong clientId, NetworkPipeline pipeline, DataStrea Channel channel = pipeline == _reliableSequencedPipeline ? Channel.Reliable : Channel.Unreliable; - HandleReceivedData(message, channel, clientId); + HandleReceivedData(message, channel, connection); } } - protected abstract void HandleReceivedData(ArraySegment message, Channel channel, ulong clientId); + protected abstract void HandleReceivedData(ArraySegment message, Channel channel, NetworkConnection connection); - protected void ClearSendQueuesForClientId(ulong clientId) + protected void ClearSendQueuesForClientId(NetworkConnection connection) { // NativeList and manual foreach avoids any allocations. using var keys = new NativeList(16, Allocator.Temp); foreach (SendTarget key in _sendQueue.Keys) { - if (key.ClientId == clientId) + if (key.Connection == connection) { keys.Add(key); } @@ -401,18 +390,18 @@ protected void ClearSendQueuesForClientId(ulong clientId) } } - protected void FlushSendQueuesForClientId(ulong clientId) + protected void FlushSendQueuesForClientId(NetworkConnection connection) { foreach (var kvp in _sendQueue) { - if (kvp.Key.ClientId == clientId) + if (kvp.Key.Connection == connection) { SendBatchedMessages(kvp.Key, kvp.Value); } } } - public virtual void Shutdown() + protected virtual void Shutdown() { if (!Driver.IsCreated) { @@ -432,7 +421,7 @@ public virtual void Shutdown() // but there might be disconnect messages and those require an update call.) Driver.ScheduleUpdate().Complete(); - DisposeInternals(); + Dispose(); ReliableReceiveQueues.Clear(); } @@ -457,8 +446,10 @@ protected void InitDriver(bool asServer) #region DebugSimulator +#if UTP_TRANSPORT_2_0_ABOVE + [Obsolete("DebugSimulator is no longer supported and has no effect. Use Network Simulator from the Multiplayer Tools package.", false)] +#endif private SimulatorParameters DebugSimulator => Transport.DebugSimulator; - private uint? DebugSimulatorRandomSeed => Transport.DebugSimulatorRandomSeed; #if UTP_TRANSPORT_2_0_ABOVE private void ConfigureSimulatorForUtp2() @@ -471,7 +462,7 @@ private void ConfigureSimulatorForUtp2() packetDelayMs: 0, packetJitterMs: 0, packetDropPercentage: 0, - randomSeed: DebugSimulatorRandomSeed ?? (uint)System.Diagnostics.Stopwatch.GetTimestamp() + randomSeed: Transport.DebugSimulatorRandomSeed ??= (uint)System.Diagnostics.Stopwatch.GetTimestamp() , mode: ApplyMode.AllPackets ); @@ -486,7 +477,7 @@ private void ConfigureSimulatorForUtp1() packetDelayMs: DebugSimulator.PacketDelayMS, packetJitterMs: DebugSimulator.PacketJitterMS, packetDropPercentage: DebugSimulator.PacketDropRate, - randomSeed: DebugSimulatorRandomSeed ?? (uint)System.Diagnostics.Stopwatch.GetTimestamp() + randomSeed: Transport.DebugSimulatorRandomSeed ??= (uint)System.Diagnostics.Stopwatch.GetTimestamp() ); } #endif diff --git a/Assets/FishNet/Plugins/FishyUnityTransport/Core/SendTarget.cs b/Assets/FishNet/Plugins/FishyUnityTransport/Core/SendTarget.cs index 17cb1b1..7eec89c 100644 --- a/Assets/FishNet/Plugins/FishyUnityTransport/Core/SendTarget.cs +++ b/Assets/FishNet/Plugins/FishyUnityTransport/Core/SendTarget.cs @@ -8,18 +8,18 @@ namespace FishNet.Transporting.FishyUnityTransport /// public readonly struct SendTarget : IEquatable { - public readonly ulong ClientId; + public readonly NetworkConnection Connection; public readonly NetworkPipeline NetworkPipeline; - public SendTarget(ulong clientId, NetworkPipeline networkPipeline) + public SendTarget(NetworkConnection connection, NetworkPipeline networkPipeline) { - ClientId = clientId; + Connection = connection; NetworkPipeline = networkPipeline; } public bool Equals(SendTarget other) { - return ClientId == other.ClientId && NetworkPipeline.Equals(other.NetworkPipeline); + return Connection == other.Connection && NetworkPipeline.Equals(other.NetworkPipeline); } public override bool Equals(object obj) @@ -31,7 +31,7 @@ public override int GetHashCode() { unchecked { - return (ClientId.GetHashCode() * 397) ^ NetworkPipeline.GetHashCode(); + return (Connection.GetHashCode() * 397) ^ NetworkPipeline.GetHashCode(); } } } diff --git a/Assets/FishNet/Plugins/FishyUnityTransport/Core/ServerSocket.cs b/Assets/FishNet/Plugins/FishyUnityTransport/Core/ServerSocket.cs index a59ce6e..de880ac 100644 --- a/Assets/FishNet/Plugins/FishyUnityTransport/Core/ServerSocket.cs +++ b/Assets/FishNet/Plugins/FishyUnityTransport/Core/ServerSocket.cs @@ -95,16 +95,13 @@ private bool ServerBindAndListen(NetworkEndpoint endPoint) // and start listening for new connections. Driver.Listen(); - if (!Driver.Listening) + if (Driver.Listening) return true; + if (Transport.NetworkManager.CanLog(LoggingType.Error)) { - if (Transport.NetworkManager.CanLog(LoggingType.Error)) - { - Debug.LogError("Server failed to listen"); - } - return false; + Debug.LogError("Server failed to listen"); } + return false; - return true; } /// @@ -125,35 +122,31 @@ public bool StopServer() /// /// Stops a remote client from the server, disconnecting the client. /// - /// - public bool DisconnectRemoteClient(ulong clientId) + /// + public bool DisconnectRemoteClient(NetworkConnection connection) { + Debug.Assert(State == LocalConnectionState.Started, "DisconnectRemoteClient should be called on a listening server"); if (State != LocalConnectionState.Started) return false; - FlushSendQueuesForClientId(clientId); - - ReliableReceiveQueues.Remove(clientId); - ClearSendQueuesForClientId(clientId); + FlushSendQueuesForClientId(connection); + ReliableReceiveQueues.Remove(connection); + ClearSendQueuesForClientId(connection); - NetworkConnection connection = ParseClientId(clientId); if (Driver.GetConnectionState(connection) != NetworkConnection.State.Disconnected) { Driver.Disconnect(connection); } - - Transport.HandleRemoteConnectionState(RemoteConnectionState.Stopped, clientId, Transport.Index); - + Transport.HandleRemoteConnectionState(RemoteConnectionState.Stopped, connection, Transport.Index); return true; } - protected override void HandleDisconnectEvent(ulong clientId) + protected override void HandleDisconnectEvent(NetworkConnection connection) { - Transport.HandleRemoteConnectionState(RemoteConnectionState.Stopped, clientId, Transport.Index); + Transport.HandleRemoteConnectionState(RemoteConnectionState.Stopped, connection, Transport.Index); } - public string GetConnectionAddress(ulong clientId) + public string GetConnectionAddress(NetworkConnection connection) { - NetworkConnection connection = ParseClientId(clientId); return connection.GetState(Driver) == NetworkConnection.State.Disconnected ? string.Empty #if UTP_TRANSPORT_2_0_ABOVE @@ -167,20 +160,11 @@ protected virtual void HandleIncomingConnection(NetworkConnection incomingConnec { if (NetworkManager.ServerManager.Clients.Count >= Transport.GetMaximumClients()) { - DisconnectRemoteClient(ParseClientId(incomingConnection)); + DisconnectRemoteClient(incomingConnection); return; } - Transport.HandleRemoteConnectionState(new RemoteConnectionStateArgs(RemoteConnectionState.Started, incomingConnection.GetHashCode(), Transport.Index)); - } - - /// - /// Gets the current ConnectionState of a remote client on the server. - /// - /// ConnectionId to get ConnectionState for. - public NetworkConnection.State GetConnectionState(ulong clientId) - { - return ParseClientId(clientId).GetState(Driver); + Transport.HandleRemoteConnectionState(RemoteConnectionState.Started, incomingConnection, Transport.Index); } protected override void SetLocalConnectionState(LocalConnectionState state) @@ -188,18 +172,21 @@ protected override void SetLocalConnectionState(LocalConnectionState state) if (state == State) return; State = state; - - Transport.HandleServerConnectionState(new ServerConnectionStateArgs(state, Transport.Index)); + if (Transport) + { + Transport.HandleServerConnectionState(new ServerConnectionStateArgs(state, Transport.Index)); + } } - protected override void OnPushMessageFailure(int channelId, ArraySegment payload, ulong clientId) + protected override void OnPushMessageFailure(int channelId, ArraySegment payload, NetworkConnection connection) { - DisconnectRemoteClient(clientId); + DisconnectRemoteClient(connection); + Transport.HandleRemoteConnectionState(RemoteConnectionState.Stopped, connection, Transport.Index); } - protected override void HandleReceivedData(ArraySegment message, Channel channel, ulong clientId) + protected override void HandleReceivedData(ArraySegment message, Channel channel, NetworkConnection connection) { - Transport.HandleServerReceivedData(message, channel, clientId, Transport.Index); + Transport.HandleServerReceivedData(message, channel, connection, Transport.Index); } protected override void SetupSecureParameters() @@ -211,5 +198,10 @@ protected override void SetupSecureParameters() NetworkSettings.WithSecureServerParameters(_serverCertificate, _serverPrivateKey); } + + public NetworkConnection.State GetConnectionState(NetworkConnection connection) + { + return connection.GetState(Driver); + } } } \ No newline at end of file diff --git a/Assets/FishNet/Plugins/FishyUnityTransport/FishyUnityTransport.cs b/Assets/FishNet/Plugins/FishyUnityTransport/FishyUnityTransport.cs index 7d15b27..c5e51aa 100644 --- a/Assets/FishNet/Plugins/FishyUnityTransport/FishyUnityTransport.cs +++ b/Assets/FishNet/Plugins/FishyUnityTransport/FishyUnityTransport.cs @@ -1,5 +1,7 @@ using System; +using System.Collections; using System.Collections.Generic; +using System.Linq; using FishNet.Managing; using FishNet.Managing.Logging; using Unity.Networking.Transport; @@ -19,6 +21,11 @@ namespace FishNet.Transporting.FishyUnityTransport [AddComponentMenu("FishNet/Transport/FishyUnityTransport")] public class FishyUnityTransport : Transport { + ~FishyUnityTransport() + { + Shutdown(); + } + #region Constants /// @@ -62,7 +69,7 @@ public bool UseWebSockets [Tooltip("Per default the client/server communication will not be encrypted. Select true to enable DTLS for UDP and TLS for Websocket.")] [SerializeField] - private bool _useEncryption = false; + private bool _useEncryption; /// /// Per default the client/server communication will not be encrypted. Select true to enable DTLS for UDP and TLS for Websocket. /// @@ -137,7 +144,7 @@ public int ConnectTimeoutMS get => _connectTimeoutMS; set => _connectTimeoutMS = value; } - + [Tooltip("The maximum amount of connection attempts we will try before disconnecting.")] [SerializeField] private int _maxConnectAttempts = NetworkParameterConstants.MaxConnectAttempts; @@ -189,8 +196,7 @@ public int DisconnectTimeoutMS [Range(1, 4095)] [SerializeField] private int _maximumClients = 4095; - internal uint? DebugSimulatorRandomSeed { get; set; } = null; - + internal uint? DebugSimulatorRandomSeed { get; set; } internal RelayServerData RelayServerDataInternal; public RelayServerData RelayServerData => RelayServerDataInternal; @@ -198,14 +204,16 @@ public int DisconnectTimeoutMS private readonly ServerSocket _serverSocket = new(); private readonly ClientSocket _clientSocket = new(); - #region ClientId And TransportId + #region Connection And TransportId + + private readonly Dictionary _transportIdToClientIdMap = new(); + private readonly Dictionary _clientIdToTransportIdMap = new(); - private readonly Dictionary _transportIdToClientIdMap = new(); - private readonly Dictionary _clientIdToTransportIdMap = new(); + internal int ConnectionToTransportId(NetworkConnection connection) => _clientIdToTransportIdMap[connection]; - internal int ClientIdToTransportId(ulong clientId) => _clientIdToTransportIdMap[clientId]; + private NetworkConnection TransportIdToConnection(int transportId) => _transportIdToClientIdMap[transportId]; - private ulong TransportIdToClientId(int transportId) => _transportIdToClientIdMap[transportId]; + internal static int ParseTransportId(NetworkConnection connection) => connection.GetHashCode(); #endregion @@ -231,15 +239,15 @@ private void OnDestroy() #region ConnectionStates. - public override string GetConnectionAddress(int connectionId) - { - return _serverSocket.GetConnectionAddress(TransportIdToClientId(connectionId)); - } - public override event Action OnClientConnectionState; public override event Action OnServerConnectionState; public override event Action OnRemoteConnectionState; + public override string GetConnectionAddress(int connectionId) + { + return _serverSocket.GetConnectionAddress(TransportIdToConnection(connectionId)); + } + public override LocalConnectionState GetConnectionState(bool server) { return server ? _serverSocket.State : _clientSocket.State; @@ -247,7 +255,7 @@ public override LocalConnectionState GetConnectionState(bool server) public override RemoteConnectionState GetConnectionState(int connectionId) { - return _serverSocket.GetConnectionState(TransportIdToClientId(connectionId)) == NetworkConnection.State.Connected + return _serverSocket.GetConnectionState(TransportIdToConnection(connectionId)) == NetworkConnection.State.Connected ? RemoteConnectionState.Started : RemoteConnectionState.Stopped; } @@ -257,19 +265,19 @@ public override void HandleClientConnectionState(ClientConnectionStateArgs conne OnClientConnectionState?.Invoke(connectionStateArgs); } - internal void HandleClientConnectionState(LocalConnectionState connectionState, ulong clientId, int transportIndex) + internal void HandleClientConnectionState(LocalConnectionState connectionState, NetworkConnection connection, int transportIndex) { - int transportId = ParseClientIdToTransportId(clientId); + int transportId = ParseTransportId(connection); switch (connectionState) { case LocalConnectionState.Started: - _transportIdToClientIdMap[transportId] = clientId; - _clientIdToTransportIdMap[clientId] = transportId; + _transportIdToClientIdMap[transportId] = connection; + _clientIdToTransportIdMap[connection] = transportId; break; case LocalConnectionState.Stopped: _transportIdToClientIdMap.Remove(transportId); - _clientIdToTransportIdMap.Remove(clientId); + _clientIdToTransportIdMap.Remove(connection); break; } @@ -281,18 +289,18 @@ public override void HandleServerConnectionState(ServerConnectionStateArgs conne OnServerConnectionState?.Invoke(connectionStateArgs); } - internal void HandleRemoteConnectionState(RemoteConnectionState state, ulong clientId, int transportIndex) + internal void HandleRemoteConnectionState(RemoteConnectionState state, NetworkConnection connection, int transportIndex) { - int transportId = ParseClientIdToTransportId(clientId); + int transportId = ParseTransportId(connection); switch (state) { case RemoteConnectionState.Started: - _transportIdToClientIdMap[transportId] = clientId; - _clientIdToTransportIdMap[clientId] = transportId; + _transportIdToClientIdMap[transportId] = connection; + _clientIdToTransportIdMap[connection] = transportId; break; case RemoteConnectionState.Stopped: _transportIdToClientIdMap.Remove(transportId); - _clientIdToTransportIdMap.Remove(clientId); + _clientIdToTransportIdMap.Remove(connection); break; default: throw new ArgumentOutOfRangeException(nameof(state), state, null); @@ -306,11 +314,6 @@ public override void HandleRemoteConnectionState(RemoteConnectionStateArgs conne OnRemoteConnectionState?.Invoke(connectionStateArgs); } - internal static int ParseClientIdToTransportId(ulong clientId) - { - return clientId.GetHashCode(); - } - #endregion #region Iterating. @@ -338,6 +341,7 @@ public override void IterateOutgoing(bool server) _clientSocket.IterateOutgoing(); } } + #endregion #region ReceivedData. @@ -356,9 +360,9 @@ public override void HandleClientReceivedDataArgs(ClientReceivedDataArgs receive public override event Action OnServerReceivedData; - internal void HandleServerReceivedData(ArraySegment message, Channel channel, ulong clientId, int transportIndex) + internal void HandleServerReceivedData(ArraySegment message, Channel channel, NetworkConnection connection, int transportIndex) { - HandleServerReceivedDataArgs(new ServerReceivedDataArgs(message, channel, ClientIdToTransportId(clientId), transportIndex)); + HandleServerReceivedDataArgs(new ServerReceivedDataArgs(message, channel, ConnectionToTransportId(connection), transportIndex)); } public override void HandleServerReceivedDataArgs(ServerReceivedDataArgs receivedDataArgs) @@ -369,6 +373,7 @@ public override void HandleServerReceivedDataArgs(ServerReceivedDataArgs receive #endregion #region Sending. + public override void SendToServer(byte channelId, ArraySegment segment) { if (_clientSocket.State != LocalConnectionState.Started) return; @@ -378,8 +383,9 @@ public override void SendToServer(byte channelId, ArraySegment segment) public override void SendToClient(byte channelId, ArraySegment segment, int connectionId) { if (_serverSocket.State != LocalConnectionState.Started) return; - _serverSocket.Send(channelId, segment, TransportIdToClientId(connectionId)); + _serverSocket.Send(channelId, segment, TransportIdToConnection(connectionId)); } + #endregion #region Configuration. @@ -520,25 +526,23 @@ public void SetConnectionData(string ipv4Address, ushort port, string listenAddr public override bool StartConnection(bool server) { - return server ? StartServer() : StartClient(); + return server ? _serverSocket.StartConnection() : _clientSocket.StartConnection(); } public override bool StopConnection(bool server) { - return server ? StopServer() : StopClient(); + return server ? _serverSocket.StopServer() : _clientSocket.StopClient(); } public override bool StopConnection(int connectionId, bool immediately) { - return StopClient(connectionId); + return _serverSocket.DisconnectRemoteClient(TransportIdToConnection(connectionId)); } public override void Shutdown() { StopConnection(false); StopConnection(true); - _serverSocket.Shutdown(); - _clientSocket.Shutdown(); _transportIdToClientIdMap.Clear(); _clientIdToTransportIdMap.Clear(); } @@ -549,7 +553,7 @@ public override void Shutdown() public override int GetMTU(byte channelId) { - //Check for client activity + // Check for client activity if (_clientSocket is { State: LocalConnectionState.Started }) { return NetworkParameterConstants.MTU - _clientSocket.GetMaxHeaderSize((Channel)channelId); @@ -564,34 +568,5 @@ public override int GetMTU(byte channelId) } #endregion - - #region Privates. - - private bool StartServer() - { - return _serverSocket.StartConnection(); - } - - private bool StopServer() - { - return _serverSocket != null && _serverSocket.StopServer(); - } - - private bool StartClient() - { - return _clientSocket.StartConnection(); - } - - private bool StopClient() - { - return _clientSocket.StopClient(); - } - - private bool StopClient(int connectionId) - { - return _serverSocket.DisconnectRemoteClient(TransportIdToClientId(connectionId)); - } - - #endregion } } \ No newline at end of file From 08fee6ce50eab1703812ce3658563ec11afbdc89 Mon Sep 17 00:00:00 2001 From: Alven Date: Tue, 2 May 2023 16:22:46 +0500 Subject: [PATCH 3/3] Remove an unused assembly --- .../Plugins/FishyUnityTransport/FishyUnityTransport.asmdef | 1 - 1 file changed, 1 deletion(-) diff --git a/Assets/FishNet/Plugins/FishyUnityTransport/FishyUnityTransport.asmdef b/Assets/FishNet/Plugins/FishyUnityTransport/FishyUnityTransport.asmdef index b6b6db5..4808762 100644 --- a/Assets/FishNet/Plugins/FishyUnityTransport/FishyUnityTransport.asmdef +++ b/Assets/FishNet/Plugins/FishyUnityTransport/FishyUnityTransport.asmdef @@ -4,7 +4,6 @@ "references": [ "GUID:7c88a4a7926ee5145ad2dfa06f454c67", "GUID:e0cd26848372d4e5c891c569017e11f1", - "GUID:fe25561d224ed4743af4c60938a59d0b", "GUID:f2d49d9fa7e7eb3418e39723a7d3b92f", "GUID:2665a8d13d1b3f18800f46e256720795" ],