From 5e69129667f1fd5bb6b1cef1354f7a2834fd223c Mon Sep 17 00:00:00 2001 From: ALEXTANG <574809918@qq.com> Date: Wed, 12 Jul 2023 17:35:05 +0800 Subject: [PATCH] Remove old networkmodule Remove old networkmodule --- Assets/GameScripts/Editor/Inspector.meta | 8 - .../Editor/Inspector/NetworkInspector.cs | 62 - .../Editor/Inspector/NetworkInspector.cs.meta | 3 - .../GameScripts/HotFix/GameLogic/Network.meta | 3 - .../GameLogic/Network/ClientConnectWatcher.cs | 166 -- .../Network/ClientConnectWatcher.cs.meta | 3 - .../HotFix/GameLogic/Network/GameClient.cs | 428 ---- .../GameLogic/Network/GameClient.cs.meta | 3 - .../HotFix/GameLogic/Network/MsgDispatcher.cs | 265 -- .../GameLogic/Network/MsgDispatcher.cs.meta | 3 - .../GameLogic/Network/NetworkChannelHelper.cs | 226 -- .../Network/NetworkChannelHelper.cs.meta | 3 - .../HotFix/GameLogic/Network/NetworkCore.meta | 3 - .../Network/NetworkCore/AddressFamily.cs | 23 - .../Network/NetworkCore/AddressFamily.cs.meta | 3 - .../Network/NetworkCore/Interface.meta | 3 - .../NetworkCore/Interface/INetworkChannel.cs | 180 -- .../Interface/INetworkChannel.cs.meta | 3 - .../Interface/INetworkChannelHelper.cs | 67 - .../Interface/INetworkChannelHelper.cs.meta | 3 - .../NetworkCore/Interface/INetworkManager.cs | 84 - .../Interface/INetworkManager.cs.meta | 3 - .../NetworkCore/Interface/IPacketHeader.cs | 16 - .../Interface/IPacketHeader.cs.meta | 3 - .../GameLogic/Network/NetworkCore/Kcp.meta | 3 - .../Network/NetworkCore/Kcp/Core.meta | 8 - .../Network/NetworkCore/Kcp/Core/FakeKcpIO.cs | 71 - .../NetworkCore/Kcp/Core/FakeKcpIO.cs.meta | 11 - .../NetworkCore/Kcp/Core/IKcpInterface.cs | 147 -- .../Kcp/Core/IKcpInterface.cs.meta | 11 - .../NetworkCore/Kcp/Core/IKcpSegment.cs | 88 - .../NetworkCore/Kcp/Core/IKcpSegment.cs.meta | 11 - .../Network/NetworkCore/Kcp/Core/Kcp.cs | 387 --- .../Network/NetworkCore/Kcp/Core/Kcp.cs.meta | 11 - .../Network/NetworkCore/Kcp/Core/KcpCore.cs | 2207 ----------------- .../NetworkCore/Kcp/Core/KcpCore.cs.meta | 11 - .../Network/NetworkCore/Kcp/Core/KcpIO.cs | 262 -- .../NetworkCore/Kcp/Core/KcpIO.cs.meta | 11 - .../NetworkCore/Kcp/Core/KcpOutputWriter.cs | 50 - .../Kcp/Core/KcpOutputWriter.cs.meta | 11 - .../NetworkCore/Kcp/Core/KcpSegment.cs | 402 --- .../NetworkCore/Kcp/Core/KcpSegment.cs.meta | 11 - .../Network/NetworkCore/Kcp/Core/KcpTrace.cs | 79 - .../NetworkCore/Kcp/Core/KcpTrace.cs.meta | 11 - .../NetworkCore/Kcp/Core/SegManager.cs | 265 -- .../NetworkCore/Kcp/Core/SegManager.cs.meta | 11 - .../NetworkCore/Kcp/Core/SimpleKcpClient.cs | 65 - .../Kcp/Core/SimpleKcpClient.cs.meta | 11 - .../NetworkCore/Kcp/Core/SimpleKcpServer.cs | 48 - .../Kcp/Core/SimpleKcpServer.cs.meta | 3 - .../Network/NetworkCore/Kcp/Core/Utility.cs | 73 - .../NetworkCore/Kcp/Core/Utility.cs.meta | 11 - .../Kcp/NetworkManager.KcpNetworkChannel.cs | 287 --- .../NetworkManager.KcpNetworkChannel.cs.meta | 3 - .../GameLogic/Network/NetworkCore/NetUtil.cs | 54 - .../Network/NetworkCore/NetUtil.cs.meta | 3 - .../GameLogic/Network/NetworkCore/Network.cs | 144 -- .../Network/NetworkCore/Network.cs.meta | 3 - .../Network/NetworkCore/NetworkErrorCode.cs | 53 - .../NetworkCore/NetworkErrorCode.cs.meta | 3 - .../Network/NetworkCore/NetworkEvent.cs | 30 - .../Network/NetworkCore/NetworkEvent.cs.meta | 3 - .../NetworkManager.ConnectState.cs | 23 - .../NetworkManager.ConnectState.cs.meta | 3 - .../NetworkManager.HeartBeatState.cs | 39 - .../NetworkManager.HeartBeatState.cs.meta | 3 - .../NetworkManager.NetworkChannelBase.cs | 684 ----- .../NetworkManager.NetworkChannelBase.cs.meta | 3 - .../NetworkManager.ReceiveState.cs | 91 - .../NetworkManager.ReceiveState.cs.meta | 3 - .../NetworkCore/NetworkManager.SendState.cs | 60 - .../NetworkManager.SendState.cs.meta | 3 - .../NetworkManager.TcpNetworkChannel.cs | 281 --- .../NetworkManager.TcpNetworkChannel.cs.meta | 3 - ...anager.TcpWithSyncReceiveNetworkChannel.cs | 257 -- ...r.TcpWithSyncReceiveNetworkChannel.cs.meta | 3 - .../NetworkManager.UdpNetworkChannel.cs | 291 --- .../NetworkManager.UdpNetworkChannel.cs.meta | 3 - .../Network/NetworkCore/NetworkManager.cs | 317 --- .../NetworkCore/NetworkManager.cs.meta | 3 - .../Network/NetworkCore/ServiceType.cs | 28 - .../Network/NetworkCore/ServiceType.cs.meta | 3 - .../HotFix/GameLogic/Network/PacketHeader.cs | 47 - .../GameLogic/Network/PacketHeader.cs.meta | 3 - .../HotFix/GameLogic/Network/ProtoUtil.cs | 30 - .../GameLogic/Network/ProtoUtil.cs.meta | 3 - .../GameLogic/Network/ProtobufUtility.cs | 217 -- .../GameLogic/Network/ProtobufUtility.cs.meta | 3 - .../HotFix/GameLogic/Network/ProtobufUtils.cs | 138 -- .../GameLogic/Network/ProtobufUtils.cs.meta | 3 - 90 files changed, 8982 deletions(-) delete mode 100644 Assets/GameScripts/Editor/Inspector.meta delete mode 100644 Assets/GameScripts/Editor/Inspector/NetworkInspector.cs delete mode 100644 Assets/GameScripts/Editor/Inspector/NetworkInspector.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/ClientConnectWatcher.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/ClientConnectWatcher.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/GameClient.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/GameClient.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/MsgDispatcher.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/MsgDispatcher.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkChannelHelper.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkChannelHelper.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/AddressFamily.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/AddressFamily.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkChannel.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkChannel.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkChannelHelper.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkChannelHelper.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkManager.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkManager.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/IPacketHeader.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/IPacketHeader.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/FakeKcpIO.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/FakeKcpIO.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/IKcpInterface.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/IKcpInterface.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/IKcpSegment.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/IKcpSegment.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/Kcp.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/Kcp.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpCore.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpCore.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpIO.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpIO.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpOutputWriter.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpOutputWriter.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpSegment.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpSegment.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpTrace.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpTrace.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SegManager.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SegManager.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SimpleKcpClient.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SimpleKcpClient.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SimpleKcpServer.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SimpleKcpServer.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/Utility.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/Utility.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/NetworkManager.KcpNetworkChannel.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/NetworkManager.KcpNetworkChannel.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetUtil.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetUtil.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Network.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Network.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkErrorCode.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkErrorCode.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkEvent.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkEvent.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.ConnectState.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.ConnectState.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.HeartBeatState.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.HeartBeatState.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.NetworkChannelBase.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.NetworkChannelBase.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.ReceiveState.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.ReceiveState.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.SendState.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.SendState.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.TcpNetworkChannel.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.TcpNetworkChannel.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.TcpWithSyncReceiveNetworkChannel.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.TcpWithSyncReceiveNetworkChannel.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.UdpNetworkChannel.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.UdpNetworkChannel.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/ServiceType.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/ServiceType.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/PacketHeader.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/PacketHeader.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/ProtoUtil.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/ProtoUtil.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/ProtobufUtility.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/ProtobufUtility.cs.meta delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/ProtobufUtils.cs delete mode 100644 Assets/GameScripts/HotFix/GameLogic/Network/ProtobufUtils.cs.meta diff --git a/Assets/GameScripts/Editor/Inspector.meta b/Assets/GameScripts/Editor/Inspector.meta deleted file mode 100644 index 2e127e32..00000000 --- a/Assets/GameScripts/Editor/Inspector.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 22d1bcdd317c6f64daeb9bf9742495f2 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/GameScripts/Editor/Inspector/NetworkInspector.cs b/Assets/GameScripts/Editor/Inspector/NetworkInspector.cs deleted file mode 100644 index bf680dbf..00000000 --- a/Assets/GameScripts/Editor/Inspector/NetworkInspector.cs +++ /dev/null @@ -1,62 +0,0 @@ -using UnityEditor; -using UnityEngine; - -namespace TEngine.Editor.Inspector -{ - [CustomEditor(typeof(Network))] - internal sealed class NetworkInspector : GameFrameworkInspector - { - public override void OnInspectorGUI() - { - base.OnInspectorGUI(); - - if (!EditorApplication.isPlaying) - { - EditorGUILayout.HelpBox("Available during runtime only.", MessageType.Info); - return; - } - - Network t = (Network)target; - - if (IsPrefabInHierarchy(t.gameObject)) - { - EditorGUILayout.LabelField("Network Channel Count", t.NetworkChannelCount.ToString()); - - INetworkChannel[] networkChannels = t.GetAllNetworkChannels(); - foreach (INetworkChannel networkChannel in networkChannels) - { - DrawNetworkChannel(networkChannel); - } - } - - Repaint(); - } - - private void DrawNetworkChannel(INetworkChannel networkChannel) - { - EditorGUILayout.BeginVertical("box"); - { - EditorGUILayout.LabelField(networkChannel.Name, networkChannel.Connected ? "Connected" : "Disconnected"); - EditorGUILayout.LabelField("Service Type", networkChannel.ServiceType.ToString()); - EditorGUILayout.LabelField("Address Family", networkChannel.AddressFamily.ToString()); - EditorGUILayout.LabelField("Local Address", networkChannel.Connected ? networkChannel.Socket.LocalEndPoint.ToString() : "Unavailable"); - EditorGUILayout.LabelField("Remote Address", networkChannel.Connected ? networkChannel.Socket.RemoteEndPoint.ToString() : "Unavailable"); - EditorGUILayout.LabelField("Send Packet", Utility.Text.Format("{0} / {1}", networkChannel.SendPacketCount, networkChannel.SentPacketCount)); - EditorGUILayout.LabelField("Receive Packet", Utility.Text.Format("{0} / {1}", networkChannel.ReceivePacketCount, networkChannel.ReceivedPacketCount)); - EditorGUILayout.LabelField("Miss Heart Beat Count", networkChannel.MissHeartBeatCount.ToString()); - EditorGUILayout.LabelField("Heart Beat", Utility.Text.Format("{0:F2} / {1:F2}", networkChannel.HeartBeatElapseSeconds, networkChannel.HeartBeatInterval)); - EditorGUI.BeginDisabledGroup(!networkChannel.Connected); - { - if (GUILayout.Button("Disconnect")) - { - networkChannel.Close(); - } - } - EditorGUI.EndDisabledGroup(); - } - EditorGUILayout.EndVertical(); - - EditorGUILayout.Separator(); - } - } -} \ No newline at end of file diff --git a/Assets/GameScripts/Editor/Inspector/NetworkInspector.cs.meta b/Assets/GameScripts/Editor/Inspector/NetworkInspector.cs.meta deleted file mode 100644 index 24e390c1..00000000 --- a/Assets/GameScripts/Editor/Inspector/NetworkInspector.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 3301ba180cdc446bbdf823c860ae7a68 -timeCreated: 1682045195 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network.meta b/Assets/GameScripts/HotFix/GameLogic/Network.meta deleted file mode 100644 index 13955a39..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 145b951be40d41dea06e76bd967a5d15 -timeCreated: 1682045847 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/ClientConnectWatcher.cs b/Assets/GameScripts/HotFix/GameLogic/Network/ClientConnectWatcher.cs deleted file mode 100644 index e62f0ede..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/ClientConnectWatcher.cs +++ /dev/null @@ -1,166 +0,0 @@ -using TEngine; - -namespace GameLogic -{ - public enum ClientConnectWatcherStatus - { - StatusInit, - StatusReconnectAuto, - StatusReconnectConfirm, - StatusWaitExit - } - - public class ClientConnectWatcher - { - private readonly GameClient _client; - private ClientConnectWatcherStatus _status; - private float _statusTime; - private int _reconnectCnt = 0; - private int _disconnectReason = 0; - - private bool _enable = false; - - public bool Enable - { - get => _enable; - set - { - if (_enable != value) - { - _enable = value; - if (_enable) - { - OnEnable(); - } - else - { - OnDisable(); - } - } - } - } - - private ClientConnectWatcherStatus Status - { - get => _status; - set - { - if (_status == value) return; - _status = value; - _statusTime = NowTime; - } - } - - private float NowTime => GameTime.unscaledTime; - - public ClientConnectWatcher(GameClient client) - { - _client = client; - _statusTime = NowTime; - _status = ClientConnectWatcherStatus.StatusInit; - } - - public void Update() - { - if (!_enable) - { - return; - } - - if (_client.IsEntered) - { - return; - } - - switch (_status) - { - case ClientConnectWatcherStatus.StatusInit: - UpdateOnInitStatus(); - break; - case ClientConnectWatcherStatus.StatusReconnectAuto: - UpdateOnReconnectAuto(); - break; - case ClientConnectWatcherStatus.StatusReconnectConfirm: - UpdateOnReconnectConfirm(); - break; - case ClientConnectWatcherStatus.StatusWaitExit: - UpdateOnWaitExit(); - break; - } - } - - public void OnReConnect() - { - if (_status == ClientConnectWatcherStatus.StatusReconnectConfirm) - { - Status = ClientConnectWatcherStatus.StatusReconnectAuto; - } - } - - void UpdateOnInitStatus() - { - int autoReconnectMaxCount = 4; - if (_reconnectCnt <= autoReconnectMaxCount) - { - if (_reconnectCnt == 0) - { - _disconnectReason = _client.LastNetErrCode; - } - - Status = ClientConnectWatcherStatus.StatusReconnectAuto; - _reconnectCnt++; - - //重连 - _client.Reconnect(); - } - else - { - Status = ClientConnectWatcherStatus.StatusReconnectConfirm; - _reconnectCnt++; - // UISys.Mgr.ShowUI(GAME_UI_TYPE.Tip_NetDisconn, UISys.Mgr.GetUIWindowParam().SetParam("errCode", m_disconnectReason)); - } - } - - void UpdateOnReconnectAuto() - { - if (_client.IsEntered) - { - Status = ClientConnectWatcherStatus.StatusInit; - _reconnectCnt = 0; - return; - } - - float nowTime = NowTime; - var timeoutTime = 10f; - - if (_statusTime + timeoutTime < nowTime) - { - Log.Error("UpdateOnReconnectAuto timeout: {0}", timeoutTime); - - //切换到默认的,下一帧继续判断是否需要自动还是手动 - Status = ClientConnectWatcherStatus.StatusInit; - } - } - - void UpdateOnReconnectConfirm() - { - - } - - void UpdateOnWaitExit() - { - } - - private void OnDisable() - { - Status = ClientConnectWatcherStatus.StatusInit; - _reconnectCnt = 0; - } - - private void OnEnable() - { - Status = ClientConnectWatcherStatus.StatusInit; - _reconnectCnt = 0; - } - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/ClientConnectWatcher.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/ClientConnectWatcher.cs.meta deleted file mode 100644 index ce6c15a3..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/ClientConnectWatcher.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 3e4e637f3da340dd9512150c3e2ff087 -timeCreated: 1684334948 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/GameClient.cs b/Assets/GameScripts/HotFix/GameLogic/Network/GameClient.cs deleted file mode 100644 index 2f6e36c9..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/GameClient.cs +++ /dev/null @@ -1,428 +0,0 @@ -using System.Net.Sockets; -using GameBase; -using GameProto; -using TEngine; -using CSPkg = GameProto.CSPkg; - -namespace GameLogic -{ - public enum GameClientStatus - { - StatusInit, //初始化 - StatusReconnect, //重新连接 - StatusClose, //断开连接 - StatusLogin, //登录中 - StatusEnter, //AccountLogin成功,进入服务器了 - } - - public enum CsMsgResult - { - NoError = 0, - NetworkError = 1, - InternalError = 2, - MsgTimeOut = 3, - PingTimeOut = 4, - } - - //定义消息回报的回调接口 - public delegate void CsMsgDelegate(CsMsgResult result, CSPkg msg); - - /// - /// 统计网络协议的接口 - /// - public delegate void CsMsgStatDelegate(int cmdID, int pkgSize); - - public class GameClient : Singleton - { - private readonly INetworkChannel _channel; - - private GameClientStatus _status = GameClientStatus.StatusInit; - - private readonly MsgDispatcher _dispatcher; - - private readonly ClientConnectWatcher _connectWatcher; - - private float _lastLogDisconnectErrTime = 0f; - - private int _lastNetErrCode = 0; - - public int LastNetErrCode => _lastNetErrCode; - - public GameClientStatus Status - { - get => _status; - set => _status = value; - } - - public bool IsEntered => _status == GameClientStatus.StatusEnter; - - /// - /// 连续心跳超时 - /// - private int _heatBeatTimeoutNum = 0; - - private int _ping = -1; - - private float NowTime => GameTime.unscaledTime; - - private string _lastHost = null; - private int _lastPort = 0; - - public GameClient() - { - _connectWatcher = new ClientConnectWatcher(this); - _dispatcher = new MsgDispatcher(); - _dispatcher.SetTimeout(5f); - GameEvent.AddEventListener(NetworkEvent.NetworkConnectedEvent,OnNetworkConnected); - GameEvent.AddEventListener(NetworkEvent.NetworkClosedEvent,OnNetworkClosed); - GameEvent.AddEventListener(NetworkEvent.NetworkErrorEvent,OnNetworkError); - GameEvent.AddEventListener(NetworkEvent.NetworkCustomErrorEvent,OnNetworkCustomError); - _channel = Network.Instance.CreateNetworkChannel("GameClient", ServiceType.Tcp, new NetworkChannelHelper()); - } - - private void OnNetworkConnected(INetworkChannel channel, object userdata) - { - bool isReconnect = (_status == GameClientStatus.StatusReconnect); - //准备登录 - Status = GameClientStatus.StatusLogin; - - OnServerConnected(isReconnect); - } - - private void OnNetworkClosed(INetworkChannel channel) - { - - } - - private void OnNetworkError(INetworkChannel channel, NetworkErrorCode networkErrorCode, SocketError socketError, string errorMessage) - { - - } - - private void OnNetworkCustomError(INetworkChannel channel, object userData) - { - - } - - public void Connect(string host, int port, bool reconnect = false) - { - ResetParam(); - if (!reconnect) - { - SetWatchReconnect(false); - } - - if (reconnect) - { - // GameEvent.Get().ShowWaitUITip(WaitUISeq.LOGINWORLD_SEQID, G.R(TextDefine.ID_TIPS_RECONNECTING)); - } - else - { - // GameEvent.Get().ShowWaitUI(WaitUISeq.LOGINWORLD_SEQID); - } - - _lastHost = host; - _lastPort = port; - - Status = reconnect ? GameClientStatus.StatusReconnect : GameClientStatus.StatusInit; - - _channel.Connect(host, port); - } - - public void Reconnect() - { - if (string.IsNullOrEmpty(_lastHost) || _lastPort <= 0) - { - // GameModule.UI.ShowTipMsg("Invalid reconnect param"); - return; - } - - _connectWatcher.OnReConnect(); - Connect(_lastHost, _lastPort, true); - } - - - public void Shutdown() - { - _channel.Close(); - _status = GameClientStatus.StatusInit; - } - - public void OnServerConnected(bool isReconnect) - { - - } - - public bool SendCsMsg(CSPkg reqPkg) - { - if (!IsStatusCanSendMsg(reqPkg.Head.MsgId)) - { - return false; - } - - return DoSendData(reqPkg); - } - - public bool IsStatusCanSendMsg(uint msgId) - { - bool canSend = false; - if (_status == GameClientStatus.StatusLogin) - { - canSend = (msgId == (uint)CSMsgID.CsCmdActLoginReq); - } - - if (_status == GameClientStatus.StatusEnter) - { - canSend = true; - } - - if (!canSend) - { - float nowTime = NowTime; - if (_lastLogDisconnectErrTime + 5 < nowTime) - { - Log.Error("GameClient not connected, send msg failed, msgId[{0}]", msgId); - _lastLogDisconnectErrTime = nowTime; - } - - //UISys.Mgr.ShowTipMsg(TextDefine.ID_ERR_NETWORKD_DISCONNECT); - } - - return canSend; - } - - public bool SendCsMsg(CSPkg reqPkg, uint resCmd, CsMsgDelegate resHandler = null, bool needShowWaitUI = true) - { - if (!IsStatusCanSendMsg(reqPkg.Head.MsgId)) - { - return false; - } - - var ret = DoSendData(reqPkg); - if (!ret) - { - if (resHandler != null) - { - resHandler(CsMsgResult.InternalError, null); - } - - _dispatcher.NotifyCmdError(resCmd, CsMsgResult.InternalError); - } - else - { - //注册消息 - if (resHandler != null) - { - _dispatcher.RegSeqHandle(reqPkg.Head.Echo, resCmd, resHandler); - if (reqPkg.Head.Echo > 0 && IsWaitingCmd(resCmd) && needShowWaitUI) - { - // TODO - // GameEvent.Get().ShowWaitUI(reqPkg.Head.Echo); - } - } - } - - return ret; - } - - private bool DoSendData(CSPkg reqPkg) - { - if (!IsIgnoreLog(reqPkg.Head.MsgId)) - { - Log.Debug("[c-s] CmdId[{0}]\n{1}", reqPkg.Head.MsgId, reqPkg.Body.ToString()); - } - var sendRet = _channel.Send(reqPkg); - return sendRet; - } - - private bool IsIgnoreLog(uint msgId) - { - bool ignoreLog = false; - switch (msgId) - { - case (uint)CSMsgID.CsCmdHeatbeatReq: - case (uint)CSMsgID.CsCmdHeatbeatRes: - ignoreLog = true; - break; - } - return ignoreLog; - } - - public static bool IsWaitingCmd(uint msgId) - { - //心跳包不需要读条等待 - if (msgId == (uint)CSMsgID.CsCmdHeatbeatRes) - { - return false; - } - - return true; - } - - private void ResetParam() - { - _lastLogDisconnectErrTime = 0f; - _heatBeatTimeoutNum = 0; - _lastHbTime = 0f; - _ping = -1; - _lastNetErrCode = 0; - } - - public void OnUpdate() - { - _dispatcher.Update(); - TickHeartBeat(); - CheckHeatBeatTimeout(); - _connectWatcher.Update(); - } - - /// - /// 注册静态消息 - /// - /// - /// - public void RegCmdHandle(int iCmdID, CsMsgDelegate msgDelegate) - { - _dispatcher.RegCmdHandle((uint)iCmdID, msgDelegate); - } - - /// - /// 移除消息处理函数 - /// - /// - /// - public void RmvCmdHandle(int cmdId, CsMsgDelegate msgDelegate) - { - _dispatcher.RmvCmdHandle((uint)cmdId, msgDelegate); - } - - /// - /// 设置加密密钥 - /// - /// - public void SetEncryptKey(string key) - { - } - - /// - /// 设置是否需要监控网络重连。 - /// 登录成功后,开启监控,可以自动重连或者提示玩家重连。 - /// - /// - public void SetWatchReconnect(bool needWatch) - { - _connectWatcher.Enable = needWatch; - } - - public bool IsNetworkOkAndLogin() - { - return _status == GameClientStatus.StatusEnter; - } - - #region 心跳处理 - - /// - /// 最近一次心跳的时间 - /// - private float _lastHbTime = 0f; - - /// - /// 心跳间隔 - /// - private readonly float _heartBeatDurTime = 5; - - /// - /// 心跳超时的最大次数 - /// - private const int HeatBeatTimeoutMaxCount = 2; - - private bool CheckHeatBeatTimeout() - { - if (_heatBeatTimeoutNum >= HeatBeatTimeoutMaxCount) - { - //断开连接 - Shutdown(); - - //准备重连 - _heatBeatTimeoutNum = 0; - Status = GameClientStatus.StatusClose; - Log.Error("heat beat detect timeout"); - return false; - } - - return true; - } - - void TickHeartBeat() - { - if (Status != GameClientStatus.StatusEnter) - { - return; - } - - var nowTime = NowTime; - if (_lastHbTime + _heartBeatDurTime < nowTime) - { - _lastHbTime = nowTime; - - CSPkg heatPkg = ProtobufUtility.BuildCsMsg((int)CSMsgID.CsCmdHeatbeatReq); - heatPkg.Body.HeatBeatReq = new CSHeatBeatReq { HeatEchoTime = _lastHbTime }; - SendCsMsg(heatPkg, (int)CSMsgID.CsCmdHeatbeatRes, HandleHeatBeatRes); - } - } - - void HandleHeatBeatRes(CsMsgResult result, CSPkg msg) - { - if (result != CsMsgResult.NoError) - { - //如果是超时了,则标记最近收到包的次数 - if (result == CsMsgResult.MsgTimeOut) - { - _heatBeatTimeoutNum++; - Log.Warning("heat beat timeout: {0}", _heatBeatTimeoutNum); - } - } - else - { - var resBody = msg.Body.HeatBeatRes; - float diffTime = NowTime - resBody.HeatEchoTime; - _ping = (int)(diffTime * 1000); - _heatBeatTimeoutNum = 0; - } - } - - #endregion - - #region Ping值 - - /// - /// ping值 - /// - public int Ping - { - get - { - if (IsPingValid()) - { - return _ping / 4; - } - else - { - return 0; - } - } - } - - public bool IsPingValid() - { - if (IsNetworkOkAndLogin()) - { - return _ping >= 0; - } - - return false; - } - - #endregion - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/GameClient.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/GameClient.cs.meta deleted file mode 100644 index b77d9457..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/GameClient.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 8c5441725c9f4d98a7790dc76a6a0c48 -timeCreated: 1684331687 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/MsgDispatcher.cs b/Assets/GameScripts/HotFix/GameLogic/Network/MsgDispatcher.cs deleted file mode 100644 index 3cb909c5..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/MsgDispatcher.cs +++ /dev/null @@ -1,265 +0,0 @@ -using System; -using System.Collections.Generic; -using GameProto; -using TEngine; -using CSPkg = GameProto.CSPkg; - -namespace GameLogic -{ - internal class MsgHandleDataToRmv - { - public uint MsgId; - public CsMsgDelegate Handle; - }; - - class MsgDispatcher - { - const int CheckTimeoutPerframe = 10; - const int MaxMsgHandle = 256; - - private readonly CsMsgDelegate[] _aMsgHandles = new CsMsgDelegate[MaxMsgHandle]; - private readonly float[] _fMsgRegTime = new float[MaxMsgHandle]; - private readonly UInt32[] _adwMsgRegSeq = new UInt32[MaxMsgHandle]; //因为_aiMsgRegResCmdID存储的是hash,不能保证一定seqid一样,所以这儿存储下,用来校验 - private readonly uint[] _aiMsgRegResCmdID = new uint[MaxMsgHandle]; - - UInt32 _dwLastCheckIndex = 0; - - private readonly Dictionary> _mapCmdHandle = new Dictionary>(); - private readonly List _listStatHandle = new List(); - - //防止在处理消息的时候又删除了消息映射,所以这儿加了个队列来做个保护 - private readonly List _rmvList = new List(); - private bool _isInHandleLoop = false; - private float _timeout = 5; - - // 清理所有的网络消息 - public void CleanAllNetMsg() - { - _mapCmdHandle.Clear(); - } - - public void SetTimeout(float timeout) - { - _timeout = timeout; - } - - public void RegSeqHandle(UInt32 dwMsgSeqID, uint iResCmdID, CsMsgDelegate msgDelegate) - { - UInt32 hashIndex = dwMsgSeqID % MaxMsgHandle; - if (_aMsgHandles[hashIndex] != null) - { - OnCallSeqHandle(_adwMsgRegSeq[hashIndex], _aiMsgRegResCmdID[hashIndex]); - NotifyTimeout(_aMsgHandles[hashIndex]); - RmvReg((int)hashIndex); - } - - _aMsgHandles[hashIndex] = msgDelegate; - _fMsgRegTime[hashIndex] = NowTime; - _adwMsgRegSeq[hashIndex] = dwMsgSeqID; - _aiMsgRegResCmdID[hashIndex] = iResCmdID; - } - - public void RegCmdHandle(uint iCmdID, CsMsgDelegate msgDelegate) - { - if (!_mapCmdHandle.TryGetValue(iCmdID, out var listHandle)) - { - listHandle = new List(); - _mapCmdHandle[iCmdID] = listHandle; - } - - if (listHandle != null) - { - if (listHandle.Contains(msgDelegate)) - { - Log.Error("-------------repeat RegCmdHandle:{0}-----------", iCmdID); - } - - listHandle.Add(msgDelegate); - } - } - - /// - /// 注册统计处理接口 - /// - /// - public void RegCmdStatHandle(CsMsgStatDelegate handler) - { - _listStatHandle.Add(handler); - } - - public void DispatchCmdStat(int cmdID, int pkgSize) - { - foreach (CsMsgStatDelegate handle in _listStatHandle) - { - handle(cmdID, pkgSize); - } - } - - public void RmvCmdHandle(uint iCmdID, CsMsgDelegate msgDelegate) - { - if (_isInHandleLoop) - { - MsgHandleDataToRmv toRmvData = new MsgHandleDataToRmv(); - toRmvData.MsgId = iCmdID; - toRmvData.Handle = msgDelegate; - - _rmvList.Add(toRmvData); - return; - } - - if (!_mapCmdHandle.TryGetValue(iCmdID, out var listHandle)) - { - return; - } - - if (listHandle != null) - { - listHandle.Remove(msgDelegate); - } - } - - public void NotifyCmdError(uint iCmdID, CsMsgResult result) - { - NotifyCmdHandle(iCmdID, result, default(CSPkg)); - } - - protected bool NotifyCmdHandle(uint cmdID, CsMsgResult result, CSPkg pkg) - { - bool ret = false; - if (_mapCmdHandle.TryGetValue(cmdID, out var listHandle)) - { - _isInHandleLoop = true; - - var rmvList = _rmvList; - rmvList.Clear(); - foreach (CsMsgDelegate handle in listHandle) - { - ret = true; - - TProfiler.BeginSample("handle"); - handle(result, pkg); - TProfiler.EndSample(); - } - - _isInHandleLoop = false; - - //再统一删除掉 - int rmvCnt = rmvList.Count; - for (int i = 0; i < rmvCnt; i++) - { - var rmvItem = rmvList[i]; - Log.Error("-------------remove cmd handle on loop:{0}-----------", rmvItem.MsgId); - RmvCmdHandle(rmvItem.MsgId, rmvItem.Handle); - } - } - - return ret; - } - - protected void OnCallSeqHandle(UInt32 echoSeq, uint resCmdID) - { - if (echoSeq > 0) - { - // TODO - // GameEvent.Get().FinWaitUI(echoSeq); - } - } - - protected void NotifyTimeout(CsMsgDelegate msgHandler) - { - msgHandler(CsMsgResult.MsgTimeOut, default(CSPkg)); - } - - public void NotifySeqError(UInt32 dwSeqID, CsMsgResult result) - { - UInt32 hashIndex = dwSeqID % MaxMsgHandle; - - //先判断是否有注册的指定消息 - if (_aMsgHandles[hashIndex] != null && - _adwMsgRegSeq[hashIndex] == dwSeqID) - { - OnCallSeqHandle(dwSeqID, _aiMsgRegResCmdID[hashIndex]); - _aMsgHandles[hashIndex](result, null); - - RmvReg((int)hashIndex); - } - } - - public bool IsCmdFilterNoLog(int cmdID) - { - switch (cmdID) - { - case (int)CSMsgID.CsCmdHeatbeatRes: - return true; - default: - break; - } - return false; - } - - public void NotifyMsg(CSPkg msg) - { - UInt32 dwSeq = msg.Head.Echo; - UInt32 hashIndex = dwSeq % MaxMsgHandle; - //判断是否有固定的消息处理流程 - bool bHaveHandle = NotifyCmdHandle(msg.Head.MsgId, CsMsgResult.NoError, msg); - - //再判断是否有注册的指定消息 - if (_aMsgHandles[hashIndex] != null && - _adwMsgRegSeq[hashIndex] == dwSeq && - _aiMsgRegResCmdID[hashIndex] == (int)msg.Head.MsgId) - { - OnCallSeqHandle(_adwMsgRegSeq[hashIndex], _aiMsgRegResCmdID[hashIndex]); - _aMsgHandles[hashIndex](CsMsgResult.NoError, msg); - RmvReg((int)hashIndex); - bHaveHandle = true; - } - - if (!bHaveHandle) - { - Log.Debug("there is no handle for Msg[{0}]", msg.Head.MsgId); - } - } - - private float NowTime => GameTime.unscaledTime; - - public void Update() - { - CheckTimeOut(); - } - - /// - /// 定时检查是否请求超时。 - /// - private void CheckTimeOut() - { - float timeout = _timeout; - float nowTime = NowTime; - for (int i = 0; i < CheckTimeoutPerframe; i++) - { - _dwLastCheckIndex = (_dwLastCheckIndex + 1) % MaxMsgHandle; - if (_aMsgHandles[_dwLastCheckIndex] != null) - { - if (_fMsgRegTime[_dwLastCheckIndex] + timeout < nowTime) - { - Log.Error("msg timeout, resCmdID[{0}], reqSeq[{1}]", _aiMsgRegResCmdID[_dwLastCheckIndex], - _adwMsgRegSeq[_dwLastCheckIndex]); - - OnCallSeqHandle(_adwMsgRegSeq[_dwLastCheckIndex], _aiMsgRegResCmdID[_dwLastCheckIndex]); - NotifyTimeout(_aMsgHandles[_dwLastCheckIndex]); - - RmvReg((int)_dwLastCheckIndex); - } - } - } - } - - public void RmvReg(int index) - { - _aMsgHandles[index] = null; - _adwMsgRegSeq[index] = 0; - _aiMsgRegResCmdID[index] = 0; - _fMsgRegTime[index] = 0; - } - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/MsgDispatcher.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/MsgDispatcher.cs.meta deleted file mode 100644 index c9c8c3d4..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/MsgDispatcher.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 7d667fb84fed4c5f93a06c464585512f -timeCreated: 1684333223 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkChannelHelper.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkChannelHelper.cs deleted file mode 100644 index f3c74efc..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkChannelHelper.cs +++ /dev/null @@ -1,226 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net.Sockets; -using GameProto; -using Google.Protobuf; -using TEngine; - -namespace GameLogic -{ - public class NetworkChannelHelper : INetworkChannelHelper, IMemory - { - private readonly Dictionary _serverToClientPacketTypes = new Dictionary(); - private readonly MemoryStream _cachedStream = new MemoryStream(1024 * 8); - private INetworkChannel _networkChannel = null; - - /// - /// 获取消息包头长度。 - /// 4。 - /// - public int PacketHeaderLength => sizeof(int); - - /// - /// 初始化网络频道辅助器。 - /// - /// 网络频道。 - public void Initialize(INetworkChannel networkChannel) - { - _networkChannel = networkChannel; - - GameEvent.AddEventListener(NetworkEvent.NetworkConnectedEvent, OnNetworkConnected); - GameEvent.AddEventListener(NetworkEvent.NetworkClosedEvent, OnNetworkClosed); - GameEvent.AddEventListener(NetworkEvent.NetworkMissHeartBeatEvent, OnNetworkMissHeartBeat); - GameEvent.AddEventListener(NetworkEvent.NetworkErrorEvent, OnNetworkError); - GameEvent.AddEventListener(NetworkEvent.NetworkCustomErrorEvent, OnNetworkCustomError); - } - - /// - /// 关闭并清理网络频道辅助器。 - /// - public void Shutdown() - { - GameEvent.RemoveEventListener(NetworkEvent.NetworkConnectedEvent, OnNetworkConnected); - GameEvent.RemoveEventListener(NetworkEvent.NetworkClosedEvent, OnNetworkClosed); - GameEvent.RemoveEventListener(NetworkEvent.NetworkMissHeartBeatEvent, OnNetworkMissHeartBeat); - GameEvent.RemoveEventListener(NetworkEvent.NetworkErrorEvent, OnNetworkError); - GameEvent.RemoveEventListener(NetworkEvent.NetworkCustomErrorEvent, OnNetworkCustomError); - - _networkChannel = null; - } - - /// - /// 准备进行连接。 - /// - public void PrepareForConnecting() - { - _networkChannel.Socket.ReceiveBufferSize = 1024 * 64; - _networkChannel.Socket.SendBufferSize = 1024 * 64; - } - - public CSPkg HeartBeatPack = new CSPkg { Head = new CSPkgHead(), Body = new CSPkgBody() }; - - /// - /// 发送心跳消息包。 - /// - /// 是否发送心跳消息包成功。 - public bool SendHeartBeat() - { - HeartBeatPack.Head.MsgId = (uint)CSMsgID.CsCmdHeatbeatReq; - _networkChannel.Send(HeartBeatPack); - return true; - } - - /// - /// 序列化消息包。 - /// - /// 消息包类型。 - /// 要序列化的消息包。 - /// 要序列化的目标流。 - /// 是否序列化成功。 - public bool Serialize(CSPkg packet, Stream destination) - { - if (packet == null) - { - Log.Warning("Packet is invalid."); - return false; - } - - _cachedStream.SetLength(_cachedStream.Capacity); // 此行防止 Array.Copy 的数据无法写入 - _cachedStream.Position = 0L; - global::ProtobufUtility.ToStreamWithHead(packet,_cachedStream); - _cachedStream.WriteTo(destination); - return true; - } - - /// - /// 反序列化消息包头。 - /// - /// 要反序列化的来源流。 - /// 用户自定义错误数据。 - /// 反序列化后的消息包头。 - public IPacketHeader DeserializePacketHeader(Stream source, out object customErrorData) - { - // 注意:此函数并不在主线程调用! - customErrorData = null; - PacketHeader packetHeader = MemoryPool.Acquire(); - packetHeader.PacketLength = ((MemoryStream)source).GetBuffer()[0]; - return packetHeader; - } - - /// - /// 反序列化消息包。 - /// - /// 消息包头。 - /// 要反序列化的来源流。 - /// 用户自定义错误数据。 - /// 反序列化后的消息包。 - public CSPkg DeserializePacket(IPacketHeader packetHeader, Stream source, out object customErrorData) - { - // 注意:此函数并不在主线程调用! - customErrorData = null; - - PacketHeader scPacketHeader = packetHeader as PacketHeader; - if (scPacketHeader == null) - { - Log.Warning("Packet header is invalid."); - return null; - } - - CSPkg csPkg = null; - if (scPacketHeader.IsValid) - { - try - { - csPkg = global::ProtobufUtility.Deserialize(((MemoryStream)source).GetBuffer(),0,scPacketHeader.PacketLength); - Log.Debug("[s-c] CmdId[{0}]\n{1}", csPkg.Head.MsgId, csPkg.ToString()); - } - catch (Exception e) - { - Log.Warning(e); - } - } - else - { - Log.Warning("Packet header is invalid."); - } - - MemoryPool.Release(scPacketHeader); - return csPkg; - } - - private Type GetServerToClientPacketType(int id) - { - if (_serverToClientPacketTypes.TryGetValue(id, out var type)) - { - return type; - } - - return null; - } - - private void OnNetworkConnected(INetworkChannel channel, object userdata) - { - if (channel != _networkChannel) - { - return; - } - - Log.Info("Network channel '{0}' connected, local address '{1}', remote address '{2}'.", - channel.Name, channel.Socket.LocalEndPoint.ToString(), - channel.Socket.RemoteEndPoint.ToString()); - } - - private void OnNetworkClosed(INetworkChannel channel) - { - if (channel != _networkChannel) - { - return; - } - - Log.Info("Network channel '{0}' closed.", channel.Name); - } - - private void OnNetworkMissHeartBeat(INetworkChannel channel, int missCount) - { - if (channel != _networkChannel) - { - return; - } - - Log.Fatal("Network channel '{0}' miss heart beat '{1}' times.", channel.Name, missCount.ToString()); - - if (missCount < 2) - { - return; - } - - channel.Close(); - } - - private void OnNetworkError(INetworkChannel channel, NetworkErrorCode networkErrorCode, SocketError socketError, string errorMessage) - { - if (channel != _networkChannel) - { - return; - } - - Log.Fatal("Network channel '{0}' error, error code is '{1}', error message is '{2}'.", channel.Name, networkErrorCode.ToString(), errorMessage); - - channel.Close(); - } - - private void OnNetworkCustomError(INetworkChannel channel, object userData) - { - if (channel != _networkChannel) - { - return; - } - } - - public void Clear() - { - } - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkChannelHelper.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkChannelHelper.cs.meta deleted file mode 100644 index e3d8f91d..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkChannelHelper.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: bf86ce2ddfb5429abecfb06257c86acd -timeCreated: 1682045961 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore.meta deleted file mode 100644 index 854c49e1..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: e77590d750cf480baae2468038654bc0 -timeCreated: 1681991042 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/AddressFamily.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/AddressFamily.cs deleted file mode 100644 index abc8568c..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/AddressFamily.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace TEngine -{ - /// - /// 网络地址类型。 - /// - public enum AddressFamily : byte - { - /// - /// 未知。 - /// - Unknown = 0, - - /// - /// IP 版本 4。 - /// - IPv4, - - /// - /// IP 版本 6。 - /// - IPv6 - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/AddressFamily.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/AddressFamily.cs.meta deleted file mode 100644 index fb25e3eb..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/AddressFamily.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: dd8e805430d24bdb8c2679b59ba7c2d6 -timeCreated: 1681993653 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface.meta deleted file mode 100644 index 31761b46..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 9aefe7f3e0fd485091a20579b29872a7 -timeCreated: 1681994393 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkChannel.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkChannel.cs deleted file mode 100644 index cf136411..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkChannel.cs +++ /dev/null @@ -1,180 +0,0 @@ -using System; -using System.Net; -using System.Net.Sockets; -using GameProto; -using Google.Protobuf; - -namespace TEngine -{ - /// - /// 网络频道接口。 - /// - public interface INetworkChannel - { - /// - /// 获取网络频道名称。 - /// - string Name - { - get; - } - - /// - /// 获取网络频道所使用的 Socket。 - /// - Socket Socket - { - get; - } - - /// - /// 获取是否已连接。 - /// - bool Connected - { - get; - } - - /// - /// 获取网络服务类型。 - /// - ServiceType ServiceType - { - get; - } - - /// - /// 获取网络地址类型。 - /// - AddressFamily AddressFamily - { - get; - } - - /// - /// 获取要发送的消息包数量。 - /// - int SendPacketCount - { - get; - } - - /// - /// 获取累计发送的消息包数量。 - /// - int SentPacketCount - { - get; - } - - /// - /// 获取已接收未处理的消息包数量。 - /// - int ReceivePacketCount - { - get; - } - - /// - /// 获取累计已接收的消息包数量。 - /// - int ReceivedPacketCount - { - get; - } - - /// - /// 获取或设置当收到消息包时是否重置心跳流逝时间。 - /// - bool ResetHeartBeatElapseSecondsWhenReceivePacket - { - get; - set; - } - - /// - /// 获取丢失心跳的次数。 - /// - int MissHeartBeatCount - { - get; - } - - /// - /// 获取或设置心跳间隔时长,以秒为单位。 - /// - float HeartBeatInterval - { - get; - set; - } - - /// - /// 获取心跳等待时长,以秒为单位。 - /// - float HeartBeatElapseSeconds - { - get; - } - - /// - /// 注册网络消息包处理函数。 - /// - /// 网络消息包id。 - /// 要注册的网络消息包处理函数。 - /// 是否检测重复。 - void RegisterMsgHandler(int msgId, CsMsgDelegate msgDelegate, bool checkRepeat = false); - - /// - /// 移除网络消息包处理函数。 - /// - /// 网络消息包id。 - /// 要注册的网络消息包处理函数。 - void RemoveMsgHandler(int msgId, CsMsgDelegate msgDelegate); - - /// - /// 连接到远程主机。 - /// - /// 远程主机的 IP 地址。 - /// 远程主机的端口号。 - void Connect(string ipAddress, int port); - - /// - /// 连接到远程主机。 - /// - /// 远程主机的 IP 地址。 - /// 远程主机的端口号。 - void Connect(IPAddress ipAddress, int port); - - /// - /// 连接到远程主机。 - /// - /// 远程主机的 IP 地址。 - /// 远程主机的端口号。 - /// 用户自定义数据。 - void Connect(IPAddress ipAddress, int port, object userData); - - /// - /// 关闭网络频道。 - /// - void Close(); - - /// - /// 向远程主机发送消息包。 - /// - /// 消息包类型。 - /// 要发送的消息包。 - /// 消息包是否发送成功。 - bool Send(CSPkg packet); - - /// - /// 向远程主机发送消息包并注册消息回调。 - /// - /// 消息包类型。 - /// 要发送的消息包。 - /// 要注册的回调。 - /// 是否需要等待UI。 - /// 消息包是否发送成功。 - bool Send(CSPkg packet, CsMsgDelegate resHandler, bool needShowWaitUI = false); - } -} diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkChannel.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkChannel.cs.meta deleted file mode 100644 index 24e3bb66..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkChannel.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 09b554ed41c546a1bc40e5be392f836a -timeCreated: 1681993830 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkChannelHelper.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkChannelHelper.cs deleted file mode 100644 index ce850051..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkChannelHelper.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System.IO; -using GameProto; - -namespace TEngine -{ - /// - /// 网络频道辅助器接口。 - /// - public interface INetworkChannelHelper - { - /// - /// 获取消息包头长度。 - /// - int PacketHeaderLength - { - get; - } - - /// - /// 初始化网络频道辅助器。 - /// - /// 网络频道。 - void Initialize(INetworkChannel networkChannel); - - /// - /// 关闭并清理网络频道辅助器。 - /// - void Shutdown(); - - /// - /// 准备进行连接。 - /// - void PrepareForConnecting(); - - /// - /// 发送心跳消息包。 - /// - /// 是否发送心跳消息包成功。 - bool SendHeartBeat(); - - /// - /// 序列化消息包。 - /// - /// 消息包类型。 - /// 要序列化的消息包。 - /// 要序列化的目标流。 - /// 是否序列化成功。 - bool Serialize(CSPkg packet, Stream destination); - - /// - /// 反序列化消息包头。 - /// - /// 要反序列化的来源流。 - /// 用户自定义错误数据。 - /// 反序列化后的消息包头。 - IPacketHeader DeserializePacketHeader(Stream source, out object customErrorData); - - /// - /// 反序列化消息包。 - /// - /// 消息包头。 - /// 要反序列化的来源流。 - /// 用户自定义错误数据。 - /// 反序列化后的消息包。 - CSPkg DeserializePacket(IPacketHeader packetHeader, Stream source, out object customErrorData); - } -} diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkChannelHelper.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkChannelHelper.cs.meta deleted file mode 100644 index d1dc4b97..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkChannelHelper.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 1f847791db5a4e6cbbc39dd56a6888d9 -timeCreated: 1681993713 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkManager.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkManager.cs deleted file mode 100644 index 131a1409..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkManager.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net.Sockets; - -namespace TEngine -{ - /// - /// 网络管理器接口。 - /// - public interface INetworkManager - { - /// - /// 获取网络频道数量。 - /// - int NetworkChannelCount { get; } - - /// - /// 网络连接成功事件。 - /// - event Action NetworkConnected; - - /// - /// 网络连接关闭事件。 - /// - event Action NetworkClosed; - - /// - /// 网络心跳包丢失事件。 - /// - event Action NetworkMissHeartBeat; - - /// - /// 网络错误事件。 - /// - event Action NetworkError; - - /// - /// 用户自定义网络错误事件。 - /// - event Action NetworkCustomError; - - /// - /// 检查是否存在网络频道。 - /// - /// 网络频道名称。 - /// 是否存在网络频道。 - bool HasNetworkChannel(string name); - - /// - /// 获取网络频道。 - /// - /// 网络频道名称。 - /// 要获取的网络频道。 - INetworkChannel GetNetworkChannel(string name); - - /// - /// 获取所有网络频道。 - /// - /// 所有网络频道。 - INetworkChannel[] GetAllNetworkChannels(); - - /// - /// 获取所有网络频道。 - /// - /// 所有网络频道。 - void GetAllNetworkChannels(List results); - - /// - /// 创建网络频道。 - /// - /// 网络频道名称。 - /// 网络服务类型。 - /// 网络频道辅助器。 - /// 要创建的网络频道。 - INetworkChannel CreateNetworkChannel(string name, ServiceType serviceType, INetworkChannelHelper networkChannelHelper); - - /// - /// 销毁网络频道。 - /// - /// 网络频道名称。 - /// 是否销毁网络频道成功。 - bool DestroyNetworkChannel(string name); - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkManager.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkManager.cs.meta deleted file mode 100644 index 50ce8e95..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/INetworkManager.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 7de8458fc50e4cd3b49ef73d35ad9763 -timeCreated: 1681993806 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/IPacketHeader.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/IPacketHeader.cs deleted file mode 100644 index 9fad5e0b..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/IPacketHeader.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace TEngine -{ - /// - /// 网络消息包头接口。 - /// - public interface IPacketHeader - { - /// - /// 获取网络消息包长度。 - /// - int PacketLength - { - get; - } - } -} diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/IPacketHeader.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/IPacketHeader.cs.meta deleted file mode 100644 index ba80f456..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Interface/IPacketHeader.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 7659e4a617d84126b0a548077fb4fdcc -timeCreated: 1681994226 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp.meta deleted file mode 100644 index 10c01280..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 6d988d26345f402f9177488d8921184f -timeCreated: 1682092063 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core.meta deleted file mode 100644 index b91893dc..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 6dff8f4f5dd94df49bf6d616fb11cc9c -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/FakeKcpIO.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/FakeKcpIO.cs deleted file mode 100644 index 200b30e3..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/FakeKcpIO.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System.Buffers; -using Cysharp.Threading.Tasks; - -namespace System.Net.Sockets.Kcp -{ - /// - /// 用于调试的KCP IO 类,没有Kcp功能 - /// - public class FakeKcpIO : IKcpIO - { - QueuePipe recv = new QueuePipe(); - public int Input(ReadOnlySpan span) - { - byte[] buffer = new byte[span.Length]; - span.CopyTo(buffer); - recv.Write(buffer); - return 0; - } - - public int Input(ReadOnlySequence span) - { - byte[] buffer = new byte[span.Length]; - span.CopyTo(buffer); - return Input(buffer); - } - - public async UniTask RecvAsync(IBufferWriter writer, object options = null) - { - var buffer = await recv.ReadAsync().ConfigureAwait(false); - var target = writer.GetMemory(buffer.Length); - buffer.AsSpan().CopyTo(target.Span); - writer.Advance(buffer.Length); - } - - public async UniTask RecvAsync(ArraySegment buffer, object options = null) - { - var temp = await recv.ReadAsync().ConfigureAwait(false); - temp.AsSpan().CopyTo(buffer); - return temp.Length; - } - - QueuePipe send = new QueuePipe(); - public int Send(ReadOnlySpan span, object options = null) - { - byte[] buffer = new byte[span.Length]; - span.CopyTo(buffer); - send.Write(buffer); - return 0; - } - - public int Send(ReadOnlySequence span, object options = null) - { - byte[] buffer = new byte[span.Length]; - span.CopyTo(buffer); - return Send(buffer); - } - - public async UniTask OutputAsync(IBufferWriter writer, object options = null) - { - var buffer = await send.ReadAsync().ConfigureAwait(false); - Write(writer, buffer); - } - - private static void Write(IBufferWriter writer, byte[] buffer) - { - var span = writer.GetSpan(buffer.Length); - buffer.AsSpan().CopyTo(span); - writer.Advance(buffer.Length); - } - } -} diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/FakeKcpIO.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/FakeKcpIO.cs.meta deleted file mode 100644 index 3f00b35d..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/FakeKcpIO.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e3c2f9de3c34ffc409549b86ac3fc530 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/IKcpInterface.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/IKcpInterface.cs deleted file mode 100644 index 72bfb079..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/IKcpInterface.cs +++ /dev/null @@ -1,147 +0,0 @@ -using BufferOwner = System.Buffers.IMemoryOwner; -using System.Buffers; -using Cysharp.Threading.Tasks; - -namespace System.Net.Sockets.Kcp -{ - /// - /// Kcp回调 - /// - public interface IKcpCallback - { - /// - /// kcp 发送方向输出 - /// - /// kcp 交出发送缓冲区控制权,缓冲区来自 - /// 数据的有效长度 - /// 不需要返回值 - /// 通过增加 avalidLength 能够在协议栈中有效的减少数据拷贝 - void Output(BufferOwner buffer, int avalidLength); - } - - /// - /// Kcp回调 - /// - /// - /// 失败设计,。IMemoryOwner是没有办法代替的。 - /// 这里只相当于把 IKcpCallback 和 IRentable 和并。 - /// - public interface IKcpOutputWriter : IBufferWriter - { - int UnflushedBytes { get; } - void Flush(); - } - - /// - /// 外部提供缓冲区,可以在外部链接一个内存池 - /// - public interface IRentable - { - /// - /// 外部提供缓冲区,可以在外部链接一个内存池 - /// - BufferOwner RentBuffer(int length); - } - - public interface IKcpSetting - { - int Interval(int interval); - /// - /// fastest: ikcp_nodelay(kcp, 1, 20, 2, 1) - /// - /// 0:disable(default), 1:enable - /// internal update timer interval in millisec, default is 100ms - /// 0:disable fast resend(default), 1:enable fast resend - /// 0:normal congestion control(default), 1:disable congestion control - /// - int NoDelay(int nodelay, int interval, int resend, int nc); - /// - /// change MTU size, default is 1400 - /// ** 这个方法不是线程安全的。请在没有发送和接收时调用 。 - /// - /// - /// - /// - /// 如果没有必要,不要修改Mtu。过小的Mtu会导致分片数大于接收窗口,造成kcp阻塞冻结。 - /// - int SetMtu(int mtu = 1400); - /// - /// set maximum window size: sndwnd=32, rcvwnd=128 by default - /// - /// - /// - /// - /// - /// 如果没有必要请不要修改。注意确保接收窗口必须大于最大分片数。 - /// - int WndSize(int sndwnd = 32, int rcvwnd = 128); - } - - public interface IKcpUpdate - { - void Update(in DateTimeOffset time); - } - - public interface IKcpSendable - { - /// - /// 将要发送到网络的数据Send到kcp协议中 - /// - /// - /// - int Send(ReadOnlySpan span, object options = null); - /// - /// 将要发送到网络的数据Send到kcp协议中 - /// - /// - /// - int Send(ReadOnlySequence span, object options = null); - } - - public interface IKcpInputable - { - /// - /// 下层收到数据后添加到kcp协议中 - /// - /// - int Input(ReadOnlySpan span); - /// - /// 下层收到数据后添加到kcp协议中 - /// - /// - int Input(ReadOnlySequence span); - } - - /// - /// kcp协议输入输出标准接口 - /// - public interface IKcpIO : IKcpSendable, IKcpInputable - { - /// - /// 从kcp中取出一个整合完毕的数据包 - /// - /// - UniTask RecvAsync(IBufferWriter writer, object options = null); - - /// - /// 从kcp中取出一个整合完毕的数据包 - /// - /// - /// - /// 接收数据长度 - UniTask RecvAsync(ArraySegment buffer, object options = null); - - /// - /// 从kcp协议中取出需要发送到网络的数据。 - /// - /// - /// - /// - UniTask OutputAsync(IBufferWriter writer, object options = null); - } - -} - - - - diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/IKcpInterface.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/IKcpInterface.cs.meta deleted file mode 100644 index 6fa4a162..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/IKcpInterface.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b0ca98e42147b3948bc8d30f24e9c366 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/IKcpSegment.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/IKcpSegment.cs deleted file mode 100644 index 8308bf7d..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/IKcpSegment.cs +++ /dev/null @@ -1,88 +0,0 @@ -namespace System.Net.Sockets.Kcp -{ - /// - /// Kcp报头 - /// https://zhuanlan.zhihu.com/p/559191428 - /// - public interface IKcpHeader - { - /// - /// 会话编号,两方一致才会通信 - /// - uint conv { get; set; } - /// - /// 指令类型 - /// - /// - /// IKCP_CMD_PUSH = 81 // cmd: push data 数据报文 - /// IKCP_CMD_ACK = 82 // cmd: ack 确认报文 - /// IKCP_CMD_WASK = 83 // cmd: window probe (ask) 窗口探测报文,询问对端剩余接收窗口的大小. - /// IKCP_CMD_WINS = 84 // cmd: window size (tell) 窗口通知报文,通知对端剩余接收窗口的大小. - /// - byte cmd { get; set; } - /// - /// 剩余分片数量,表示随后还有多少个报文属于同一个包。 - /// - byte frg { get; set; } - /// - /// 自己可用窗口大小 - /// - ushort wnd { get; set; } - /// - /// 发送时的时间戳 - /// - uint ts { get; set; } - /// - /// 编号 确认编号或者报文编号 - /// - uint sn { get; set; } - /// - /// 代表编号前面的所有报都收到了的标志 - /// - uint una { get; set; } - /// - /// 数据内容长度 - /// - uint len { get; } - } - public interface IKcpSegment : IKcpHeader - { - /// - /// 重传的时间戳。超过当前时间重发这个包 - /// - uint resendts { get; set; } - /// - /// 超时重传时间,根据网络去定 - /// - uint rto { get; set; } - /// - /// 快速重传机制,记录被跳过的次数,超过次数进行快速重传 - /// - uint fastack { get; set; } - /// - /// 重传次数 - /// - uint xmit { get; set; } - - /// - /// 数据内容 - /// - Span data { get; } - /// - /// 将IKcpSegment编码成字节数组,并返回总长度(包括Kcp报头) - /// - /// - /// - int Encode(Span buffer); - } - - public interface ISegmentManager where Segment : IKcpSegment - { - Segment Alloc(int appendDateSize); - void Free(Segment seg); - } - -} - - - diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/IKcpSegment.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/IKcpSegment.cs.meta deleted file mode 100644 index d3c132cd..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/IKcpSegment.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a9259bb6b548e46459cc766d8fe2faeb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/Kcp.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/Kcp.cs deleted file mode 100644 index c0f6b43d..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/Kcp.cs +++ /dev/null @@ -1,387 +0,0 @@ -using System.Buffers; -using BufferOwner = System.Buffers.IMemoryOwner; - -namespace System.Net.Sockets.Kcp -{ - public class Kcp : KcpCore - where Segment : IKcpSegment - { - /// - /// create a new kcp control object, 'conv' must equal in two endpoint - /// from the same connection. - /// - /// - /// - /// 可租用内存的回调 - public Kcp(uint conv_, IKcpCallback callback, IRentable rentable = null) - : base(conv_) - { - callbackHandle = callback; - this.rentable = rentable; - } - - - //extension 重构和新增加的部分============================================ - - IRentable rentable; - /// - /// 如果外部能够提供缓冲区则使用外部缓冲区,否则new byte[] - /// - /// - /// - internal protected override BufferOwner CreateBuffer(int needSize) - { - var res = rentable?.RentBuffer(needSize); - if (res == null) - { - return base.CreateBuffer(needSize); - } - else - { - if (res.Memory.Length < needSize) - { - throw new ArgumentException($"{nameof(rentable.RentBuffer)} 指定的委托不符合标准,返回的" + - $"BufferOwner.Memory.Length 小于 {nameof(needSize)}"); - } - } - - return res; - } - - /// - /// TryRecv Recv设计上同一时刻只允许一个线程调用。 - /// 因为要保证数据顺序,多个线程同时调用Recv也没有意义。 - /// 所以只需要部分加锁即可。 - /// - /// - public (BufferOwner buffer, int avalidLength) TryRecv() - { - var peekSize = -1; - lock (rcv_queueLock) - { - if (rcv_queue.Count == 0) - { - ///没有可用包 - return (null, -1); - } - - var seq = rcv_queue[0]; - - if (seq.frg == 0) - { - peekSize = (int)seq.len; - } - - if (rcv_queue.Count < seq.frg + 1) - { - ///没有足够的包 - return (null, -1); - } - - uint length = 0; - - foreach (var item in rcv_queue) - { - length += item.len; - if (item.frg == 0) - { - break; - } - } - - peekSize = (int)length; - - if (peekSize <= 0) - { - return (null, -2); - } - } - - var buffer = CreateBuffer(peekSize); - var recvlength = UncheckRecv(buffer.Memory.Span); - return (buffer, recvlength); - } - - /// - /// TryRecv Recv设计上同一时刻只允许一个线程调用。 - /// 因为要保证数据顺序,多个线程同时调用Recv也没有意义。 - /// 所以只需要部分加锁即可。 - /// - /// - /// - public int TryRecv(IBufferWriter writer) - { - var peekSize = -1; - lock (rcv_queueLock) - { - if (rcv_queue.Count == 0) - { - ///没有可用包 - return -1; - } - - var seq = rcv_queue[0]; - - if (seq.frg == 0) - { - peekSize = (int)seq.len; - } - - if (rcv_queue.Count < seq.frg + 1) - { - ///没有足够的包 - return -1; - } - - uint length = 0; - - foreach (var item in rcv_queue) - { - length += item.len; - if (item.frg == 0) - { - break; - } - } - - peekSize = (int)length; - - if (peekSize <= 0) - { - return -2; - } - } - - return UncheckRecv(writer); - } - - /// - /// user/upper level recv: returns size, returns below zero for EAGAIN - /// - /// - /// - public int Recv(Span buffer) - { - if (0 == rcv_queue.Count) - { - return -1; - } - - var peekSize = PeekSize(); - if (peekSize < 0) - { - return -2; - } - - if (peekSize > buffer.Length) - { - return -3; - } - - /// 拆分函数 - var recvLength = UncheckRecv(buffer); - - return recvLength; - } - - /// - /// user/upper level recv: returns size, returns below zero for EAGAIN - /// - /// - /// - public int Recv(IBufferWriter writer) - { - if (0 == rcv_queue.Count) - { - return -1; - } - - var peekSize = PeekSize(); - if (peekSize < 0) - { - return -2; - } - - //if (peekSize > buffer.Length) - //{ - // return -3; - //} - - /// 拆分函数 - var recvLength = UncheckRecv(writer); - - return recvLength; - } - - /// - /// 这个函数不检查任何参数 - /// - /// - /// - int UncheckRecv(Span buffer) - { - var recover = false; - if (rcv_queue.Count >= rcv_wnd) - { - recover = true; - } - - #region merge fragment. - /// merge fragment. - - var recvLength = 0; - lock (rcv_queueLock) - { - var count = 0; - foreach (var seg in rcv_queue) - { - seg.data.CopyTo(buffer.Slice(recvLength)); - recvLength += (int)seg.len; - - count++; - int frg = seg.frg; - - SegmentManager.Free(seg); - if (frg == 0) - { - break; - } - } - - if (count > 0) - { - rcv_queue.RemoveRange(0, count); - } - } - - #endregion - - Move_Rcv_buf_2_Rcv_queue(); - - #region fast recover - /// fast recover - if (rcv_queue.Count < rcv_wnd && recover) - { - // ready to send back IKCP_CMD_WINS in ikcp_flush - // tell remote my window size - probe |= IKCP_ASK_TELL; - } - #endregion - return recvLength; - } - - /// - /// 这个函数不检查任何参数 - /// - /// - /// - int UncheckRecv(IBufferWriter writer) - { - var recover = false; - if (rcv_queue.Count >= rcv_wnd) - { - recover = true; - } - - #region merge fragment. - /// merge fragment. - - var recvLength = 0; - lock (rcv_queueLock) - { - var count = 0; - foreach (var seg in rcv_queue) - { - var len = (int)seg.len; - var destination = writer.GetSpan(len); - - seg.data.CopyTo(destination); - writer.Advance(len); - - recvLength += len; - - count++; - int frg = seg.frg; - - SegmentManager.Free(seg); - if (frg == 0) - { - break; - } - } - - if (count > 0) - { - rcv_queue.RemoveRange(0, count); - } - } - - #endregion - - Move_Rcv_buf_2_Rcv_queue(); - - #region fast recover - /// fast recover - if (rcv_queue.Count < rcv_wnd && recover) - { - // ready to send back IKCP_CMD_WINS in ikcp_flush - // tell remote my window size - probe |= IKCP_ASK_TELL; - } - #endregion - return recvLength; - } - - /// - /// check the size of next message in the recv queue - /// - /// - public int PeekSize() - { - lock (rcv_queueLock) - { - if (rcv_queue.Count == 0) - { - ///没有可用包 - return -1; - } - - var seq = rcv_queue[0]; - - if (seq.frg == 0) - { - return (int)seq.len; - } - - if (rcv_queue.Count < seq.frg + 1) - { - ///没有足够的包 - return -1; - } - - uint length = 0; - - foreach (var seg in rcv_queue) - { - length += seg.len; - if (seg.frg == 0) - { - break; - } - } - - return (int)length; - } - } - } -} - - - - - - - - - - diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/Kcp.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/Kcp.cs.meta deleted file mode 100644 index 1dee2c42..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/Kcp.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b3840e90e37f0194bbfafb564ff80d45 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpCore.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpCore.cs deleted file mode 100644 index a7680e0f..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpCore.cs +++ /dev/null @@ -1,2207 +0,0 @@ -using System.Buffers; -using System.Buffers.Binary; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using static System.Math; -using BufferOwner = System.Buffers.IMemoryOwner; - -namespace System.Net.Sockets.Kcp -{ - public abstract class KcpConst - { - // 为了减少阅读难度,变量名尽量于 C版 统一 - /* - conv 会话ID - mtu 最大传输单元 - mss 最大分片大小 - state 连接状态(0xFFFFFFFF表示断开连接) - snd_una 第一个未确认的包 - snd_nxt 待发送包的序号 - rcv_nxt 待接收消息序号 - ssthresh 拥塞窗口阈值 - rx_rttvar ack接收rtt浮动值 - rx_srtt ack接收rtt静态值 - rx_rto 由ack接收延迟计算出来的复原时间 - rx_minrto 最小复原时间 - snd_wnd 发送窗口大小 - rcv_wnd 接收窗口大小 - rmt_wnd, 远端接收窗口大小 - cwnd, 拥塞窗口大小 - probe 探查变量,IKCP_ASK_TELL表示告知远端窗口大小。IKCP_ASK_SEND表示请求远端告知窗口大小 - interval 内部flush刷新间隔 - ts_flush 下次flush刷新时间戳 - nodelay 是否启动无延迟模式 - updated 是否调用过update函数的标识 - ts_probe, 下次探查窗口的时间戳 - probe_wait 探查窗口需要等待的时间 - dead_link 最大重传次数 - incr 可发送的最大数据量 - fastresend 触发快速重传的重复ack个数 - nocwnd 取消拥塞控制 - stream 是否采用流传输模式 - - snd_queue 发送消息的队列 - rcv_queue 接收消息的队列 - snd_buf 发送消息的缓存 - rcv_buf 接收消息的缓存 - acklist 待发送的ack列表 - buffer 存储消息字节流的内存 - output udp发送消息的回调函数 - */ - - #region Const - - public const int IKCP_RTO_NDL = 30; // no delay min rto - public const int IKCP_RTO_MIN = 100; // normal min rto - public const int IKCP_RTO_DEF = 200; - public const int IKCP_RTO_MAX = 60000; - /// - /// 数据报文 - /// - public const int IKCP_CMD_PUSH = 81; // cmd: push data - /// - /// 确认报文 - /// - public const int IKCP_CMD_ACK = 82; // cmd: ack - /// - /// 窗口探测报文,询问对端剩余接收窗口的大小. - /// - public const int IKCP_CMD_WASK = 83; // cmd: window probe (ask) - /// - /// 窗口通知报文,通知对端剩余接收窗口的大小. - /// - public const int IKCP_CMD_WINS = 84; // cmd: window size (tell) - /// - /// IKCP_ASK_SEND表示请求远端告知窗口大小 - /// - public const int IKCP_ASK_SEND = 1; // need to send IKCP_CMD_WASK - /// - /// IKCP_ASK_TELL表示告知远端窗口大小。 - /// - public const int IKCP_ASK_TELL = 2; // need to send IKCP_CMD_WINS - public const int IKCP_WND_SND = 32; - /// - /// 接收窗口默认值。必须大于最大分片数 - /// - public const int IKCP_WND_RCV = 128; // must >= max fragment size - /// - /// 默认最大传输单元 常见路由值 1492 1480 默认1400保证在路由层不会被分片 - /// - public const int IKCP_MTU_DEF = 1400; - public const int IKCP_ACK_FAST = 3; - public const int IKCP_INTERVAL = 100; - public const int IKCP_OVERHEAD = 24; - public const int IKCP_DEADLINK = 20; - public const int IKCP_THRESH_INIT = 2; - public const int IKCP_THRESH_MIN = 2; - /// - /// 窗口探查CD - /// - public const int IKCP_PROBE_INIT = 7000; // 7 secs to probe window size - public const int IKCP_PROBE_LIMIT = 120000; // up to 120 secs to probe window - public const int IKCP_FASTACK_LIMIT = 5; // max times to trigger fastack - #endregion - - /// - /// https://github.com/skywind3000/kcp/issues/53 - /// 按照 C版 设计,使用小端字节序 - /// - public static bool IsLittleEndian = true; - } - - /// - /// https://luyuhuang.tech/2020/12/09/kcp.html - /// https://github.com/skywind3000/kcp/wiki/Network-Layer - /// 外部buffer ----拆分拷贝----等待列表 -----移动----发送列表----拷贝----发送buffer---output - /// https://github.com/skywind3000/kcp/issues/118#issuecomment-338133930 - /// - public partial class KcpCore : KcpConst, IKcpSetting, IKcpUpdate, IDisposable - where Segment : IKcpSegment - { - #region kcp members - /// - /// 频道号 - /// - public uint conv { get; protected set; } - /// - /// 最大传输单元(Maximum Transmission Unit,MTU) - /// - protected uint mtu; - - /// - /// 缓冲区最小大小 - /// - protected int BufferNeedSize - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - return (int)((mtu/* + IKCP_OVERHEAD*/) /** 3*/); - } - } - - /// - /// 最大报文段长度 - /// - protected uint mss; - /// - /// 连接状态(0xFFFFFFFF表示断开连接) - /// - protected int state; - /// - /// 第一个未确认的包 - /// - protected uint snd_una; - /// - /// 待发送包的序号 - /// - protected uint snd_nxt; - /// - /// 下一个等待接收消息ID,待接收消息序号 - /// - protected uint rcv_nxt; - protected uint ts_recent; - protected uint ts_lastack; - /// - /// 拥塞窗口阈值 - /// - protected uint ssthresh; - /// - /// ack接收rtt浮动值 - /// - protected uint rx_rttval; - /// - /// ack接收rtt静态值 - /// - protected uint rx_srtt; - /// - /// 由ack接收延迟计算出来的复原时间。Retransmission TimeOut(RTO), 超时重传时间. - /// - protected uint rx_rto; - /// - /// 最小复原时间 - /// - protected uint rx_minrto; - /// - /// 发送窗口大小 - /// - protected uint snd_wnd; - /// - /// 接收窗口大小 - /// - protected uint rcv_wnd; - /// - /// 远端接收窗口大小 - /// - protected uint rmt_wnd; - /// - /// 拥塞窗口大小 - /// - protected uint cwnd; - /// - /// 探查变量,IKCP_ASK_TELL表示告知远端窗口大小。IKCP_ASK_SEND表示请求远端告知窗口大小 - /// - protected uint probe; - protected uint current; - /// - /// 内部flush刷新间隔 - /// - protected uint interval; - /// - /// 下次flush刷新时间戳 - /// - protected uint ts_flush; - protected uint xmit; - /// - /// 是否启动无延迟模式 - /// - protected uint nodelay; - /// - /// 是否调用过update函数的标识 - /// - protected uint updated; - /// - /// 下次探查窗口的时间戳 - /// - protected uint ts_probe; - /// - /// 探查窗口需要等待的时间 - /// - protected uint probe_wait; - /// - /// 最大重传次数 - /// - protected uint dead_link; - /// - /// 可发送的最大数据量 - /// - protected uint incr; - /// - /// 触发快速重传的重复ack个数 - /// - public int fastresend; - public int fastlimit; - /// - /// 取消拥塞控制 - /// - protected int nocwnd; - protected int logmask; - /// - /// 是否采用流传输模式 - /// - public int stream; - protected BufferOwner buffer; - - #endregion - - #region 锁和容器 - - /// - /// 增加锁保证发送线程安全,否则可能导致2个消息的分片交替入队。 - /// 用例:普通发送和广播可能会导致多个线程同时调用Send方法。 - /// - protected readonly object snd_queueLock = new object(); - protected readonly object snd_bufLock = new object(); - protected readonly object rcv_bufLock = new object(); - protected readonly object rcv_queueLock = new object(); - - /// - /// 发送 ack 队列 - /// - protected ConcurrentQueue<(uint sn, uint ts)> acklist = new ConcurrentQueue<(uint sn, uint ts)>(); - /// - /// 发送等待队列 - /// - internal ConcurrentQueue snd_queue = new ConcurrentQueue(); - /// - /// 正在发送列表 - /// - internal LinkedList snd_buf = new LinkedList(); - /// - /// 正在等待触发接收回调函数消息列表 - /// 需要执行的操作 添加 遍历 删除 - /// - internal List rcv_queue = new List(); - /// - /// 正在等待重组消息列表 - /// 需要执行的操作 添加 插入 遍历 删除 - /// - internal LinkedList rcv_buf = new LinkedList(); - - /// - /// get how many packet is waiting to be sent - /// - /// - public int WaitSnd => snd_buf.Count + snd_queue.Count; - - #endregion - - public ISegmentManager SegmentManager { get; set; } - public KcpCore(uint conv_) - { - conv = conv_; - - snd_wnd = IKCP_WND_SND; - rcv_wnd = IKCP_WND_RCV; - rmt_wnd = IKCP_WND_RCV; - mtu = IKCP_MTU_DEF; - mss = mtu - IKCP_OVERHEAD; - buffer = CreateBuffer(BufferNeedSize); - - rx_rto = IKCP_RTO_DEF; - rx_minrto = IKCP_RTO_MIN; - interval = IKCP_INTERVAL; - ts_flush = IKCP_INTERVAL; - ssthresh = IKCP_THRESH_INIT; - fastlimit = IKCP_FASTACK_LIMIT; - dead_link = IKCP_DEADLINK; - } - - #region IDisposable Support - private bool disposedValue = false; // 要检测冗余调用 - - /// - /// 是否正在释放 - /// - private bool m_disposing = false; - - protected bool CheckDispose() - { - if (m_disposing) - { - return true; - } - - if (disposedValue) - { - throw new ObjectDisposedException( - $"{nameof(Kcp)} [conv:{conv}]"); - } - - return false; - } - - protected virtual void Dispose(bool disposing) - { - try - { - m_disposing = true; - if (!disposedValue) - { - if (disposing) - { - // 释放托管状态(托管对象)。 - callbackHandle = null; - acklist = null; - buffer = null; - } - - // 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。 - // 将大型字段设置为 null。 - void FreeCollection(IEnumerable collection) - { - if (collection == null) - { - return; - } - foreach (var item in collection) - { - try - { - SegmentManager.Free(item); - } - catch (Exception) - { - //理论上此处不会有任何异常 - LogFail($"此处绝不应该出现异常。 Dispose 时出现预计外异常,联系作者"); - } - } - } - - lock (snd_queueLock) - { - while (snd_queue != null && - (snd_queue.TryDequeue(out var segment) - || !snd_queue.IsEmpty) - ) - { - try - { - SegmentManager.Free(segment); - } - catch (Exception) - { - //理论上这里没有任何异常; - } - } - snd_queue = null; - } - - lock (snd_bufLock) - { - FreeCollection(snd_buf); - snd_buf?.Clear(); - snd_buf = null; - } - - lock (rcv_bufLock) - { - FreeCollection(rcv_buf); - rcv_buf?.Clear(); - rcv_buf = null; - } - - lock (rcv_queueLock) - { - FreeCollection(rcv_queue); - rcv_queue?.Clear(); - rcv_queue = null; - } - - - disposedValue = true; - } - } - finally - { - m_disposing = false; - } - - } - - // 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。 - ~KcpCore() - { - // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。 - Dispose(false); - } - - // 添加此代码以正确实现可处置模式。 - /// - /// 释放不是严格线程安全的,尽量使用和Update相同的线程调用, - /// 或者等待析构时自动释放。 - /// - public void Dispose() - { - // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。 - Dispose(true); - // 如果在以上内容中替代了终结器,则取消注释以下行。 - GC.SuppressFinalize(this); - } - - #endregion - - internal protected IKcpCallback callbackHandle; - internal protected IKcpOutputWriter OutputWriter; - - protected static uint Ibound(uint lower, uint middle, uint upper) - { - return Min(Max(lower, middle), upper); - } - - protected static int Itimediff(uint later, uint earlier) - { - return ((int)(later - earlier)); - } - - internal protected virtual BufferOwner CreateBuffer(int needSize) - { - return new KcpInnerBuffer(needSize); - } - - internal protected class KcpInnerBuffer : BufferOwner - { - private readonly Memory _memory; - - public Memory Memory - { - get - { - if (alreadyDisposed) - { - throw new ObjectDisposedException(nameof(KcpInnerBuffer)); - } - return _memory; - } - } - - public KcpInnerBuffer(int size) - { - _memory = new Memory(new byte[size]); - } - - bool alreadyDisposed = false; - public void Dispose() - { - alreadyDisposed = true; - } - } - - - #region 功能逻辑 - - //功能函数 - - /// - /// Determine when should you invoke ikcp_update: - /// returns when you should invoke ikcp_update in millisec, if there - /// is no ikcp_input/_send calling. you can call ikcp_update in that - /// time, instead of call update repeatly. - /// - /// Important to reduce unnacessary ikcp_update invoking. use it to - /// schedule ikcp_update (eg. implementing an epoll-like mechanism, - /// or optimize ikcp_update when handling massive kcp connections) - /// - /// - /// - /// - public DateTimeOffset Check(in DateTimeOffset time) - { - if (CheckDispose()) - { - //检查释放 - return default; - } - - if (updated == 0) - { - return time; - } - - var current_ = time.ConvertTime(); - - var ts_flush_ = ts_flush; - var tm_flush_ = 0x7fffffff; - var tm_packet = 0x7fffffff; - var minimal = 0; - - if (Itimediff(current_, ts_flush_) >= 10000 || Itimediff(current_, ts_flush_) < -10000) - { - ts_flush_ = current_; - } - - if (Itimediff(current_, ts_flush_) >= 0) - { - return time; - } - - tm_flush_ = Itimediff(ts_flush_, current_); - - lock (snd_bufLock) - { - foreach (var seg in snd_buf) - { - var diff = Itimediff(seg.resendts, current_); - if (diff <= 0) - { - return time; - } - - if (diff < tm_packet) - { - tm_packet = diff; - } - } - } - - minimal = tm_packet < tm_flush_ ? tm_packet : tm_flush_; - if (minimal >= interval) minimal = (int)interval; - - return time + TimeSpan.FromMilliseconds(minimal); - } - - /// - /// move available data from rcv_buf -> rcv_queue - /// - protected void Move_Rcv_buf_2_Rcv_queue() - { - lock (rcv_bufLock) - { - while (rcv_buf.Count > 0) - { - var seg = rcv_buf.First.Value; - if (seg.sn == rcv_nxt && rcv_queue.Count < rcv_wnd) - { - rcv_buf.RemoveFirst(); - lock (rcv_queueLock) - { - rcv_queue.Add(seg); - } - - rcv_nxt++; - } - else - { - break; - } - } - } - } - - /// - /// update ack. - /// - /// - protected void Update_ack(int rtt) - { - if (rx_srtt == 0) - { - rx_srtt = (uint)rtt; - rx_rttval = (uint)rtt / 2; - } - else - { - int delta = (int)((uint)rtt - rx_srtt); - - if (delta < 0) - { - delta = -delta; - } - - rx_rttval = (3 * rx_rttval + (uint)delta) / 4; - rx_srtt = (uint)((7 * rx_srtt + rtt) / 8); - - if (rx_srtt < 1) - { - rx_srtt = 1; - } - } - - var rto = rx_srtt + Max(interval, 4 * rx_rttval); - - rx_rto = Ibound(rx_minrto, rto, IKCP_RTO_MAX); - } - - protected void Shrink_buf() - { - lock (snd_bufLock) - { - snd_una = snd_buf.Count > 0 ? snd_buf.First.Value.sn : snd_nxt; - } - } - - protected void Parse_ack(uint sn) - { - if (Itimediff(sn, snd_una) < 0 || Itimediff(sn, snd_nxt) >= 0) - { - return; - } - - lock (snd_bufLock) - { - for (var p = snd_buf.First; p != null; p = p.Next) - { - var seg = p.Value; - if (sn == seg.sn) - { - snd_buf.Remove(p); - SegmentManager.Free(seg); - break; - } - - if (Itimediff(sn, seg.sn) < 0) - { - break; - } - } - } - } - - protected void Parse_una(uint una) - { - /// 删除给定时间之前的片段。保留之后的片段 - lock (snd_bufLock) - { - while (snd_buf.First != null) - { - var seg = snd_buf.First.Value; - if (Itimediff(una, seg.sn) > 0) - { - snd_buf.RemoveFirst(); - SegmentManager.Free(seg); - } - else - { - break; - } - } - } - - } - - protected void Parse_fastack(uint sn, uint ts) - { - if (Itimediff(sn, snd_una) < 0 || Itimediff(sn, snd_nxt) >= 0) - { - return; - } - - lock (snd_bufLock) - { - foreach (var item in snd_buf) - { - var seg = item; - if (Itimediff(sn, seg.sn) < 0) - { - break; - } - else if (sn != seg.sn) - { -#if !IKCP_FASTACK_CONSERVE - seg.fastack++; -#else - if (Itimediff(ts, seg.ts) >= 0) - { - seg.fastack++; - } -#endif - } - } - } - } - - /// - /// 处理下层网络收到的数据包 - /// - /// - internal virtual void Parse_data(Segment newseg) - { - var sn = newseg.sn; - - lock (rcv_bufLock) - { - if (Itimediff(sn, rcv_nxt + rcv_wnd) >= 0 || Itimediff(sn, rcv_nxt) < 0) - { - // 如果接收到数据报文的编号大于 rcv_nxt + rcv_wnd 或小于 rcv_nxt, 这个报文就会被丢弃. - SegmentManager.Free(newseg); - return; - } - - var repeat = false; - - ///检查是否重复消息和插入位置 - LinkedListNode p; - for (p = rcv_buf.Last; p != null; p = p.Previous) - { - var seg = p.Value; - if (seg.sn == sn) - { - repeat = true; - break; - } - - if (Itimediff(sn, seg.sn) > 0) - { - break; - } - } - - if (!repeat) - { - if (CanLog(KcpLogMask.IKCP_LOG_PARSE_DATA)) - { - LogWriteLine($"{newseg.ToLogString()}", KcpLogMask.IKCP_LOG_PARSE_DATA.ToString()); - } - - if (p == null) - { - rcv_buf.AddFirst(newseg); - if (newseg.frg + 1 > rcv_wnd) - { - //分片数大于接收窗口,造成kcp阻塞冻结。 - //Console.WriteLine($"分片数大于接收窗口,造成kcp阻塞冻结。frgCount:{newseg.frg + 1} rcv_wnd:{rcv_wnd}"); - //百分之百阻塞冻结,打印日志没有必要。直接抛出异常。 - throw new NotSupportedException($"分片数大于接收窗口,造成kcp阻塞冻结。frgCount:{newseg.frg + 1} rcv_wnd:{rcv_wnd}"); - } - } - else - { - rcv_buf.AddAfter(p, newseg); - } - - } - else - { - SegmentManager.Free(newseg); - } - } - - Move_Rcv_buf_2_Rcv_queue(); - } - - protected ushort Wnd_unused() - { - ///此处没有加锁,所以不要内联变量,否则可能导致 判断变量和赋值变量不一致 - int waitCount = rcv_queue.Count; - - if (waitCount < rcv_wnd) - { - //Q:为什么要减去nrcv_que,rcv_queue中已经排好序了,还要算在接收窗口内,感觉不能理解? - //现在问题是如果一个超大数据包,分片数大于rcv_wnd接收窗口,会导致rcv_wnd持续为0,阻塞整个流程。 - //个人理解,rcv_queue中的数据是已经确认的数据,无论用户是否recv,都不应该影响收发。 - //A:现在在发送出加一个分片数检测,过大直接抛出异常。防止阻塞发送。 - //在接收端也加一个检测,如果(frg+1)分片数 > rcv_wnd,也要抛出一个异常或者警告。至少有个提示。 - - /// fix https://github.com/skywind3000/kcp/issues/126 - /// 实际上 rcv_wnd 不应该大于65535 - var count = rcv_wnd - waitCount; - return (ushort)Min(count, ushort.MaxValue); - } - - return 0; - } - - /// - /// flush pending data - /// - protected void Flush() - { - var current_ = current; - var buffer_ = buffer; - var change = 0; - var lost = 0; - var offset = 0; - - if (updated == 0) - { - return; - } - - ushort wnd_ = Wnd_unused(); - - unsafe - { - ///在栈上分配这个segment,这个segment随用随销毁,不会被保存 - const int len = KcpSegment.LocalOffset + KcpSegment.HeadOffset; - var ptr = stackalloc byte[len]; - KcpSegment seg = new KcpSegment(ptr, 0); - //seg = KcpSegment.AllocHGlobal(0); - - seg.conv = conv; - seg.cmd = IKCP_CMD_ACK; - //seg.frg = 0; - seg.wnd = wnd_; - seg.una = rcv_nxt; - //seg.len = 0; - //seg.sn = 0; - //seg.ts = 0; - - #region flush acknowledges - - if (CheckDispose()) - { - //检查释放 - return; - } - - while (acklist.TryDequeue(out var temp)) - { - if (offset + IKCP_OVERHEAD > mtu) - { - callbackHandle.Output(buffer, offset); - offset = 0; - buffer = CreateBuffer(BufferNeedSize); - - //IKcpOutputer outputer = null; - //var span = outputer.GetSpan(offset); - //buffer.Memory.Span.Slice(0, offset).CopyTo(span); - //outputer.Advance(offset); - //outputer.Flush(); - } - - seg.sn = temp.sn; - seg.ts = temp.ts; - offset += seg.Encode(buffer.Memory.Span.Slice(offset)); - } - - #endregion - - #region probe window size (if remote window size equals zero) - // probe window size (if remote window size equals zero) - if (rmt_wnd == 0) - { - if (probe_wait == 0) - { - probe_wait = IKCP_PROBE_INIT; - ts_probe = current + probe_wait; - } - else - { - if (Itimediff(current, ts_probe) >= 0) - { - if (probe_wait < IKCP_PROBE_INIT) - { - probe_wait = IKCP_PROBE_INIT; - } - - probe_wait += probe_wait / 2; - - if (probe_wait > IKCP_PROBE_LIMIT) - { - probe_wait = IKCP_PROBE_LIMIT; - } - - ts_probe = current + probe_wait; - probe |= IKCP_ASK_SEND; - } - } - } - else - { - ts_probe = 0; - probe_wait = 0; - } - #endregion - - #region flush window probing commands - // flush window probing commands - if ((probe & IKCP_ASK_SEND) != 0) - { - seg.cmd = IKCP_CMD_WASK; - if (offset + IKCP_OVERHEAD > (int)mtu) - { - callbackHandle.Output(buffer, offset); - offset = 0; - buffer = CreateBuffer(BufferNeedSize); - } - offset += seg.Encode(buffer.Memory.Span.Slice(offset)); - } - - if ((probe & IKCP_ASK_TELL) != 0) - { - seg.cmd = IKCP_CMD_WINS; - if (offset + IKCP_OVERHEAD > (int)mtu) - { - callbackHandle.Output(buffer, offset); - offset = 0; - buffer = CreateBuffer(BufferNeedSize); - } - offset += seg.Encode(buffer.Memory.Span.Slice(offset)); - } - - probe = 0; - #endregion - } - - #region 刷新,将发送等待列表移动到发送列表 - - // calculate window size - var cwnd_ = Min(snd_wnd, rmt_wnd); - if (nocwnd == 0) - { - cwnd_ = Min(cwnd, cwnd_); - } - - while (Itimediff(snd_nxt, snd_una + cwnd_) < 0) - { - if (snd_queue.TryDequeue(out var newseg)) - { - newseg.conv = conv; - newseg.cmd = IKCP_CMD_PUSH; - newseg.wnd = wnd_; - newseg.ts = current_; - newseg.sn = snd_nxt; - snd_nxt++; - newseg.una = rcv_nxt; - newseg.resendts = current_; - newseg.rto = rx_rto; - newseg.fastack = 0; - newseg.xmit = 0; - lock (snd_bufLock) - { - snd_buf.AddLast(newseg); - } - } - else - { - break; - } - } - - #endregion - - #region 刷新 发送列表,调用Output - - // calculate resent - var resent = fastresend > 0 ? (uint)fastresend : 0xffffffff; - var rtomin = nodelay == 0 ? (rx_rto >> 3) : 0; - - lock (snd_bufLock) - { - // flush data segments - foreach (var item in snd_buf) - { - var segment = item; - var needsend = false; - var debug = Itimediff(current_, segment.resendts); - if (segment.xmit == 0) - { - //新加入 snd_buf 中, 从未发送过的报文直接发送出去; - needsend = true; - segment.xmit++; - segment.rto = rx_rto; - segment.resendts = current_ + rx_rto + rtomin; - } - else if (Itimediff(current_, segment.resendts) >= 0) - { - //发送过的, 但是在 RTO 内未收到 ACK 的报文, 需要重传; - needsend = true; - segment.xmit++; - this.xmit++; - if (nodelay == 0) - { - segment.rto += Math.Max(segment.rto, rx_rto); - } - else - { - var step = nodelay < 2 ? segment.rto : rx_rto; - segment.rto += step / 2; - } - - segment.resendts = current_ + segment.rto; - lost = 1; - } - else if (segment.fastack >= resent) - { - //发送过的, 但是 ACK 失序若干次的报文, 需要执行快速重传. - if (segment.xmit <= fastlimit - || fastlimit <= 0) - { - needsend = true; - segment.xmit++; - segment.fastack = 0; - segment.resendts = current_ + segment.rto; - change++; - } - } - - if (needsend) - { - segment.ts = current_; - segment.wnd = wnd_; - segment.una = rcv_nxt; - - var need = IKCP_OVERHEAD + segment.len; - if (offset + need > mtu) - { - callbackHandle.Output(buffer, offset); - offset = 0; - buffer = CreateBuffer(BufferNeedSize); - } - - offset += segment.Encode(buffer.Memory.Span.Slice(offset)); - - if (CanLog(KcpLogMask.IKCP_LOG_NEED_SEND)) - { - LogWriteLine($"{segment.ToLogString(true)}", KcpLogMask.IKCP_LOG_NEED_SEND.ToString()); - } - - if (segment.xmit >= dead_link) - { - state = -1; - - if (CanLog(KcpLogMask.IKCP_LOG_DEAD_LINK)) - { - LogWriteLine($"state = -1; xmit:{segment.xmit} >= dead_link:{dead_link}", KcpLogMask.IKCP_LOG_DEAD_LINK.ToString()); - } - } - } - } - } - - // flash remain segments - if (offset > 0) - { - callbackHandle.Output(buffer, offset); - offset = 0; - buffer = CreateBuffer(BufferNeedSize); - } - - #endregion - - #region update ssthresh - // update ssthresh 根据丢包情况计算 ssthresh 和 cwnd. - if (change != 0) - { - var inflight = snd_nxt - snd_una; - ssthresh = inflight / 2; - if (ssthresh < IKCP_THRESH_MIN) - { - ssthresh = IKCP_THRESH_MIN; - } - - cwnd = ssthresh + resent; - incr = cwnd * mss; - } - - if (lost != 0) - { - ssthresh = cwnd / 2; - if (ssthresh < IKCP_THRESH_MIN) - { - ssthresh = IKCP_THRESH_MIN; - } - - cwnd = 1; - incr = mss; - } - - if (cwnd < 1) - { - cwnd = 1; - incr = mss; - } - #endregion - - if (state == -1) - { - OnDeadlink(); - } - } - - protected virtual void OnDeadlink() - { - - } - - /// - /// Test OutputWriter - /// - protected void Flush2() - { - var current_ = current; - var change = 0; - var lost = 0; - - if (updated == 0) - { - return; - } - - ushort wnd_ = Wnd_unused(); - - unsafe - { - ///在栈上分配这个segment,这个segment随用随销毁,不会被保存 - const int len = KcpSegment.LocalOffset + KcpSegment.HeadOffset; - var ptr = stackalloc byte[len]; - KcpSegment seg = new KcpSegment(ptr, 0); - //seg = KcpSegment.AllocHGlobal(0); - - seg.conv = conv; - seg.cmd = IKCP_CMD_ACK; - //seg.frg = 0; - seg.wnd = wnd_; - seg.una = rcv_nxt; - //seg.len = 0; - //seg.sn = 0; - //seg.ts = 0; - - #region flush acknowledges - - if (CheckDispose()) - { - //检查释放 - return; - } - - while (acklist.TryDequeue(out var temp)) - { - if (OutputWriter.UnflushedBytes + IKCP_OVERHEAD > mtu) - { - OutputWriter.Flush(); - } - - seg.sn = temp.sn; - seg.ts = temp.ts; - seg.Encode(OutputWriter); - } - - #endregion - - #region probe window size (if remote window size equals zero) - // probe window size (if remote window size equals zero) - if (rmt_wnd == 0) - { - if (probe_wait == 0) - { - probe_wait = IKCP_PROBE_INIT; - ts_probe = current + probe_wait; - } - else - { - if (Itimediff(current, ts_probe) >= 0) - { - if (probe_wait < IKCP_PROBE_INIT) - { - probe_wait = IKCP_PROBE_INIT; - } - - probe_wait += probe_wait / 2; - - if (probe_wait > IKCP_PROBE_LIMIT) - { - probe_wait = IKCP_PROBE_LIMIT; - } - - ts_probe = current + probe_wait; - probe |= IKCP_ASK_SEND; - } - } - } - else - { - ts_probe = 0; - probe_wait = 0; - } - #endregion - - #region flush window probing commands - // flush window probing commands - if ((probe & IKCP_ASK_SEND) != 0) - { - seg.cmd = IKCP_CMD_WASK; - if (OutputWriter.UnflushedBytes + IKCP_OVERHEAD > (int)mtu) - { - OutputWriter.Flush(); - } - seg.Encode(OutputWriter); - } - - if ((probe & IKCP_ASK_TELL) != 0) - { - seg.cmd = IKCP_CMD_WINS; - if (OutputWriter.UnflushedBytes + IKCP_OVERHEAD > (int)mtu) - { - OutputWriter.Flush(); - } - seg.Encode(OutputWriter); - } - - probe = 0; - #endregion - } - - #region 刷新,将发送等待列表移动到发送列表 - - // calculate window size - var cwnd_ = Min(snd_wnd, rmt_wnd); - if (nocwnd == 0) - { - cwnd_ = Min(cwnd, cwnd_); - } - - while (Itimediff(snd_nxt, snd_una + cwnd_) < 0) - { - if (snd_queue.TryDequeue(out var newseg)) - { - newseg.conv = conv; - newseg.cmd = IKCP_CMD_PUSH; - newseg.wnd = wnd_; - newseg.ts = current_; - newseg.sn = snd_nxt; - snd_nxt++; - newseg.una = rcv_nxt; - newseg.resendts = current_; - newseg.rto = rx_rto; - newseg.fastack = 0; - newseg.xmit = 0; - lock (snd_bufLock) - { - snd_buf.AddLast(newseg); - } - } - else - { - break; - } - } - - #endregion - - #region 刷新 发送列表,调用Output - - // calculate resent - var resent = fastresend > 0 ? (uint)fastresend : 0xffffffff; - var rtomin = nodelay == 0 ? (rx_rto >> 3) : 0; - - lock (snd_bufLock) - { - // flush data segments - foreach (var item in snd_buf) - { - var segment = item; - var needsend = false; - var debug = Itimediff(current_, segment.resendts); - if (segment.xmit == 0) - { - //新加入 snd_buf 中, 从未发送过的报文直接发送出去; - needsend = true; - segment.xmit++; - segment.rto = rx_rto; - segment.resendts = current_ + rx_rto + rtomin; - } - else if (Itimediff(current_, segment.resendts) >= 0) - { - //发送过的, 但是在 RTO 内未收到 ACK 的报文, 需要重传; - needsend = true; - segment.xmit++; - this.xmit++; - if (nodelay == 0) - { - segment.rto += Math.Max(segment.rto, rx_rto); - } - else - { - var step = nodelay < 2 ? segment.rto : rx_rto; - segment.rto += step / 2; - } - - segment.resendts = current_ + segment.rto; - lost = 1; - } - else if (segment.fastack >= resent) - { - //发送过的, 但是 ACK 失序若干次的报文, 需要执行快速重传. - if (segment.xmit <= fastlimit - || fastlimit <= 0) - { - needsend = true; - segment.xmit++; - segment.fastack = 0; - segment.resendts = current_ + segment.rto; - change++; - } - } - - if (needsend) - { - segment.ts = current_; - segment.wnd = wnd_; - segment.una = rcv_nxt; - - var need = IKCP_OVERHEAD + segment.len; - if (OutputWriter.UnflushedBytes + need > mtu) - { - OutputWriter.Flush(); - } - - segment.Encode(OutputWriter); - - if (CanLog(KcpLogMask.IKCP_LOG_NEED_SEND)) - { - LogWriteLine($"{segment.ToLogString(true)}", KcpLogMask.IKCP_LOG_NEED_SEND.ToString()); - } - - if (segment.xmit >= dead_link) - { - state = -1; - - if (CanLog(KcpLogMask.IKCP_LOG_DEAD_LINK)) - { - LogWriteLine($"state = -1; xmit:{segment.xmit} >= dead_link:{dead_link}", KcpLogMask.IKCP_LOG_DEAD_LINK.ToString()); - } - } - } - } - } - - - // flash remain segments - if (OutputWriter.UnflushedBytes > 0) - { - OutputWriter.Flush(); - } - - #endregion - - #region update ssthresh - // update ssthresh 根据丢包情况计算 ssthresh 和 cwnd. - if (change != 0) - { - var inflight = snd_nxt - snd_una; - ssthresh = inflight / 2; - if (ssthresh < IKCP_THRESH_MIN) - { - ssthresh = IKCP_THRESH_MIN; - } - - cwnd = ssthresh + resent; - incr = cwnd * mss; - } - - if (lost != 0) - { - ssthresh = cwnd / 2; - if (ssthresh < IKCP_THRESH_MIN) - { - ssthresh = IKCP_THRESH_MIN; - } - - cwnd = 1; - incr = mss; - } - - if (cwnd < 1) - { - cwnd = 1; - incr = mss; - } - #endregion - - if (state == -1) - { - OnDeadlink(); - } - } - - /// - /// update state (call it repeatedly, every 10ms-100ms), or you can ask - /// ikcp_check when to call it again (without ikcp_input/_send calling). - /// - /// DateTime.UtcNow - public void Update(in DateTimeOffset time) - { - if (CheckDispose()) - { - //检查释放 - return; - } - - current = time.ConvertTime(); - - if (updated == 0) - { - updated = 1; - ts_flush = current; - } - - var slap = Itimediff(current, ts_flush); - - if (slap >= 10000 || slap < -10000) - { - ts_flush = current; - slap = 0; - } - - if (slap >= 0) - { - ts_flush += interval; - if (Itimediff(current, ts_flush) >= 0) - { - ts_flush = current + interval; - } - - Flush(); - } - } - - #endregion - - #region 设置控制 - - public int SetMtu(int mtu = IKCP_MTU_DEF) - { - if (mtu < 50 || mtu < IKCP_OVERHEAD) - { - return -1; - } - - var buffer_ = CreateBuffer(BufferNeedSize); - if (null == buffer_) - { - return -2; - } - - this.mtu = (uint)mtu; - mss = this.mtu - IKCP_OVERHEAD; - buffer.Dispose(); - buffer = buffer_; - return 0; - } - - /// - /// - /// - /// - /// - public int Interval(int interval_) - { - if (interval_ > 5000) - { - interval_ = 5000; - } - else if (interval_ < 0) - { - /// 将最小值 10 改为 0; - ///在特殊形况下允许CPU满负荷运转; - interval_ = 0; - } - interval = (uint)interval_; - return 0; - } - - public int NoDelay(int nodelay_, int interval_, int resend_, int nc_) - { - - if (nodelay_ > 0) - { - nodelay = (uint)nodelay_; - if (nodelay_ != 0) - { - rx_minrto = IKCP_RTO_NDL; - } - else - { - rx_minrto = IKCP_RTO_MIN; - } - } - - if (resend_ >= 0) - { - fastresend = resend_; - } - - if (nc_ >= 0) - { - nocwnd = nc_; - } - - return Interval(interval_); - } - - public int WndSize(int sndwnd = IKCP_WND_SND, int rcvwnd = IKCP_WND_RCV) - { - if (sndwnd > 0) - { - snd_wnd = (uint)sndwnd; - } - - if (rcvwnd > 0) - { - rcv_wnd = (uint)rcvwnd; - } - - return 0; - } - - #endregion - - - } - - public partial class KcpCore : IKcpSendable - { - /// - /// user/upper level send, returns below zero for error - /// - /// - /// - /// - public int Send(ReadOnlySpan span, object options = null) - { - if (CheckDispose()) - { - //检查释放 - return -4; - } - - if (mss <= 0) - { - throw new InvalidOperationException($" mss <= 0 "); - } - - - if (span.Length == 0) - { - return -1; - } - var offset = 0; - int count; - - #region append to previous segment in streaming mode (if possible) - /// 基于线程安全和数据结构的等原因,移除了追加数据到最后一个包行为。 - #endregion - - #region fragment - - if (span.Length <= mss) - { - count = 1; - } - else - { - count = (int)(span.Length + mss - 1) / (int)mss; - } - - if (count > IKCP_WND_RCV) - { - return -2; - } - - if (count == 0) - { - count = 1; - } - - lock (snd_queueLock) - { - for (var i = 0; i < count; i++) - { - int size; - if (span.Length - offset > mss) - { - size = (int)mss; - } - else - { - size = (int)span.Length - offset; - } - - var seg = SegmentManager.Alloc(size); - span.Slice(offset, size).CopyTo(seg.data); - offset += size; - seg.frg = (byte)(count - i - 1); - snd_queue.Enqueue(seg); - } - } - - #endregion - - return 0; - } - - //public int Send(Span span) - //{ - // return Send((ReadOnlySpan)span); - //} - - public int Send(ReadOnlySequence span, object options = null) - { - if (CheckDispose()) - { - //检查释放 - return -4; - } - - if (mss <= 0) - { - throw new InvalidOperationException($" mss <= 0 "); - } - - - if (span.Length == 0) - { - return -1; - } - var offset = 0; - int count; - - #region append to previous segment in streaming mode (if possible) - /// 基于线程安全和数据结构的等原因,移除了追加数据到最后一个包行为。 - #endregion - - #region fragment - - if (span.Length <= mss) - { - count = 1; - } - else - { - count = (int)(span.Length + mss - 1) / (int)mss; - } - - if (count > IKCP_WND_RCV) - { - return -2; - } - - if (count == 0) - { - count = 1; - } - - lock (snd_queueLock) - { - for (var i = 0; i < count; i++) - { - int size; - if (span.Length - offset > mss) - { - size = (int)mss; - } - else - { - size = (int)span.Length - offset; - } - - var seg = SegmentManager.Alloc(size); - span.Slice(offset, size).CopyTo(seg.data); - offset += size; - seg.frg = (byte)(count - i - 1); - snd_queue.Enqueue(seg); - } - } - - #endregion - - return 0; - } - } - - public partial class KcpCore : IKcpInputable - { - /// - /// when you received a low level packet (eg. UDP packet), call it - /// - /// - /// - public int Input(ReadOnlySpan span) - { - if (CheckDispose()) - { - //检查释放 - return -4; - } - - if (CanLog(KcpLogMask.IKCP_LOG_INPUT)) - { - LogWriteLine($"[RI] {span.Length} bytes", KcpLogMask.IKCP_LOG_INPUT.ToString()); - } - - if (span.Length < IKCP_OVERHEAD) - { - return -1; - } - - uint prev_una = snd_una; - var offset = 0; - int flag = 0; - uint maxack = 0; - uint latest_ts = 0; - while (true) - { - uint ts = 0; - uint sn = 0; - uint length = 0; - uint una = 0; - uint conv_ = 0; - ushort wnd = 0; - byte cmd = 0; - byte frg = 0; - - if (span.Length - offset < IKCP_OVERHEAD) - { - break; - } - - Span header = stackalloc byte[24]; - span.Slice(offset, 24).CopyTo(header); - offset += ReadHeader(header, - ref conv_, - ref cmd, - ref frg, - ref wnd, - ref ts, - ref sn, - ref una, - ref length); - - if (conv != conv_) - { - return -1; - } - - if (span.Length - offset < length || (int)length < 0) - { - return -2; - } - - switch (cmd) - { - case IKCP_CMD_PUSH: - case IKCP_CMD_ACK: - case IKCP_CMD_WASK: - case IKCP_CMD_WINS: - break; - default: - return -3; - } - - rmt_wnd = wnd; - Parse_una(una); - Shrink_buf(); - - if (IKCP_CMD_ACK == cmd) - { - if (Itimediff(current, ts) >= 0) - { - Update_ack(Itimediff(current, ts)); - } - Parse_ack(sn); - Shrink_buf(); - - if (flag == 0) - { - flag = 1; - maxack = sn; - latest_ts = ts; - } - else if (Itimediff(sn, maxack) > 0) - { -#if !IKCP_FASTACK_CONSERVE - maxack = sn; - latest_ts = ts; -#else - if (Itimediff(ts, latest_ts) > 0) - { - maxack = sn; - latest_ts = ts; - } -#endif - } - - if (CanLog(KcpLogMask.IKCP_LOG_IN_ACK)) - { - LogWriteLine($"input ack: sn={sn} rtt={Itimediff(current, ts)} rto={rx_rto}", KcpLogMask.IKCP_LOG_IN_ACK.ToString()); - } - } - else if (IKCP_CMD_PUSH == cmd) - { - if (CanLog(KcpLogMask.IKCP_LOG_IN_DATA)) - { - LogWriteLine($"input psh: sn={sn} ts={ts}", KcpLogMask.IKCP_LOG_IN_DATA.ToString()); - } - - if (Itimediff(sn, rcv_nxt + rcv_wnd) < 0) - { - ///instead of ikcp_ack_push - acklist.Enqueue((sn, ts)); - - if (Itimediff(sn, rcv_nxt) >= 0) - { - var seg = SegmentManager.Alloc((int)length); - seg.conv = conv_; - seg.cmd = cmd; - seg.frg = frg; - seg.wnd = wnd; - seg.ts = ts; - seg.sn = sn; - seg.una = una; - //seg.len = length; 长度在分配时确定,不能改变 - - if (length > 0) - { - span.Slice(offset, (int)length).CopyTo(seg.data); - } - - Parse_data(seg); - } - } - } - else if (IKCP_CMD_WASK == cmd) - { - // ready to send back IKCP_CMD_WINS in Ikcp_flush - // tell remote my window size - probe |= IKCP_ASK_TELL; - - if (CanLog(KcpLogMask.IKCP_LOG_IN_PROBE)) - { - LogWriteLine($"input probe", KcpLogMask.IKCP_LOG_IN_PROBE.ToString()); - } - } - else if (IKCP_CMD_WINS == cmd) - { - // do nothing - if (CanLog(KcpLogMask.IKCP_LOG_IN_WINS)) - { - LogWriteLine($"input wins: {wnd}", KcpLogMask.IKCP_LOG_IN_WINS.ToString()); - } - } - else - { - return -3; - } - - offset += (int)length; - } - - if (flag != 0) - { - Parse_fastack(maxack, latest_ts); - } - - if (Itimediff(this.snd_una, prev_una) > 0) - { - if (cwnd < rmt_wnd) - { - if (cwnd < ssthresh) - { - cwnd++; - incr += mss; - } - else - { - if (incr < mss) - { - incr = mss; - } - incr += (mss * mss) / incr + (mss / 16); - if ((cwnd + 1) * mss <= incr) - { -#if true - cwnd = (incr + mss - 1) / ((mss > 0) ? mss : 1); -#else - cwnd++; -#endif - } - } - if (cwnd > rmt_wnd) - { - cwnd = rmt_wnd; - incr = rmt_wnd * mss; - } - } - } - - return 0; - } - - /// - /// - /// - /// - /// - public int Input(ReadOnlySequence span) - { - if (CheckDispose()) - { - //检查释放 - return -4; - } - - if (CanLog(KcpLogMask.IKCP_LOG_INPUT)) - { - LogWriteLine($"[RI] {span.Length} bytes", KcpLogMask.IKCP_LOG_INPUT.ToString()); - } - - if (span.Length < IKCP_OVERHEAD) - { - return -1; - } - - uint prev_una = snd_una; - var offset = 0; - int flag = 0; - uint maxack = 0; - uint latest_ts = 0; - while (true) - { - uint ts = 0; - uint sn = 0; - uint length = 0; - uint una = 0; - uint conv_ = 0; - ushort wnd = 0; - byte cmd = 0; - byte frg = 0; - - if (span.Length - offset < IKCP_OVERHEAD) - { - break; - } - - Span header = stackalloc byte[24]; - span.Slice(offset, 24).CopyTo(header); - offset += ReadHeader(header, - ref conv_, - ref cmd, - ref frg, - ref wnd, - ref ts, - ref sn, - ref una, - ref length); - - if (conv != conv_) - { - return -1; - } - - if (span.Length - offset < length || (int)length < 0) - { - return -2; - } - - switch (cmd) - { - case IKCP_CMD_PUSH: - case IKCP_CMD_ACK: - case IKCP_CMD_WASK: - case IKCP_CMD_WINS: - break; - default: - return -3; - } - - rmt_wnd = wnd; - Parse_una(una); - Shrink_buf(); - - if (IKCP_CMD_ACK == cmd) - { - if (Itimediff(current, ts) >= 0) - { - Update_ack(Itimediff(current, ts)); - } - Parse_ack(sn); - Shrink_buf(); - - if (flag == 0) - { - flag = 1; - maxack = sn; - latest_ts = ts; - } - else if (Itimediff(sn, maxack) > 0) - { -#if !IKCP_FASTACK_CONSERVE - maxack = sn; - latest_ts = ts; -#else - if (Itimediff(ts, latest_ts) > 0) - { - maxack = sn; - latest_ts = ts; - } -#endif - } - - - if (CanLog(KcpLogMask.IKCP_LOG_IN_ACK)) - { - LogWriteLine($"input ack: sn={sn} rtt={Itimediff(current, ts)} rto={rx_rto}", KcpLogMask.IKCP_LOG_IN_ACK.ToString()); - } - } - else if (IKCP_CMD_PUSH == cmd) - { - if (CanLog(KcpLogMask.IKCP_LOG_IN_DATA)) - { - LogWriteLine($"input psh: sn={sn} ts={ts}", KcpLogMask.IKCP_LOG_IN_DATA.ToString()); - } - - if (Itimediff(sn, rcv_nxt + rcv_wnd) < 0) - { - ///instead of ikcp_ack_push - acklist.Enqueue((sn, ts)); - - if (Itimediff(sn, rcv_nxt) >= 0) - { - var seg = SegmentManager.Alloc((int)length); - seg.conv = conv_; - seg.cmd = cmd; - seg.frg = frg; - seg.wnd = wnd; - seg.ts = ts; - seg.sn = sn; - seg.una = una; - //seg.len = length; 长度在分配时确定,不能改变 - - if (length > 0) - { - span.Slice(offset, (int)length).CopyTo(seg.data); - } - - Parse_data(seg); - } - } - } - else if (IKCP_CMD_WASK == cmd) - { - // ready to send back IKCP_CMD_WINS in Ikcp_flush - // tell remote my window size - probe |= IKCP_ASK_TELL; - - if (CanLog(KcpLogMask.IKCP_LOG_IN_PROBE)) - { - LogWriteLine($"input probe", KcpLogMask.IKCP_LOG_IN_PROBE.ToString()); - } - } - else if (IKCP_CMD_WINS == cmd) - { - // do nothing - if (CanLog(KcpLogMask.IKCP_LOG_IN_WINS)) - { - LogWriteLine($"input wins: {wnd}", KcpLogMask.IKCP_LOG_IN_WINS.ToString()); - } - } - else - { - return -3; - } - - offset += (int)length; - } - - if (flag != 0) - { - Parse_fastack(maxack, latest_ts); - } - - if (Itimediff(this.snd_una, prev_una) > 0) - { - if (cwnd < rmt_wnd) - { - if (cwnd < ssthresh) - { - cwnd++; - incr += mss; - } - else - { - if (incr < mss) - { - incr = mss; - } - incr += (mss * mss) / incr + (mss / 16); - if ((cwnd + 1) * mss <= incr) - { -#if true - cwnd = (incr + mss - 1) / ((mss > 0) ? mss : 1); -#else - cwnd++; -#endif - } - } - if (cwnd > rmt_wnd) - { - cwnd = rmt_wnd; - incr = rmt_wnd * mss; - } - } - } - - return 0; - } - - public static int ReadHeader(ReadOnlySpan header, - ref uint conv_, - ref byte cmd, - ref byte frg, - ref ushort wnd, - ref uint ts, - ref uint sn, - ref uint una, - ref uint length) - { - var offset = 0; - if (IsLittleEndian) - { - conv_ = BinaryPrimitives.ReadUInt32LittleEndian(header.Slice(offset)); - offset += 4; - - cmd = header[offset]; - offset += 1; - frg = header[offset]; - offset += 1; - wnd = BinaryPrimitives.ReadUInt16LittleEndian(header.Slice(offset)); - offset += 2; - - ts = BinaryPrimitives.ReadUInt32LittleEndian(header.Slice(offset)); - offset += 4; - sn = BinaryPrimitives.ReadUInt32LittleEndian(header.Slice(offset)); - offset += 4; - una = BinaryPrimitives.ReadUInt32LittleEndian(header.Slice(offset)); - offset += 4; - length = BinaryPrimitives.ReadUInt32LittleEndian(header.Slice(offset)); - offset += 4; - } - else - { - conv_ = BinaryPrimitives.ReadUInt32BigEndian(header.Slice(offset)); - offset += 4; - cmd = header[offset]; - offset += 1; - frg = header[offset]; - offset += 1; - wnd = BinaryPrimitives.ReadUInt16BigEndian(header.Slice(offset)); - offset += 2; - - ts = BinaryPrimitives.ReadUInt32BigEndian(header.Slice(offset)); - offset += 4; - sn = BinaryPrimitives.ReadUInt32BigEndian(header.Slice(offset)); - offset += 4; - una = BinaryPrimitives.ReadUInt32BigEndian(header.Slice(offset)); - offset += 4; - length = BinaryPrimitives.ReadUInt32BigEndian(header.Slice(offset)); - offset += 4; - } - - - return offset; - } - } -} diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpCore.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpCore.cs.meta deleted file mode 100644 index cd9858f7..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpCore.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: fcc0172c723e55a4389ad2f62b68a3fe -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpIO.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpIO.cs deleted file mode 100644 index bfc6cea0..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpIO.cs +++ /dev/null @@ -1,262 +0,0 @@ -using System.Buffers; -using System.Collections.Generic; -using System.Threading.Tasks; -using Cysharp.Threading.Tasks; -using BufferOwner = System.Buffers.IMemoryOwner; - -namespace System.Net.Sockets.Kcp -{ - /// - /// - /// 这是个简单的实现,更复杂使用微软官方实现 - /// - /// - internal class QueuePipe : Queue - { - readonly object _innerLock = new object(); - private TaskCompletionSource source; - - //线程同步上下文由Task机制保证,无需额外处理 - //SynchronizationContext callbackContext; - //public bool UseSynchronizationContext { get; set; } = true; - - public virtual void Write(T item) - { - lock (_innerLock) - { - if (source == null) - { - Enqueue(item); - } - else - { - if (Count > 0) - { - throw new Exception("内部顺序错误,不应该出现,请联系作者"); - } - - var next = source; - source = null; - next.TrySetResult(item); - } - } - } - - public new void Enqueue(T item) - { - lock (_innerLock) - { - base.Enqueue(item); - } - } - - public void Flush() - { - lock (_innerLock) - { - if (Count > 0) - { - var res = Dequeue(); - var next = source; - source = null; - next?.TrySetResult(res); - } - } - } - - public virtual Task ReadAsync() - { - lock (_innerLock) - { - if (this.Count > 0) - { - var next = Dequeue(); - return Task.FromResult(next); - } - else - { - source = new TaskCompletionSource(); - return source.Task; - } - } - } - - public UniTask ReadValueTaskAsync() - { - throw new NotImplementedException(); - } - } - - public class KcpIO : KcpCore, IKcpIO - where Segment : IKcpSegment - { - OutputQ outq; - - public KcpIO(uint conv_) : base(conv_) - { - outq = new OutputQ(); - callbackHandle = outq; - } - - internal override void Parse_data(Segment newseg) - { - base.Parse_data(newseg); - - lock (rcv_queueLock) - { - var recover = false; - if (rcv_queue.Count >= rcv_wnd) - { - recover = true; - } - - while (TryRecv(out var arraySegment) > 0) - { - recvSignal.Enqueue(arraySegment); - } - - recvSignal.Flush(); - - #region fast recover - - /// fast recover - if (rcv_queue.Count < rcv_wnd && recover) - { - // ready to send back IKCP_CMD_WINS in ikcp_flush - // tell remote my window size - probe |= IKCP_ASK_TELL; - } - - #endregion - } - } - - QueuePipe> recvSignal = new QueuePipe>(); - - internal int TryRecv(out ArraySegment package) - { - package = default; - lock (rcv_queueLock) - { - var peekSize = -1; - if (rcv_queue.Count == 0) - { - ///没有可用包 - return -1; - } - - var seq = rcv_queue[0]; - - if (seq.frg == 0) - { - peekSize = (int)seq.len; - } - - if (rcv_queue.Count < seq.frg + 1) - { - ///没有足够的包 - return -1; - } - - uint length = 0; - - Segment[] kcpSegments = ArrayPool.Shared.Rent(seq.frg + 1); - - var index = 0; - foreach (var item in rcv_queue) - { - kcpSegments[index] = item; - index++; - length += item.len; - if (item.frg == 0) - { - break; - } - } - - if (index > 0) - { - rcv_queue.RemoveRange(0, index); - } - - package = new ArraySegment(kcpSegments, 0, index); - - peekSize = (int)length; - - if (peekSize <= 0) - { - return -2; - } - - return peekSize; - } - } - - public async UniTask RecvAsync(IBufferWriter writer, object options = null) - { - var arraySegment = await recvSignal.ReadAsync().ConfigureAwait(false); - for (int i = arraySegment.Offset; i < arraySegment.Count; i++) - { - WriteRecv(writer, arraySegment.Array[i]); - } - - ArrayPool.Shared.Return(arraySegment.Array, true); - } - - private void WriteRecv(IBufferWriter writer, Segment seg) - { - var curCount = (int)seg.len; - var target = writer.GetSpan(curCount); - seg.data.CopyTo(target); - SegmentManager.Free(seg); - writer.Advance(curCount); - } - - public async UniTask RecvAsync(ArraySegment buffer, object options = null) - { - var arraySegment = await recvSignal.ReadAsync().ConfigureAwait(false); - int start = buffer.Offset; - for (int i = arraySegment.Offset; i < arraySegment.Count; i++) - { - var target = new Memory(buffer.Array, start, buffer.Array.Length - start); - - var seg = arraySegment.Array[i]; - seg.data.CopyTo(target.Span); - start += seg.data.Length; - - SegmentManager.Free(seg); - } - - ArrayPool.Shared.Return(arraySegment.Array, true); - return start - buffer.Offset; - } - - public async UniTask OutputAsync(IBufferWriter writer, object options = null) - { - var (Owner, Count) = await outq.ReadAsync().ConfigureAwait(false); - WriteOut(writer, Owner, Count); - } - - private static void WriteOut(IBufferWriter writer, BufferOwner Owner, int Count) - { - var target = writer.GetSpan(Count); - Owner.Memory.Span.Slice(0, Count).CopyTo(target); - writer.Advance(Count); - Owner.Dispose(); - } - - protected internal override BufferOwner CreateBuffer(int needSize) - { - return MemoryPool.Shared.Rent(needSize); - } - - internal class OutputQ : QueuePipe<(BufferOwner Owner, int Count)>, - IKcpCallback - { - public void Output(BufferOwner buffer, int avalidLength) - { - Write((buffer, avalidLength)); - } - } - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpIO.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpIO.cs.meta deleted file mode 100644 index 5aa66275..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpIO.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3c30d30fa46372948b60bd56eec47fe6 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpOutputWriter.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpOutputWriter.cs deleted file mode 100644 index b850bdf3..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpOutputWriter.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System.Buffers; - -namespace System.Net.Sockets.Kcp -{ - public abstract class KcpOutputWriter : IKcpOutputWriter - { - public int UnflushedBytes { get; set; } - public IMemoryOwner MemoryOwner { get; set; } - public void Flush() - { - Output(MemoryOwner, UnflushedBytes); - MemoryOwner = null; - UnflushedBytes = 0; - } - - public void Advance(int count) - { - UnflushedBytes += count; - } - - public Memory GetMemory(int sizeHint = 0) - { - if (MemoryOwner == null) - { - MemoryOwner = MemoryPool.Shared.Rent(2048); - } - return MemoryOwner.Memory.Slice(UnflushedBytes); - } - - public Span GetSpan(int sizeHint = 0) - { - if (MemoryOwner == null) - { - MemoryOwner = MemoryPool.Shared.Rent(2048); - } - return MemoryOwner.Memory.Span.Slice(UnflushedBytes); - } - - /// - /// Socket发送是要pin byte[],为了不阻塞KcpFlush,动态缓存是必须的。 - /// - /// - /// - public abstract void Output(IMemoryOwner buffer, int avalidLength); - } -} - - - - diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpOutputWriter.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpOutputWriter.cs.meta deleted file mode 100644 index 0c610af5..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpOutputWriter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a058d8fa8a92dc94395bfd6e1f6fdb8f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpSegment.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpSegment.cs deleted file mode 100644 index 71402217..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpSegment.cs +++ /dev/null @@ -1,402 +0,0 @@ -using System.Buffers.Binary; -using System.Runtime.InteropServices; - -namespace System.Net.Sockets.Kcp -{ - /// - /// 调整了没存布局,直接拷贝块提升性能。 - /// 结构体保存内容只有一个指针,不用担心参数传递过程中的性能 - /// https://github.com/skywind3000/kcp/issues/118#issuecomment-338133930 - /// 不要对没有初始化的KcpSegment(内部指针为0,所有属性都将指向位置区域) 进行任何赋值操作,可能导致内存损坏。 - /// 出于性能考虑,没有对此项进行安全检查。 - /// - public struct KcpSegment : IKcpSegment - { - internal readonly unsafe byte* ptr; - public unsafe KcpSegment(byte* intPtr, uint appendDateSize) - { - this.ptr = intPtr; - len = appendDateSize; - } - - /// - /// 使用完必须显示释放,否则内存泄漏 - /// - /// - /// - public static KcpSegment AllocHGlobal(int appendDateSize) - { - var total = LocalOffset + HeadOffset + appendDateSize; - IntPtr intPtr = Marshal.AllocHGlobal(total); - unsafe - { - ///清零 不知道是不是有更快的清0方法? - Span span = new Span(intPtr.ToPointer(), total); - span.Clear(); - - return new KcpSegment((byte*)intPtr.ToPointer(), (uint)appendDateSize); - } - } - - /// - /// 释放非托管内存 - /// - /// - public static void FreeHGlobal(KcpSegment seg) - { - unsafe - { - Marshal.FreeHGlobal((IntPtr)seg.ptr); - } - } - - /// 以下为本机使用的参数 - /// - /// offset = 0 - /// - public uint resendts - { - get - { - unsafe - { - return *(uint*)(ptr + 0); - } - } - set - { - unsafe - { - *(uint*)(ptr + 0) = value; - } - } - } - - /// - /// offset = 4 - /// - public uint rto - { - get - { - unsafe - { - return *(uint*)(ptr + 4); - } - } - set - { - unsafe - { - *(uint*)(ptr + 4) = value; - } - } - } - - /// - /// offset = 8 - /// - public uint fastack - { - get - { - unsafe - { - return *(uint*)(ptr + 8); - } - } - set - { - unsafe - { - *(uint*)(ptr + 8) = value; - } - } - } - - /// - /// offset = 12 - /// - public uint xmit - { - get - { - unsafe - { - return *(uint*)(ptr + 12); - } - } - set - { - unsafe - { - *(uint*)(ptr + 12) = value; - } - } - } - - ///以下为需要网络传输的参数 - public const int LocalOffset = 4 * 4; - public const int HeadOffset = KcpConst.IKCP_OVERHEAD; - - /// - /// offset = - /// - /// https://github.com/skywind3000/kcp/issues/134 - public uint conv - { - get - { - unsafe - { - return *(uint*)(LocalOffset + 0 + ptr); - } - } - set - { - unsafe - { - *(uint*)(LocalOffset + 0 + ptr) = value; - } - } - } - - /// - /// offset = + 4 - /// - public byte cmd - { - get - { - unsafe - { - return *(LocalOffset + 4 + ptr); - } - } - set - { - unsafe - { - *(LocalOffset + 4 + ptr) = value; - } - } - } - - /// - /// offset = + 5 - /// - public byte frg - { - get - { - unsafe - { - return *(LocalOffset + 5 + ptr); - } - } - set - { - unsafe - { - *(LocalOffset + 5 + ptr) = value; - } - } - } - - /// - /// offset = + 6 - /// - public ushort wnd - { - get - { - unsafe - { - return *(ushort*)(LocalOffset + 6 + ptr); - } - } - set - { - unsafe - { - *(ushort*)(LocalOffset + 6 + ptr) = value; - } - } - } - - /// - /// offset = + 8 - /// - public uint ts - { - get - { - unsafe - { - return *(uint*)(LocalOffset + 8 + ptr); - } - } - set - { - unsafe - { - *(uint*)(LocalOffset + 8 + ptr) = value; - } - } - } - - /// - /// SendNumber? - /// offset = + 12 - /// - public uint sn - { - get - { - unsafe - { - return *(uint*)(LocalOffset + 12 + ptr); - } - } - set - { - unsafe - { - *(uint*)(LocalOffset + 12 + ptr) = value; - } - } - } - - /// - /// offset = + 16 - /// - public uint una - { - get - { - unsafe - { - return *(uint*)(LocalOffset + 16 + ptr); - } - } - set - { - unsafe - { - *(uint*)(LocalOffset + 16 + ptr) = value; - } - } - } - - /// - /// AppendDateSize - /// offset = + 20 - /// - public uint len - { - get - { - unsafe - { - return *(uint*)(LocalOffset + 20 + ptr); - } - } - private set - { - unsafe - { - *(uint*)(LocalOffset + 20 + ptr) = value; - } - } - } - - /// - /// - /// - /// https://github.com/skywind3000/kcp/issues/35#issuecomment-263770736 - public Span data - { - get - { - unsafe - { - return new Span(LocalOffset + HeadOffset + ptr, (int)len); - } - } - } - - - - /// - /// 将片段中的要发送的数据拷贝到指定缓冲区 - /// - /// - /// - public int Encode(Span buffer) - { - var datelen = (int)(HeadOffset + len); - - ///备用偏移值 现阶段没有使用 - const int offset = 0; - - if (KcpConst.IsLittleEndian) - { - if (BitConverter.IsLittleEndian) - { - ///小端可以一次拷贝 - unsafe - { - ///要发送的数据从LocalOffset开始。 - ///本结构体调整了要发送字段和单机使用字段的位置,让报头数据和数据连续,节约一次拷贝。 - Span sendDate = new Span(ptr + LocalOffset, datelen); - sendDate.CopyTo(buffer); - } - } - else - { - BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset), conv); - buffer[offset + 4] = cmd; - buffer[offset + 5] = frg; - BinaryPrimitives.WriteUInt16LittleEndian(buffer.Slice(offset + 6), wnd); - - BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset + 8), ts); - BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset + 12), sn); - BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset + 16), una); - BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset + 20), len); - - data.CopyTo(buffer.Slice(HeadOffset)); - } - } - else - { - if (BitConverter.IsLittleEndian) - { - BinaryPrimitives.WriteUInt32BigEndian(buffer.Slice(offset), conv); - buffer[offset + 4] = cmd; - buffer[offset + 5] = frg; - BinaryPrimitives.WriteUInt16BigEndian(buffer.Slice(offset + 6), wnd); - - BinaryPrimitives.WriteUInt32BigEndian(buffer.Slice(offset + 8), ts); - BinaryPrimitives.WriteUInt32BigEndian(buffer.Slice(offset + 12), sn); - BinaryPrimitives.WriteUInt32BigEndian(buffer.Slice(offset + 16), una); - BinaryPrimitives.WriteUInt32BigEndian(buffer.Slice(offset + 20), len); - - data.CopyTo(buffer.Slice(HeadOffset)); - } - else - { - ///大端可以一次拷贝 - unsafe - { - ///要发送的数据从LocalOffset开始。 - ///本结构体调整了要发送字段和单机使用字段的位置,让报头数据和数据连续,节约一次拷贝。 - Span sendDate = new Span(ptr + LocalOffset, datelen); - sendDate.CopyTo(buffer); - } - } - } - - return datelen; - } - } -} diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpSegment.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpSegment.cs.meta deleted file mode 100644 index 2e5b4568..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpSegment.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: daab08fc1f00355429c23a1e36993942 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpTrace.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpTrace.cs deleted file mode 100644 index f288cb52..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpTrace.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace System.Net.Sockets.Kcp -{ - public partial class KcpCore - { - public KcpLogMask LogMask { get; set; } = KcpLogMask.IKCP_LOG_PARSE_DATA | KcpLogMask.IKCP_LOG_NEED_SEND | KcpLogMask.IKCP_LOG_DEAD_LINK; - - public virtual bool CanLog(KcpLogMask mask) - { - if ((mask & LogMask) == 0) - { - return false; - } - -#if NETSTANDARD2_0_OR_GREATER || NET5_0_OR_GREATER - if (TraceListener != null) - { - return true; - } -#endif - return false; - } - -#if NETSTANDARD2_0_OR_GREATER || NET5_0_OR_GREATER - public System.Diagnostics.TraceListener TraceListener { get; set; } -#endif - - public virtual void LogFail(string message) - { -#if NETSTANDARD2_0_OR_GREATER || NET5_0_OR_GREATER - TraceListener?.Fail(message); -#endif - } - - public virtual void LogWriteLine(string message, string category) - { -#if NETSTANDARD2_0_OR_GREATER || NET5_0_OR_GREATER - TraceListener?.WriteLine(message, category); -#endif - } - - [Obsolete("一定要先判断CanLog 内部判断是否存在TraceListener,避免在没有TraceListener时生成字符串", true)] - public virtual void LogWriteLine(string message, KcpLogMask mask) - { -#if NETSTANDARD2_0_OR_GREATER || NET5_0_OR_GREATER - if (CanLog(mask)) - { - LogWriteLine(message, mask.ToString()); - } -#endif - } - } - - [Flags] - public enum KcpLogMask - { - IKCP_LOG_OUTPUT = 1 << 0, - IKCP_LOG_INPUT = 1 << 1, - IKCP_LOG_SEND = 1 << 2, - IKCP_LOG_RECV = 1 << 3, - IKCP_LOG_IN_DATA = 1 << 4, - IKCP_LOG_IN_ACK = 1 << 5, - IKCP_LOG_IN_PROBE = 1 << 6, - IKCP_LOG_IN_WINS = 1 << 7, - IKCP_LOG_OUT_DATA = 1 << 8, - IKCP_LOG_OUT_ACK = 1 << 9, - IKCP_LOG_OUT_PROBE = 1 << 10, - IKCP_LOG_OUT_WINS = 1 << 11, - - IKCP_LOG_PARSE_DATA = 1 << 12, - IKCP_LOG_NEED_SEND = 1 << 13, - IKCP_LOG_DEAD_LINK = 1 << 14, - } -} - - diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpTrace.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpTrace.cs.meta deleted file mode 100644 index 3841d0aa..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/KcpTrace.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 39791b0c45bf4864e87385c477d9b50c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SegManager.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SegManager.cs deleted file mode 100644 index c18a22d7..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SegManager.cs +++ /dev/null @@ -1,265 +0,0 @@ -using System.Runtime.InteropServices; -using System.Collections.Generic; -using System.Collections.Concurrent; -using System.Buffers.Binary; - -namespace System.Net.Sockets.Kcp -{ - /// - /// 动态申请非托管内存 - /// - public class SimpleSegManager : ISegmentManager - { - public static SimpleSegManager Default { get; } = new SimpleSegManager(); - public KcpSegment Alloc(int appendDateSize) - { - return KcpSegment.AllocHGlobal(appendDateSize); - } - - public void Free(KcpSegment seg) - { - KcpSegment.FreeHGlobal(seg); - } - - public class Kcp : Kcp - { - public Kcp(uint conv_, IKcpCallback callback, IRentable rentable = null) - : base(conv_, callback, rentable) - { - SegmentManager = Default; - } - } - - public class KcpIO : KcpIO - { - public KcpIO(uint conv_) - : base(conv_) - { - SegmentManager = Default; - } - } - } - - /// - /// 申请固定大小非托管内存。使用这个就不能SetMtu了,大小已经写死。 - /// - /// 需要大量测试 - public unsafe class UnSafeSegManager : ISegmentManager - { - public static UnSafeSegManager Default { get; } = new UnSafeSegManager(); - /// - /// 因为默认mtu是1400,并且内存需要内存行/内存页对齐。这里直接512对齐。 - /// - public const int blockSize = 512 * 3; - public HashSet header = new HashSet(); - public Stack blocks = new Stack(); - public readonly object locker = new object(); - public UnSafeSegManager() - { - Alloc(); - } - - void Alloc() - { - int count = 50; - IntPtr intPtr = Marshal.AllocHGlobal(blockSize * count); - header.Add(intPtr); - for (int i = 0; i < count; i++) - { - blocks.Push(intPtr + blockSize * i); - } - } - - ~UnSafeSegManager() - { - foreach (var item in header) - { - Marshal.FreeHGlobal(item); - } - } - - public KcpSegment Alloc(int appendDateSize) - { - lock (locker) - { - var total = KcpSegment.LocalOffset + KcpSegment.HeadOffset + appendDateSize; - if (total > blockSize) - { - throw new ArgumentOutOfRangeException(); - } - - if (blocks.Count > 0) - { - - } - else - { - Alloc(); - } - - var ptr = blocks.Pop(); - Span span = new Span(ptr.ToPointer(), blockSize); - span.Clear(); - return new KcpSegment((byte*)ptr.ToPointer(), (uint)appendDateSize); - } - } - - public void Free(KcpSegment seg) - { - IntPtr ptr = (IntPtr)seg.ptr; - blocks.Push(ptr); - } - - public class Kcp : Kcp - { - public Kcp(uint conv_, IKcpCallback callback, IRentable rentable = null) - : base(conv_, callback, rentable) - { - SegmentManager = Default; - } - } - - public class KcpIO : KcpIO - { - public KcpIO(uint conv_) - : base(conv_) - { - SegmentManager = Default; - } - } - } - - - /// - /// 使用内存池,而不是非托管内存,有内存alloc,但是不多。可以解决Marshal.AllocHGlobal 内核调用带来的性能问题 - /// - public class PoolSegManager : ISegmentManager - { - public static PoolSegManager Default { get; } = new PoolSegManager(); - - /// - /// 因为默认mtu是1400,并且内存需要内存行/内存页对齐。这里直接512对齐。 - /// - public const int blockSize = 512 * 3; - public class Seg : IKcpSegment - { - byte[] cache; - public Seg(int blockSize) - { - cache = Buffers.ArrayPool.Shared.Rent(blockSize); - } - - ///以下为需要网络传输的参数 - public const int LocalOffset = 4 * 4; - public const int HeadOffset = Kcp.IKCP_OVERHEAD; - - public byte cmd { get; set; } - public uint conv { get; set; } - public Span data => cache.AsSpan().Slice(0, (int)len); - public uint fastack { get; set; } - public byte frg { get; set; } - public uint len { get; internal set; } - public uint resendts { get; set; } - public uint rto { get; set; } - public uint sn { get; set; } - public uint ts { get; set; } - public uint una { get; set; } - public ushort wnd { get; set; } - public uint xmit { get; set; } - - public int Encode(Span buffer) - { - var datelen = (int)(HeadOffset + len); - - ///备用偏移值 现阶段没有使用 - const int offset = 0; - - if (BitConverter.IsLittleEndian) - { - BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset), conv); - buffer[offset + 4] = cmd; - buffer[offset + 5] = frg; - BinaryPrimitives.WriteUInt16LittleEndian(buffer.Slice(offset + 6), wnd); - - BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset + 8), ts); - BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset + 12), sn); - BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset + 16), una); - BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset + 20), len); - - data.CopyTo(buffer.Slice(HeadOffset)); - } - else - { - BinaryPrimitives.WriteUInt32BigEndian(buffer.Slice(offset), conv); - buffer[offset + 4] = cmd; - buffer[offset + 5] = frg; - BinaryPrimitives.WriteUInt16BigEndian(buffer.Slice(offset + 6), wnd); - - BinaryPrimitives.WriteUInt32BigEndian(buffer.Slice(offset + 8), ts); - BinaryPrimitives.WriteUInt32BigEndian(buffer.Slice(offset + 12), sn); - BinaryPrimitives.WriteUInt32BigEndian(buffer.Slice(offset + 16), una); - BinaryPrimitives.WriteUInt32BigEndian(buffer.Slice(offset + 20), len); - - data.CopyTo(buffer.Slice(HeadOffset)); - } - - return datelen; - } - } - ConcurrentStack Pool = new ConcurrentStack(); - public Seg Alloc(int appendDateSize) - { - if (appendDateSize > blockSize) - { - throw new NotSupportedException(); - } - if (Pool.TryPop(out var ret)) - { - } - else - { - ret = new Seg(blockSize); - } - ret.len = (uint)appendDateSize; - return ret; - } - - public void Free(Seg seg) - { - seg.cmd = 0; - seg.conv = 0; - seg.fastack = 0; - seg.frg = 0; - seg.len = 0; - seg.resendts = 0; - seg.rto = 0; - seg.sn = 0; - seg.ts = 0; - seg.una = 0; - seg.wnd = 0; - seg.xmit = 0; - Pool.Push(seg); - } - - public class Kcp : Kcp - { - public Kcp(uint conv_, IKcpCallback callback, IRentable rentable = null) - : base(conv_, callback, rentable) - { - SegmentManager = Default; - } - } - - public class KcpIO : KcpIO - { - public KcpIO(uint conv_) - : base(conv_) - { - SegmentManager = Default; - } - } - } -} - - - diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SegManager.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SegManager.cs.meta deleted file mode 100644 index 0d200168..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SegManager.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e7f0d71aa1362b6488c3173d525fd284 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SimpleKcpClient.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SimpleKcpClient.cs deleted file mode 100644 index c6663630..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SimpleKcpClient.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System.Buffers; -using System.Threading.Tasks; -using Cysharp.Threading.Tasks; - -namespace System.Net.Sockets.Kcp.Simple -{ - /// - /// 简单例子。 - /// - public class SimpleKcpClient : IKcpCallback - { - UdpClient client; - - public SimpleKcpClient(int port) - : this(port, null) - { - - } - - public SimpleKcpClient(int port, IPEndPoint endPoint) - { - client = new UdpClient(port); - kcp = new SimpleSegManager.Kcp(2001, this); - this.EndPoint = endPoint; - BeginRecv(); - } - - public SimpleSegManager.Kcp kcp { get; } - public IPEndPoint EndPoint { get; set; } - - public void Output(IMemoryOwner buffer, int avalidLength) - { - var s = buffer.Memory.Span.Slice(0, avalidLength).ToArray(); - client.SendAsync(s, s.Length, EndPoint); - buffer.Dispose(); - } - - public void SendAsync(byte[] datagram, int bytes) - { - kcp.Send(datagram.AsSpan().Slice(0, bytes)); - } - - public async UniTask ReceiveAsync() - { - var (buffer, avalidLength) = kcp.TryRecv(); - while (buffer == null) - { - await Task.Delay(10); - (buffer, avalidLength) = kcp.TryRecv(); - } - - var s = buffer.Memory.Span.Slice(0, avalidLength).ToArray(); - return s; - } - - private async void BeginRecv() - { - var res = await client.ReceiveAsync(); - EndPoint = res.RemoteEndPoint; - kcp.Input(res.Buffer); - BeginRecv(); - } - } -} - diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SimpleKcpClient.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SimpleKcpClient.cs.meta deleted file mode 100644 index 530afc3c..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SimpleKcpClient.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ff16ed9b89525df4aa6501c0edc679d5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SimpleKcpServer.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SimpleKcpServer.cs deleted file mode 100644 index e1ad21f1..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SimpleKcpServer.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System.Net.Sockets.Kcp.Simple; -using System.Threading.Tasks; - -namespace System.Net.Sockets.Kcp -{ - namespace TestServer - { - /// - /// 简单例子。 - /// - class SimpleKcpServer - { - static void Main(string[] args) - { - Console.WriteLine("Hello World!"); - - SimpleKcpClient kcpClient = new SimpleKcpClient(40001); - Task.Run(async () => - { - while (true) - { - kcpClient.kcp.Update(DateTimeOffset.UtcNow); - await Task.Delay(10); - } - }); - - StartRecv(kcpClient); - Console.ReadLine(); - } - - static async void StartRecv(SimpleKcpClient client) - { - while (true) - { - var res = await client.ReceiveAsync(); - var str = System.Text.Encoding.UTF8.GetString(res); - if ("发送一条消息" == str) - { - Console.WriteLine(str); - - var buffer = System.Text.Encoding.UTF8.GetBytes("回复一条消息"); - client.SendAsync(buffer, buffer.Length); - } - } - } - } - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SimpleKcpServer.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SimpleKcpServer.cs.meta deleted file mode 100644 index 878b81d5..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/SimpleKcpServer.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 97e221b7388e412da59b0f4d200cb891 -timeCreated: 1682095200 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/Utility.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/Utility.cs deleted file mode 100644 index 601a862f..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/Utility.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Text; - -//[assembly: InternalsVisibleTo("UnitTestProject1")] - -namespace System.Net.Sockets.Kcp -{ - public static class KcpExtension_FDF71D0BC31D49C48EEA8FAA51F017D4 - { - private static readonly DateTime utc_time = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - [Obsolete("", true)] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static uint ConvertTime(this in DateTime time) - { - return (uint)(Convert.ToInt64(time.Subtract(utc_time).TotalMilliseconds) & 0xffffffff); - } - - private static readonly DateTimeOffset utc1970 = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static uint ConvertTimeOld(this in DateTimeOffset time) - { - return (uint)(Convert.ToInt64(time.Subtract(utc1970).TotalMilliseconds) & 0xffffffff); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static uint ConvertTime2(this in DateTimeOffset time) - { -#if NETSTANDARD2_0_OR_GREATER || NET5_0_OR_GREATER - return (uint)(time.ToUnixTimeMilliseconds() & 0xffffffff); -#else - return (uint)(Convert.ToInt64(time.Subtract(utc1970).TotalMilliseconds) & 0xffffffff); -#endif - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static uint ConvertTime(this in DateTimeOffset time) - { -#if NETSTANDARD2_0_OR_GREATER || NET5_0_OR_GREATER - return (uint)(time.ToUnixTimeMilliseconds()); -#else - return (uint)(Convert.ToInt64(time.Subtract(utc1970).TotalMilliseconds) & 0xffffffff); -#endif - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static string ToLogString(this T segment, bool local = false) - where T : IKcpSegment - { - if (local) - { - return $"sn:{segment.sn,2} una:{segment.una,2} frg:{segment.frg,2} cmd:{segment.cmd,2} len:{segment.len,2} wnd:{segment.wnd} [ LocalValue: xmit:{segment.xmit} fastack:{segment.fastack} rto:{segment.rto} ]"; - } - else - { - return $"sn:{segment.sn,2} una:{segment.una,2} frg:{segment.frg,2} cmd:{segment.cmd,2} len:{segment.len,2} wnd:{segment.wnd}"; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int Encode(this T Seg, IBufferWriter writer) - where T : IKcpSegment - { - var totalLength = (int)(KcpSegment.HeadOffset + Seg.len); - var span = writer.GetSpan(totalLength); - Seg.Encode(span); - writer.Advance(totalLength); - return totalLength; - } - } -} diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/Utility.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/Utility.cs.meta deleted file mode 100644 index be197e63..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/Core/Utility.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: cd298c4aa310a7e448c4694ddc41337e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/NetworkManager.KcpNetworkChannel.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/NetworkManager.KcpNetworkChannel.cs deleted file mode 100644 index 3ceb6f04..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/NetworkManager.KcpNetworkChannel.cs +++ /dev/null @@ -1,287 +0,0 @@ -using System; -using System.Net; -using System.Net.Sockets; - -namespace TEngine -{ - internal sealed partial class NetworkManager - { - /// - /// Kcp 网络频道。 - /// - private sealed class KcpNetworkChannel : NetworkChannelBase - { - private readonly AsyncCallback _connectCallback; - private readonly AsyncCallback _sendCallback; - private readonly AsyncCallback _receiveCallback; - - /// - /// 获取网络服务类型。 - /// - public override ServiceType ServiceType => ServiceType.Kcp; - - - public KcpNetworkChannel(string name, INetworkChannelHelper networkChannelHelper) - : base(name, networkChannelHelper) - { - _connectCallback = ConnectCallback; - _sendCallback = SendCallback; - _receiveCallback = ReceiveCallback; - } - - - /// - /// 连接到远程主机。 - /// - /// 远程主机的 IP 地址。 - /// 远程主机的端口号。 - /// 用户自定义数据。 - public override void Connect(IPAddress ipAddress, int port, object userData) - { - base.Connect(ipAddress, port, userData); - MSocket = new Socket(ipAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); - if (MSocket == null) - { - string errorMessage = "Initialize network channel failure."; - if (NetworkChannelError != null) - { - NetworkChannelError(this, NetworkErrorCode.SocketError, SocketError.Success, errorMessage); - return; - } - - throw new GameFrameworkException(errorMessage); - } - - NetworkChannelHelper.PrepareForConnecting(); - ConnectAsync(ipAddress, port, userData); - } - - private void ConnectAsync(IPAddress ipAddress, int port, object userData) - { - try - { - MSocket.BeginConnect(ipAddress, port, _connectCallback, new ConnectState(MSocket, userData)); - } - catch (Exception exception) - { - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.ConnectError, - socketException?.SocketErrorCode ?? SocketError.Success, - exception.ToString()); - return; - } - - throw; - } - } - - protected override bool ProcessSend() - { - if (base.ProcessSend()) - { - SendAsync(); - return true; - } - - return false; - } - - private void ConnectCallback(IAsyncResult ar) - { - ConnectState socketUserData = (ConnectState)ar.AsyncState; - try - { - socketUserData.Socket.EndConnect(ar); - } - catch (ObjectDisposedException) - { - return; - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.ConnectError, - socketException?.SocketErrorCode ?? SocketError.Success, - exception.ToString()); - return; - } - - throw; - } - - MSentPacketCount = 0; - MReceivedPacketCount = 0; - - lock (SendPacketPool) - { - SendPacketPool.Clear(); - } - - lock (MHeartBeatState) - { - MHeartBeatState.Reset(true); - } - - if (NetworkChannelConnected != null) - { - NetworkChannelConnected(this, socketUserData.UserData); - } - - Active = true; - ReceiveAsync(); - } - - private void SendAsync() - { - try - { - MSocket.BeginSend(MSendState.Stream.GetBuffer(), (int)MSendState.Stream.Position, - (int)(MSendState.Stream.Length - MSendState.Stream.Position), SocketFlags.None, _sendCallback, - MSocket); - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.SendError, - socketException?.SocketErrorCode ?? SocketError.Success, - exception.ToString()); - return; - } - - throw; - } - } - - private void SendCallback(IAsyncResult ar) - { - Socket socket = (Socket)ar.AsyncState; - if (!socket.Connected) - { - return; - } - - int bytesSent = 0; - try - { - bytesSent = socket.EndSend(ar); - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.SendError, - socketException?.SocketErrorCode ?? SocketError.Success, - exception.ToString()); - return; - } - - throw; - } - - MSendState.Stream.Position += bytesSent; - if (MSendState.Stream.Position < MSendState.Stream.Length) - { - SendAsync(); - return; - } - - MSentPacketCount++; - MSendState.Reset(); - } - - private void ReceiveAsync() - { - try - { - MSocket.BeginReceive(MReceiveState.Stream.GetBuffer(), (int)MReceiveState.Stream.Position, - (int)(MReceiveState.Stream.Length - MReceiveState.Stream.Position), SocketFlags.None, - _receiveCallback, MSocket); - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.ReceiveError, - socketException?.SocketErrorCode ?? SocketError.Success, - exception.ToString()); - return; - } - - throw; - } - } - - private void ReceiveCallback(IAsyncResult ar) - { - Socket socket = (Socket)ar.AsyncState; - if (!socket.Connected) - { - return; - } - - int bytesReceived = 0; - try - { - bytesReceived = socket.EndReceive(ar); - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.ReceiveError, - socketException?.SocketErrorCode ?? SocketError.Success, - exception.ToString()); - return; - } - - throw; - } - - if (bytesReceived <= 0) - { - Close(); - return; - } - - MReceiveState.Stream.Position += bytesReceived; - if (MReceiveState.Stream.Position < MReceiveState.Stream.Length) - { - ReceiveAsync(); - return; - } - - MReceiveState.Stream.Position = 0L; - - bool processSuccess = false; - if (MReceiveState.PacketHeader != null) - { - processSuccess = ProcessPacket(); - MReceivedPacketCount++; - } - else - { - processSuccess = ProcessPacketHeader(); - } - - if (processSuccess) - { - ReceiveAsync(); - } - } - } - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/NetworkManager.KcpNetworkChannel.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/NetworkManager.KcpNetworkChannel.cs.meta deleted file mode 100644 index 95769a57..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Kcp/NetworkManager.KcpNetworkChannel.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 70ff4fca885c401ea776223622deab75 -timeCreated: 1682092071 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetUtil.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetUtil.cs deleted file mode 100644 index 9af05c04..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetUtil.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System.Net; -using System.Net.Sockets; - -namespace TEngine -{ - public class NetUtil - { - public static bool IsHaveIpV6Address(IPAddress[] ipAddresses, ref IPAddress[] outIPs) - { - int v6Count = 0; - for (int i = 0; i < ipAddresses.Length; i++) - { - if (System.Net.Sockets.AddressFamily.InterNetworkV6.Equals(ipAddresses[i].AddressFamily)) - { - v6Count++; - } - } - - if (v6Count > 0) - { - outIPs = new IPAddress[v6Count]; - int resIndex = 0; - for (int i = 0; i < ipAddresses.Length; i++) - { - if (System.Net.Sockets.AddressFamily.InterNetworkV6.Equals(ipAddresses[i].AddressFamily)) - { - outIPs[resIndex++] = ipAddresses[i]; - } - } - - return true; - } - - return false; - } - - public static IPEndPoint GetEndPoint(string server, int port) - { - IPAddress[] ps = Dns.GetHostAddresses(server); - IPAddress[] finalIps = ps; - if (Socket.OSSupportsIPv6 && NetUtil.IsHaveIpV6Address(ps, ref finalIps)) - { - Log.Error("socket use addr ipV6: {0}, IP count:{1} AddressFamily[{2}]", server, finalIps.Length, finalIps[0].AddressFamily); - } - - if (finalIps.Length > 0) - { - return new IPEndPoint(finalIps[0], port); - } - - return null; - } - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetUtil.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetUtil.cs.meta deleted file mode 100644 index 588ccde7..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetUtil.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 26846cca9e0f4d3c965d58882c1b503e -timeCreated: 1681991073 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Network.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Network.cs deleted file mode 100644 index 700184e8..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Network.cs +++ /dev/null @@ -1,144 +0,0 @@ -using System.Collections.Generic; -using System.Net.Sockets; -using GameBase; -using UnityEngine; - -namespace TEngine -{ - /// - /// 网络组件。 - /// - [DisallowMultipleComponent] - public sealed class Network : UnitySingleton - { - private NetworkManager m_NetworkManager = null; - - /// - /// 获取网络频道数量。 - /// - public int NetworkChannelCount => m_NetworkManager.NetworkChannelCount; - - /// - /// 游戏框架组件初始化。 - /// - public override void Awake() - { - base.Awake(); - - // m_NetworkManager = GameFrameworkEntry.GetModule(); - m_NetworkManager = new NetworkManager(); - if (m_NetworkManager == null) - { - Log.Fatal("Network manager is invalid."); - return; - } - - m_NetworkManager.NetworkConnected += OnNetworkConnected; - m_NetworkManager.NetworkClosed += OnNetworkClosed; - m_NetworkManager.NetworkMissHeartBeat += OnNetworkMissHeartBeat; - m_NetworkManager.NetworkError += OnNetworkError; - m_NetworkManager.NetworkCustomError += OnNetworkCustomError; - } - - private void Update() - { - m_NetworkManager.Update(GameTime.deltaTime, GameTime.unscaledDeltaTime); - } - - /// - /// 检查是否存在网络频道。 - /// - /// 网络频道名称。 - /// 是否存在网络频道。 - public bool HasNetworkChannel(string name) - { - return m_NetworkManager.HasNetworkChannel(name); - } - - /// - /// 获取网络频道。 - /// - /// 网络频道名称。 - /// 要获取的网络频道。 - public INetworkChannel GetNetworkChannel(string name) - { - return m_NetworkManager.GetNetworkChannel(name); - } - - /// - /// 获取所有网络频道。 - /// - /// 所有网络频道。 - public INetworkChannel[] StaticGetAllNetworkChannels() - { - return m_NetworkManager.GetAllNetworkChannels(); - } - - /// - /// 获取所有网络频道。 - /// - /// 所有网络频道。 - public INetworkChannel[] GetAllNetworkChannels() - { - return m_NetworkManager.GetAllNetworkChannels(); - } - - /// - /// 获取所有网络频道。 - /// - /// 所有网络频道。 - public void GetAllNetworkChannels(List results) - { - m_NetworkManager.GetAllNetworkChannels(results); - } - - /// - /// 创建网络频道。 - /// - /// 网络频道名称。 - /// 网络服务类型。 - /// 网络频道辅助器。 - /// 要创建的网络频道。 - public INetworkChannel CreateNetworkChannel(string name, ServiceType serviceType, - INetworkChannelHelper networkChannelHelper) - { - return m_NetworkManager.CreateNetworkChannel(name, serviceType, networkChannelHelper); - } - - /// - /// 销毁网络频道。 - /// - /// 网络频道名称。 - /// 是否销毁网络频道成功。 - public bool DestroyNetworkChannel(string channelName) - { - return m_NetworkManager.DestroyNetworkChannel(channelName); - } - - private void OnNetworkConnected(INetworkChannel channel, object userdata) - { - GameEvent.Send(NetworkEvent.NetworkConnectedEvent, channel, userdata); - } - - private void OnNetworkClosed(INetworkChannel channel) - { - GameEvent.Send(NetworkEvent.NetworkClosedEvent, channel); - } - - private void OnNetworkMissHeartBeat(INetworkChannel channel, int missCount) - { - GameEvent.Send(NetworkEvent.NetworkMissHeartBeatEvent, channel, missCount); - } - - private void OnNetworkError(INetworkChannel channel, NetworkErrorCode networkErrorCode, SocketError socketError, - string errorMessage) - { - GameEvent.Send(NetworkEvent.NetworkErrorEvent, channel, networkErrorCode, socketError, errorMessage); - } - - private void OnNetworkCustomError(INetworkChannel channel, object userData) - { - GameEvent.Send(NetworkEvent.NetworkCustomErrorEvent, channel, userData); - } - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Network.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Network.cs.meta deleted file mode 100644 index ec73e25c..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/Network.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 8edbc7d090fd4bb1ad2c6aa967ff0b76 -timeCreated: 1682044812 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkErrorCode.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkErrorCode.cs deleted file mode 100644 index de374509..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkErrorCode.cs +++ /dev/null @@ -1,53 +0,0 @@ -namespace TEngine -{ - /// - /// 网络错误码。 - /// - public enum NetworkErrorCode : byte - { - /// - /// 未知错误。 - /// - Unknown = 0, - - /// - /// 地址族错误。 - /// - AddressFamilyError, - - /// - /// Socket 错误。 - /// - SocketError, - - /// - /// 连接错误。 - /// - ConnectError, - - /// - /// 发送错误。 - /// - SendError, - - /// - /// 接收错误。 - /// - ReceiveError, - - /// - /// 序列化错误。 - /// - SerializeError, - - /// - /// 反序列化消息包头错误。 - /// - DeserializePacketHeaderError, - - /// - /// 反序列化消息包错误。 - /// - DeserializePacketError - } -} diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkErrorCode.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkErrorCode.cs.meta deleted file mode 100644 index 382bac9b..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkErrorCode.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 0bb8ca2ece7d49d28b1b4fd1bfa027e6 -timeCreated: 1681993877 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkEvent.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkEvent.cs deleted file mode 100644 index 4e7e02b1..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkEvent.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace TEngine -{ - public class NetworkEvent - { - /// - /// 网网络连接成功事件。 - /// - public static int NetworkConnectedEvent = StringId.StringToHash("NetworkEvent.NetworkConnectedEvent"); - - /// - /// 网络连接关闭事件。 - /// - public static int NetworkClosedEvent = StringId.StringToHash("NetworkEvent.NetworkClosedEvent"); - - /// - /// 网络错误事件。 - /// - public static int NetworkErrorEvent = StringId.StringToHash("NetworkEvent.NetworkErrorEvent"); - - /// - /// 用户自定义网络错误事件。 - /// - public static int NetworkCustomErrorEvent = StringId.StringToHash("NetworkEvent.NetworkCustomErrorEvent"); - - /// - /// 网络心跳包丢失事件。 - /// - public static int NetworkMissHeartBeatEvent = StringId.StringToHash("NetworkEvent.NetworkMissHeartBeatEvent"); - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkEvent.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkEvent.cs.meta deleted file mode 100644 index 3015a9a1..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkEvent.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 8e3b5eb5b76244498181c6117f0e0b1a -timeCreated: 1681993978 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.ConnectState.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.ConnectState.cs deleted file mode 100644 index ec88050e..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.ConnectState.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Net.Sockets; - -namespace TEngine -{ - internal sealed partial class NetworkManager - { - private sealed class ConnectState - { - private readonly Socket _socket; - private readonly object _userData; - - public ConnectState(Socket socket, object userData) - { - _socket = socket; - _userData = userData; - } - - public Socket Socket => _socket; - - public object UserData => _userData; - } - } -} diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.ConnectState.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.ConnectState.cs.meta deleted file mode 100644 index db4864bc..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.ConnectState.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 36ed7026c9b6441cb8a6438b2048d7f6 -timeCreated: 1681994450 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.HeartBeatState.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.HeartBeatState.cs deleted file mode 100644 index 7c74d2bc..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.HeartBeatState.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace TEngine -{ - internal sealed partial class NetworkManager - { - private sealed class HeartBeatState - { - private float _heartBeatElapseSeconds; - private int _missHeartBeatCount; - - public HeartBeatState() - { - _heartBeatElapseSeconds = 0f; - _missHeartBeatCount = 0; - } - - public float HeartBeatElapseSeconds - { - get => _heartBeatElapseSeconds; - set => _heartBeatElapseSeconds = value; - } - - public int MissHeartBeatCount - { - get => _missHeartBeatCount; - set => _missHeartBeatCount = value; - } - - public void Reset(bool resetHeartBeatElapseSeconds) - { - if (resetHeartBeatElapseSeconds) - { - _heartBeatElapseSeconds = 0f; - } - - _missHeartBeatCount = 0; - } - } - } -} diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.HeartBeatState.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.HeartBeatState.cs.meta deleted file mode 100644 index b6d8af6f..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.HeartBeatState.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 5368d77f60554db99e9c4d0862660442 -timeCreated: 1681994450 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.NetworkChannelBase.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.NetworkChannelBase.cs deleted file mode 100644 index 4509a54b..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.NetworkChannelBase.cs +++ /dev/null @@ -1,684 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.Sockets; -using GameProto; -using Google.Protobuf; - -namespace TEngine -{ - internal sealed partial class NetworkManager - { - /// - /// 网络频道基类。 - /// - private abstract class NetworkChannelBase : INetworkChannel, IDisposable - { - private const float DefaultHeartBeatInterval = 30f; - - private readonly string _name; - protected readonly Queue SendPacketPool; - protected readonly INetworkChannelHelper NetworkChannelHelper; - protected AddressFamily MAddressFamily; - protected bool MResetHeartBeatElapseSecondsWhenReceivePacket; - protected float MHeartBeatInterval; - protected Socket MSocket; - protected readonly SendState MSendState; - protected readonly ReceiveState MReceiveState; - protected readonly HeartBeatState MHeartBeatState; - protected int MSentPacketCount; - protected int MReceivedPacketCount; - protected bool Active; - private bool _disposed; - - public Action NetworkChannelConnected; - public Action NetworkChannelClosed; - public Action NetworkChannelMissHeartBeat; - public Action NetworkChannelError; - public Action NetworkChannelCustomError; - - /// - /// 消息注册Map。 - /// - private readonly Dictionary> _msgHandlerMap = new Dictionary>(); - - /// - /// 委托缓存堆栈。 - /// - private readonly Queue> _cacheHandlerQueue = new Queue>(); - - /// - /// 消息包缓存堆栈。 - /// - private readonly Queue _packsQueue = new Queue(); - - /// - /// 初始化网络频道基类的新实例。 - /// - /// 网络频道名称。 - /// 网络频道辅助器。 - public NetworkChannelBase(string name, INetworkChannelHelper networkChannelHelper) - { - _name = name ?? string.Empty; - SendPacketPool = new Queue(); - NetworkChannelHelper = networkChannelHelper; - MAddressFamily = AddressFamily.Unknown; - MResetHeartBeatElapseSecondsWhenReceivePacket = false; - MHeartBeatInterval = DefaultHeartBeatInterval; - MSocket = null; - MSendState = new SendState(); - MReceiveState = new ReceiveState(); - MHeartBeatState = new HeartBeatState(); - MSentPacketCount = 0; - MReceivedPacketCount = 0; - Active = false; - _disposed = false; - - NetworkChannelConnected = null; - NetworkChannelClosed = null; - NetworkChannelMissHeartBeat = null; - NetworkChannelError = null; - NetworkChannelCustomError = null; - - networkChannelHelper.Initialize(this); - } - - /// - /// 获取网络频道名称。 - /// - public string Name => _name; - - /// - /// 获取网络频道所使用的 Socket。 - /// - public Socket Socket => MSocket; - - /// - /// 获取是否已连接。 - /// - public bool Connected - { - get - { - if (MSocket != null) - { - return MSocket.Connected; - } - - return false; - } - } - - /// - /// 获取网络服务类型。 - /// - public abstract ServiceType ServiceType { get; } - - /// - /// 获取网络地址类型。 - /// - public AddressFamily AddressFamily => MAddressFamily; - - /// - /// 获取要发送的消息包数量。 - /// - public int SendPacketCount => SendPacketPool.Count; - - /// - /// 获取累计发送的消息包数量。 - /// - public int SentPacketCount => MSentPacketCount; - - /// - /// 获取已接收未处理的消息包数量。 - /// - public int ReceivePacketCount => _cacheHandlerQueue.Count; - - /// - /// 获取累计已接收的消息包数量。 - /// - public int ReceivedPacketCount => MReceivedPacketCount; - - /// - /// 获取或设置当收到消息包时是否重置心跳流逝时间。 - /// - public bool ResetHeartBeatElapseSecondsWhenReceivePacket - { - get => MResetHeartBeatElapseSecondsWhenReceivePacket; - set => MResetHeartBeatElapseSecondsWhenReceivePacket = value; - } - - /// - /// 获取丢失心跳的次数。 - /// - public int MissHeartBeatCount => MHeartBeatState.MissHeartBeatCount; - - /// - /// 获取或设置心跳间隔时长,以秒为单位。 - /// - public float HeartBeatInterval - { - get => MHeartBeatInterval; - set => MHeartBeatInterval = value; - } - - /// - /// 获取心跳等待时长,以秒为单位。 - /// - public float HeartBeatElapseSeconds => MHeartBeatState.HeartBeatElapseSeconds; - - /// - /// 网络频道轮询。 - /// - /// 逻辑流逝时间,以秒为单位。 - /// 真实流逝时间,以秒为单位。 - public virtual void Update(float elapseSeconds, float realElapseSeconds) - { - if (MSocket == null || !Active) - { - return; - } - - ProcessSend(); - ProcessReceive(); - if (MSocket == null || !Active) - { - return; - } - - HandleCsMsgOnUpdate(); - - if (MHeartBeatInterval > 0f) - { - bool sendHeartBeat = false; - int missHeartBeatCount = 0; - lock (MHeartBeatState) - { - if (MSocket == null || !Active) - { - return; - } - - MHeartBeatState.HeartBeatElapseSeconds += realElapseSeconds; - if (MHeartBeatState.HeartBeatElapseSeconds >= MHeartBeatInterval) - { - sendHeartBeat = true; - missHeartBeatCount = MHeartBeatState.MissHeartBeatCount; - MHeartBeatState.HeartBeatElapseSeconds = 0f; - MHeartBeatState.MissHeartBeatCount++; - } - } - - if (sendHeartBeat && NetworkChannelHelper.SendHeartBeat()) - { - if (missHeartBeatCount > 0 && NetworkChannelMissHeartBeat != null) - { - NetworkChannelMissHeartBeat(this, missHeartBeatCount); - } - } - } - } - - /// - /// 关闭网络频道。 - /// - public virtual void Shutdown() - { - Close(); - NetworkChannelHelper.Shutdown(); - } - - /// - /// 注册网络消息包处理函数。 - /// - /// 网络消息包id。 - /// 要注册的网络消息包处理函数。 - /// 是否检测重复。 - public void RegisterMsgHandler(int msgId, CsMsgDelegate msgDelegate,bool checkRepeat = true) - { - if (msgDelegate == null) - { - throw new GameFrameworkException("Msg handler is invalid."); - } - - lock (_msgHandlerMap) - { - if (!_msgHandlerMap.TryGetValue(msgId, out var listHandle)) - { - listHandle = new List(); - _msgHandlerMap[msgId] = listHandle; - } - - if (listHandle != null) - { - if (!listHandle.Contains(msgDelegate)) - { - listHandle.Add(msgDelegate); - } - else - { - if (checkRepeat) - { - Log.Error("-------------repeat RegCmdHandle MsgId:{0}-----------",msgId); - } - } - } - } - } - - /// - /// 移除网络消息包处理函数。 - /// - /// 网络消息包id。 - /// 要注册的网络消息包处理函数。 - public void RemoveMsgHandler(int msgId, CsMsgDelegate msgDelegate) - { - lock (_msgHandlerMap) - { - if (!_msgHandlerMap.TryGetValue(msgId, out List listHandle)) - { - return; - } - - if (listHandle != null) - { - listHandle.Remove(msgDelegate); - } - } - } - - /// - /// 连接到远程主机。 - /// - /// 远程主机的 IP 地址。 - /// 远程主机的端口号。 - public void Connect(string ipAddress, int port) - { - IPAddress address = IPAddress.Parse(ipAddress); - Connect(address, port, null); - } - - /// - /// 连接到远程主机。 - /// - /// 远程主机的 IP 地址。 - /// 远程主机的端口号。 - public void Connect(IPAddress ipAddress, int port) - { - Connect(ipAddress, port, null); - } - - /// - /// 连接到远程主机。 - /// - /// 远程主机的 IP 地址。 - /// 远程主机的端口号。 - /// 用户自定义数据。 - public virtual void Connect(IPAddress ipAddress, int port, object userData) - { - if (MSocket != null) - { - Close(); - MSocket = null; - } - - switch (ipAddress.AddressFamily) - { - case System.Net.Sockets.AddressFamily.InterNetwork: - MAddressFamily = AddressFamily.IPv4; - break; - - case System.Net.Sockets.AddressFamily.InterNetworkV6: - MAddressFamily = AddressFamily.IPv6; - break; - - default: - string errorMessage = Utility.Text.Format("Not supported address family '{0}'.", ipAddress.AddressFamily); - if (NetworkChannelError != null) - { - NetworkChannelError(this, NetworkErrorCode.AddressFamilyError, SocketError.Success, errorMessage); - return; - } - - throw new GameFrameworkException(errorMessage); - } - - MSendState.Reset(); - MReceiveState.PrepareForPacketHeader(NetworkChannelHelper.PacketHeaderLength); - } - - /// - /// 关闭连接并释放所有相关资源。 - /// - public void Close() - { - lock (this) - { - if (MSocket == null) - { - return; - } - - Active = false; - - try - { - MSocket.Shutdown(SocketShutdown.Both); - } - catch - { - // ignored - } - finally - { - MSocket.Close(); - MSocket = null; - - if (NetworkChannelClosed != null) - { - NetworkChannelClosed(this); - } - } - - MSentPacketCount = 0; - MReceivedPacketCount = 0; - - lock (SendPacketPool) - { - SendPacketPool.Clear(); - } - - lock (_packsQueue) - { - _packsQueue.Clear(); - } - - lock (_msgHandlerMap) - { - _msgHandlerMap.Clear(); - } - - lock (_cacheHandlerQueue) - { - _cacheHandlerQueue.Clear(); - } - - lock (MHeartBeatState) - { - MHeartBeatState.Reset(true); - } - } - } - - /// - /// 向远程主机发送消息包。 - /// - /// 要发送的消息包。 - public bool Send(CSPkg packet) - { - if (MSocket == null) - { - string errorMessage = "You must connect first."; - if (NetworkChannelError != null) - { - NetworkChannelError(this, NetworkErrorCode.SendError, SocketError.Success, errorMessage); - return false; - } - - throw new GameFrameworkException(errorMessage); - } - - if (!Active) - { - string errorMessage = "Socket is not active."; - if (NetworkChannelError != null) - { - NetworkChannelError(this, NetworkErrorCode.SendError, SocketError.Success, errorMessage); - return false; - } - - throw new GameFrameworkException(errorMessage); - } - - if (packet == null) - { - string errorMessage = "Packet is invalid."; - if (NetworkChannelError != null) - { - NetworkChannelError(this, NetworkErrorCode.SendError, SocketError.Success, errorMessage); - return false; - } - - throw new GameFrameworkException(errorMessage); - } - - lock (SendPacketPool) - { - SendPacketPool.Enqueue(packet); - } - return true; - } - - /// - /// 向远程主机发送消息包并注册消息回调。 - /// - /// 要发送的消息包。 - /// 要注册的回调。 - /// 是否需要等待UI。 - /// 消息包是否发送成功。 - public bool Send(CSPkg packet, CsMsgDelegate resHandler, bool needShowWaitUI = false) - { - RegisterMsgHandler((int)packet.Head.MsgId,resHandler,false); - return Send(packet); - } - - /// - /// 释放资源。 - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// 释放资源。 - /// - /// 释放资源标记。 - private void Dispose(bool disposing) - { - if (_disposed) - { - return; - } - - if (disposing) - { - Close(); - MSendState.Dispose(); - MReceiveState.Dispose(); - } - - _disposed = true; - } - - protected virtual bool ProcessSend() - { - if (MSendState.Stream.Length > 0 || SendPacketPool.Count <= 0) - { - return false; - } - - while (SendPacketPool.Count > 0) - { - CSPkg csPkg = null; - lock (SendPacketPool) - { - csPkg = SendPacketPool.Dequeue(); - } - - bool serializeResult = false; - try - { - serializeResult = NetworkChannelHelper.Serialize(csPkg, MSendState.Stream); - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.SerializeError, socketException?.SocketErrorCode ?? SocketError.Success, - exception.ToString()); - return false; - } - - throw; - } - - if (!serializeResult) - { - string errorMessage = "Serialized packet failure."; - if (NetworkChannelError != null) - { - NetworkChannelError(this, NetworkErrorCode.SerializeError, SocketError.Success, errorMessage); - return false; - } - - throw new GameFrameworkException(errorMessage); - } - } - - MSendState.Stream.Position = 0L; - return true; - } - - protected virtual void ProcessReceive() - { - } - - protected virtual bool ProcessPacketHeader() - { - try - { - IPacketHeader packetHeader = NetworkChannelHelper.DeserializePacketHeader(MReceiveState.Stream, out var customErrorData); - - if (customErrorData != null && NetworkChannelCustomError != null) - { - NetworkChannelCustomError(this, customErrorData); - } - - if (packetHeader == null) - { - string errorMessage = "Packet header is invalid."; - if (NetworkChannelError != null) - { - NetworkChannelError(this, NetworkErrorCode.DeserializePacketHeaderError, SocketError.Success, errorMessage); - return false; - } - - throw new GameFrameworkException(errorMessage); - } - - MReceiveState.PrepareForPacket(packetHeader); - if (packetHeader.PacketLength <= 0) - { - bool processSuccess = ProcessPacket(); - MReceivedPacketCount++; - return processSuccess; - } - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.DeserializePacketHeaderError, socketException?.SocketErrorCode ?? SocketError.Success, - exception.ToString()); - return false; - } - - throw; - } - - return true; - } - - protected virtual bool ProcessPacket() - { - lock (MHeartBeatState) - { - MHeartBeatState.Reset(MResetHeartBeatElapseSecondsWhenReceivePacket); - } - - try - { - CSPkg csPkg = NetworkChannelHelper.DeserializePacket(MReceiveState.PacketHeader, MReceiveState.Stream, out var customErrorData); - - if (customErrorData != null && NetworkChannelCustomError != null) - { - NetworkChannelCustomError(this, customErrorData); - } - - if (csPkg != null) - { - lock (_cacheHandlerQueue) - { - if (_msgHandlerMap.TryGetValue((int)csPkg.Head.MsgId, out var listHandle)) - { - _cacheHandlerQueue.Enqueue(listHandle); - - _packsQueue.Enqueue(csPkg); - } - } - } - - MReceiveState.PrepareForPacketHeader(NetworkChannelHelper.PacketHeaderLength); - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.DeserializePacketError, socketException?.SocketErrorCode ?? SocketError.Success, - exception.ToString()); - return false; - } - - throw; - } - return true; - } - - /// - /// 主线程从消息包缓存堆栈/委托缓存堆栈中出列。 - /// - private void HandleCsMsgOnUpdate() - { - if (_cacheHandlerQueue.Count <= 0 || _packsQueue.Count <= 0) - { - return; - } - try - { - foreach (CsMsgDelegate handle in _cacheHandlerQueue.Dequeue()) - { - var pack = _packsQueue.Peek(); - - if (pack != null) - { - handle(pack); - } - } - _packsQueue.Dequeue(); - } - catch (Exception e) - { - Log.Error(e.Message); - } - } - } - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.NetworkChannelBase.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.NetworkChannelBase.cs.meta deleted file mode 100644 index 88784748..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.NetworkChannelBase.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 399b677044924c6bb2a4e5d56628ca42 -timeCreated: 1681994450 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.ReceiveState.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.ReceiveState.cs deleted file mode 100644 index e24fd5fc..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.ReceiveState.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System; -using System.IO; - -namespace TEngine -{ - internal sealed partial class NetworkManager - { - private sealed class ReceiveState : IDisposable - { - private const int DefaultBufferLength = 1024 * 64; - private MemoryStream _stream; - private IPacketHeader _packetHeader; - private bool _disposed; - - public ReceiveState() - { - _stream = new MemoryStream(DefaultBufferLength); - _packetHeader = null; - _disposed = false; - } - - public MemoryStream Stream - { - get - { - return _stream; - } - } - - public IPacketHeader PacketHeader - { - get - { - return _packetHeader; - } - } - - public void PrepareForPacketHeader(int packetHeaderLength) - { - Reset(packetHeaderLength, null); - } - - public void PrepareForPacket(IPacketHeader packetHeader) - { - if (packetHeader == null) - { - throw new GameFrameworkException("Packet header is invalid."); - } - - Reset(packetHeader.PacketLength, packetHeader); - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - private void Dispose(bool disposing) - { - if (_disposed) - { - return; - } - - if (disposing) - { - if (_stream != null) - { - _stream.Dispose(); - _stream = null; - } - } - - _disposed = true; - } - - private void Reset(int targetLength, IPacketHeader packetHeader) - { - if (targetLength < 0) - { - throw new GameFrameworkException("Target length is invalid."); - } - - _stream.Position = 0L; - _stream.SetLength(targetLength); - _packetHeader = packetHeader; - } - } - } -} diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.ReceiveState.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.ReceiveState.cs.meta deleted file mode 100644 index 371a0f75..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.ReceiveState.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 89feb1bba2164efea12041106391c284 -timeCreated: 1681994450 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.SendState.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.SendState.cs deleted file mode 100644 index 58264efd..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.SendState.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; -using System.IO; - -namespace TEngine -{ - internal sealed partial class NetworkManager - { - private sealed class SendState : IDisposable - { - private const int DefaultBufferLength = 1024 * 64; - private MemoryStream _stream; - private bool _disposed; - - public SendState() - { - _stream = new MemoryStream(DefaultBufferLength); - _disposed = false; - } - - public MemoryStream Stream - { - get - { - return _stream; - } - } - - public void Reset() - { - _stream.Position = 0L; - _stream.SetLength(0L); - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - private void Dispose(bool disposing) - { - if (_disposed) - { - return; - } - - if (disposing) - { - if (_stream != null) - { - _stream.Dispose(); - _stream = null; - } - } - - _disposed = true; - } - } - } -} diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.SendState.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.SendState.cs.meta deleted file mode 100644 index 69f06ffa..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.SendState.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: df8ba0ec679b463e880f8f599ba23d77 -timeCreated: 1681994450 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.TcpNetworkChannel.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.TcpNetworkChannel.cs deleted file mode 100644 index 1582976d..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.TcpNetworkChannel.cs +++ /dev/null @@ -1,281 +0,0 @@ -using System; -using System.Net; -using System.Net.Sockets; - -namespace TEngine -{ - internal sealed partial class NetworkManager - { - /// - /// TCP 网络频道。 - /// - private sealed class TcpNetworkChannel : NetworkChannelBase - { - private readonly AsyncCallback _connectCallback; - private readonly AsyncCallback _sendCallback; - private readonly AsyncCallback _receiveCallback; - - /// - /// 初始化网络频道的新实例。 - /// - /// 网络频道名称。 - /// 网络频道辅助器。 - public TcpNetworkChannel(string name, INetworkChannelHelper networkChannelHelper) - : base(name, networkChannelHelper) - { - _connectCallback = ConnectCallback; - _sendCallback = SendCallback; - _receiveCallback = ReceiveCallback; - } - - /// - /// 获取网络服务类型。 - /// - public override ServiceType ServiceType - { - get - { - return ServiceType.Tcp; - } - } - - /// - /// 连接到远程主机。 - /// - /// 远程主机的 IP 地址。 - /// 远程主机的端口号。 - /// 用户自定义数据。 - public override void Connect(IPAddress ipAddress, int port, object userData) - { - base.Connect(ipAddress, port, userData); - MSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); - if (MSocket == null) - { - string errorMessage = "Initialize network channel failure."; - if (NetworkChannelError != null) - { - NetworkChannelError(this, NetworkErrorCode.SocketError, SocketError.Success, errorMessage); - return; - } - - throw new GameFrameworkException(errorMessage); - } - - NetworkChannelHelper.PrepareForConnecting(); - ConnectAsync(ipAddress, port, userData); - } - - protected override bool ProcessSend() - { - if (base.ProcessSend()) - { - SendAsync(); - return true; - } - - return false; - } - - private void ConnectAsync(IPAddress ipAddress, int port, object userData) - { - try - { - MSocket.BeginConnect(ipAddress, port, _connectCallback, new ConnectState(MSocket, userData)); - } - catch (Exception exception) - { - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.ConnectError, socketException != null ? socketException.SocketErrorCode : SocketError.Success, exception.ToString()); - return; - } - - throw; - } - } - - private void ConnectCallback(IAsyncResult ar) - { - ConnectState socketUserData = (ConnectState)ar.AsyncState; - try - { - socketUserData.Socket.EndConnect(ar); - } - catch (ObjectDisposedException) - { - return; - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.ConnectError, socketException != null ? socketException.SocketErrorCode : SocketError.Success, exception.ToString()); - return; - } - - throw; - } - - MSentPacketCount = 0; - MReceivedPacketCount = 0; - - lock (SendPacketPool) - { - SendPacketPool.Clear(); - } - - lock (MHeartBeatState) - { - MHeartBeatState.Reset(true); - } - - if (NetworkChannelConnected != null) - { - NetworkChannelConnected(this, socketUserData.UserData); - } - - Active = true; - ReceiveAsync(); - } - - private void SendAsync() - { - try - { - MSocket.BeginSend(MSendState.Stream.GetBuffer(), (int)MSendState.Stream.Position, (int)(MSendState.Stream.Length - MSendState.Stream.Position), SocketFlags.None, _sendCallback, MSocket); - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.SendError, socketException != null ? socketException.SocketErrorCode : SocketError.Success, exception.ToString()); - return; - } - - throw; - } - } - - private void SendCallback(IAsyncResult ar) - { - Socket socket = (Socket)ar.AsyncState; - if (!socket.Connected) - { - return; - } - - int bytesSent = 0; - try - { - bytesSent = socket.EndSend(ar); - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.SendError, socketException != null ? socketException.SocketErrorCode : SocketError.Success, exception.ToString()); - return; - } - - throw; - } - - MSendState.Stream.Position += bytesSent; - if (MSendState.Stream.Position < MSendState.Stream.Length) - { - SendAsync(); - return; - } - - MSentPacketCount++; - MSendState.Reset(); - } - - private void ReceiveAsync() - { - try - { - MSocket.BeginReceive(MReceiveState.Stream.GetBuffer(), (int)MReceiveState.Stream.Position, (int)(MReceiveState.Stream.Length - MReceiveState.Stream.Position), SocketFlags.None, _receiveCallback, MSocket); - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.ReceiveError, socketException != null ? socketException.SocketErrorCode : SocketError.Success, exception.ToString()); - return; - } - - throw; - } - } - - private void ReceiveCallback(IAsyncResult ar) - { - Socket socket = (Socket)ar.AsyncState; - if (!socket.Connected) - { - return; - } - - int bytesReceived = 0; - try - { - bytesReceived = socket.EndReceive(ar); - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.ReceiveError, socketException != null ? socketException.SocketErrorCode : SocketError.Success, exception.ToString()); - return; - } - - throw; - } - - if (bytesReceived <= 0) - { - Close(); - return; - } - - MReceiveState.Stream.Position += bytesReceived; - if (MReceiveState.Stream.Position < MReceiveState.Stream.Length) - { - ReceiveAsync(); - return; - } - - MReceiveState.Stream.Position = 0L; - - bool processSuccess = false; - if (MReceiveState.PacketHeader != null) - { - processSuccess = ProcessPacket(); - MReceivedPacketCount++; - } - else - { - processSuccess = ProcessPacketHeader(); - } - - if (processSuccess) - { - ReceiveAsync(); - return; - } - } - } - } -} diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.TcpNetworkChannel.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.TcpNetworkChannel.cs.meta deleted file mode 100644 index 577bdaaa..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.TcpNetworkChannel.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: a9660c1a740a423d9c855619aedbebd5 -timeCreated: 1681994450 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.TcpWithSyncReceiveNetworkChannel.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.TcpWithSyncReceiveNetworkChannel.cs deleted file mode 100644 index a6133c31..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.TcpWithSyncReceiveNetworkChannel.cs +++ /dev/null @@ -1,257 +0,0 @@ -using System; -using System.Net; -using System.Net.Sockets; - -namespace TEngine -{ - internal sealed partial class NetworkManager - { - /// - /// 使用同步接收的 TCP 网络频道。 - /// - private sealed class TcpWithSyncReceiveNetworkChannel : NetworkChannelBase - { - private readonly AsyncCallback _connectCallback; - private readonly AsyncCallback _sendCallback; - - /// - /// 初始化网络频道的新实例。 - /// - /// 网络频道名称。 - /// 网络频道辅助器。 - public TcpWithSyncReceiveNetworkChannel(string name, INetworkChannelHelper networkChannelHelper) - : base(name, networkChannelHelper) - { - _connectCallback = ConnectCallback; - _sendCallback = SendCallback; - } - - /// - /// 获取网络服务类型。 - /// - public override ServiceType ServiceType - { - get - { - return ServiceType.TcpWithSyncReceive; - } - } - - /// - /// 连接到远程主机。 - /// - /// 远程主机的 IP 地址。 - /// 远程主机的端口号。 - /// 用户自定义数据。 - public override void Connect(IPAddress ipAddress, int port, object userData) - { - base.Connect(ipAddress, port, userData); - MSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); - if (MSocket == null) - { - string errorMessage = "Initialize network channel failure."; - if (NetworkChannelError != null) - { - NetworkChannelError(this, NetworkErrorCode.SocketError, SocketError.Success, errorMessage); - return; - } - - throw new GameFrameworkException(errorMessage); - } - - NetworkChannelHelper.PrepareForConnecting(); - ConnectAsync(ipAddress, port, userData); - } - - protected override bool ProcessSend() - { - if (base.ProcessSend()) - { - SendAsync(); - return true; - } - - return false; - } - - protected override void ProcessReceive() - { - base.ProcessReceive(); - while (MSocket.Available > 0) - { - if (!ReceiveSync()) - { - break; - } - } - } - - private void ConnectAsync(IPAddress ipAddress, int port, object userData) - { - try - { - MSocket.BeginConnect(ipAddress, port, _connectCallback, new ConnectState(MSocket, userData)); - } - catch (Exception exception) - { - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.ConnectError, socketException != null ? socketException.SocketErrorCode : SocketError.Success, exception.ToString()); - return; - } - - throw; - } - } - - private void ConnectCallback(IAsyncResult ar) - { - ConnectState socketUserData = (ConnectState)ar.AsyncState; - try - { - socketUserData.Socket.EndConnect(ar); - } - catch (ObjectDisposedException) - { - return; - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.ConnectError, socketException != null ? socketException.SocketErrorCode : SocketError.Success, exception.ToString()); - return; - } - - throw; - } - - MSentPacketCount = 0; - MReceivedPacketCount = 0; - - lock (SendPacketPool) - { - SendPacketPool.Clear(); - } - - lock (MHeartBeatState) - { - MHeartBeatState.Reset(true); - } - - if (NetworkChannelConnected != null) - { - NetworkChannelConnected(this, socketUserData.UserData); - } - - Active = true; - } - - private void SendAsync() - { - try - { - MSocket.BeginSend(MSendState.Stream.GetBuffer(), (int)MSendState.Stream.Position, (int)(MSendState.Stream.Length - MSendState.Stream.Position), SocketFlags.None, _sendCallback, MSocket); - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.SendError, socketException != null ? socketException.SocketErrorCode : SocketError.Success, exception.ToString()); - return; - } - - throw; - } - } - - private void SendCallback(IAsyncResult ar) - { - Socket socket = (Socket)ar.AsyncState; - if (!socket.Connected) - { - return; - } - - int bytesSent = 0; - try - { - bytesSent = socket.EndSend(ar); - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.SendError, socketException != null ? socketException.SocketErrorCode : SocketError.Success, exception.ToString()); - return; - } - - throw; - } - - MSendState.Stream.Position += bytesSent; - if (MSendState.Stream.Position < MSendState.Stream.Length) - { - SendAsync(); - return; - } - - MSentPacketCount++; - MSendState.Reset(); - } - - private bool ReceiveSync() - { - try - { - int bytesReceived = MSocket.Receive(MReceiveState.Stream.GetBuffer(), (int)MReceiveState.Stream.Position, (int)(MReceiveState.Stream.Length - MReceiveState.Stream.Position), SocketFlags.None); - if (bytesReceived <= 0) - { - Close(); - return false; - } - - MReceiveState.Stream.Position += bytesReceived; - if (MReceiveState.Stream.Position < MReceiveState.Stream.Length) - { - return false; - } - - MReceiveState.Stream.Position = 0L; - - bool processSuccess = false; - if (MReceiveState.PacketHeader != null) - { - processSuccess = ProcessPacket(); - MReceivedPacketCount++; - } - else - { - processSuccess = ProcessPacketHeader(); - } - - return processSuccess; - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.ReceiveError, socketException != null ? socketException.SocketErrorCode : SocketError.Success, exception.ToString()); - return false; - } - - throw; - } - } - } - } -} diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.TcpWithSyncReceiveNetworkChannel.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.TcpWithSyncReceiveNetworkChannel.cs.meta deleted file mode 100644 index 65365f14..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.TcpWithSyncReceiveNetworkChannel.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: ce9312d4603b4eda99cec01fa82364af -timeCreated: 1681994450 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.UdpNetworkChannel.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.UdpNetworkChannel.cs deleted file mode 100644 index 82fad527..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.UdpNetworkChannel.cs +++ /dev/null @@ -1,291 +0,0 @@ -using System; -using System.Net; -using System.Net.Sockets; - -namespace TEngine -{ - internal sealed partial class NetworkManager - { - /// - /// Udp 网络频道。 - /// - private sealed class UdpNetworkChannel : NetworkChannelBase - { - private readonly AsyncCallback _connectCallback; - private readonly AsyncCallback _sendCallback; - private readonly AsyncCallback _receiveCallback; - - /// - /// 获取网络服务类型。 - /// - public override ServiceType ServiceType => ServiceType.Udp; - - /// - /// 初始化网络频道的新实例。 - /// - /// 网络频道名称。 - /// 网络频道辅助器。 - public UdpNetworkChannel(string name, INetworkChannelHelper networkChannelHelper) - : base(name, networkChannelHelper) - { - _connectCallback = ConnectCallback; - _sendCallback = SendCallback; - _receiveCallback = ReceiveCallback; - } - - - /// - /// 连接到远程主机。 - /// - /// 远程主机的 IP 地址。 - /// 远程主机的端口号。 - /// 用户自定义数据。 - public override void Connect(IPAddress ipAddress, int port, object userData) - { - base.Connect(ipAddress, port, userData); - MSocket = new Socket(ipAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); - if (MSocket == null) - { - string errorMessage = "Initialize network channel failure."; - if (NetworkChannelError != null) - { - NetworkChannelError(this, NetworkErrorCode.SocketError, SocketError.Success, errorMessage); - return; - } - - throw new GameFrameworkException(errorMessage); - } - - NetworkChannelHelper.PrepareForConnecting(); - ConnectAsync(ipAddress, port, userData); - } - - private void ConnectAsync(IPAddress ipAddress, int port, object userData) - { - try - { - MSocket.BeginConnect(ipAddress, port, _connectCallback, new ConnectState(MSocket, userData)); - } - catch (Exception exception) - { - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.ConnectError, - socketException?.SocketErrorCode ?? SocketError.Success, - exception.ToString()); - return; - } - - throw; - } - } - - protected override bool ProcessSend() - { - if (base.ProcessSend()) - { - SendAsync(); - return true; - } - - return false; - } - - private void ConnectCallback(IAsyncResult ar) - { - ConnectState socketUserData = (ConnectState)ar.AsyncState; - try - { - socketUserData.Socket.EndConnect(ar); - } - catch (ObjectDisposedException) - { - return; - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.ConnectError, - socketException?.SocketErrorCode ?? SocketError.Success, - exception.ToString()); - return; - } - - throw; - } - - MSentPacketCount = 0; - MReceivedPacketCount = 0; - - lock (SendPacketPool) - { - SendPacketPool.Clear(); - } - - lock (MHeartBeatState) - { - MHeartBeatState.Reset(true); - } - - if (NetworkChannelConnected != null) - { - NetworkChannelConnected(this, socketUserData.UserData); - } - - Active = true; - ReceiveAsync(); - } - - private void SendAsync() - { - try - { - MSocket.BeginSend(MSendState.Stream.GetBuffer(), (int)MSendState.Stream.Position, - (int)(MSendState.Stream.Length - MSendState.Stream.Position), SocketFlags.None, _sendCallback, - MSocket); - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.SendError, - socketException?.SocketErrorCode ?? SocketError.Success, - exception.ToString()); - return; - } - - throw; - } - } - - private void SendCallback(IAsyncResult ar) - { - Socket socket = (Socket)ar.AsyncState; - if (!socket.Connected) - { - return; - } - - int bytesSent = 0; - try - { - bytesSent = socket.EndSend(ar); - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.SendError, - socketException?.SocketErrorCode ?? SocketError.Success, - exception.ToString()); - return; - } - - throw; - } - - MSendState.Stream.Position += bytesSent; - if (MSendState.Stream.Position < MSendState.Stream.Length) - { - SendAsync(); - return; - } - - MSentPacketCount++; - MSendState.Reset(); - } - - private void ReceiveAsync() - { - try - { - MSocket.BeginReceive(MReceiveState.Stream.GetBuffer(), (int)MReceiveState.Stream.Position, - (int)(MReceiveState.Stream.Length - MReceiveState.Stream.Position), SocketFlags.None, - _receiveCallback, MSocket); - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.ReceiveError, - socketException?.SocketErrorCode ?? SocketError.Success, - exception.ToString()); - return; - } - - throw; - } - } - - private void ReceiveCallback(IAsyncResult ar) - { - Socket socket = (Socket)ar.AsyncState; - if (!socket.Connected) - { - return; - } - - int bytesReceived = 0; - try - { - bytesReceived = socket.EndReceive(ar); - } - catch (Exception exception) - { - Active = false; - if (NetworkChannelError != null) - { - SocketException socketException = exception as SocketException; - NetworkChannelError(this, NetworkErrorCode.ReceiveError, - socketException?.SocketErrorCode ?? SocketError.Success, - exception.ToString()); - return; - } - - throw; - } - - if (bytesReceived <= 0) - { - Close(); - return; - } - - MReceiveState.Stream.Position += bytesReceived; - if (MReceiveState.Stream.Position < MReceiveState.Stream.Length) - { - ReceiveAsync(); - return; - } - - MReceiveState.Stream.Position = 0L; - - bool processSuccess = false; - if (MReceiveState.PacketHeader != null) - { - processSuccess = ProcessPacket(); - MReceivedPacketCount++; - } - else - { - processSuccess = ProcessPacketHeader(); - } - - if (processSuccess) - { - ReceiveAsync(); - } - } - } - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.UdpNetworkChannel.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.UdpNetworkChannel.cs.meta deleted file mode 100644 index 3779b333..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.UdpNetworkChannel.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: cb75f9187f154d83a9fd92d8e1ab318d -timeCreated: 1682091504 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.cs deleted file mode 100644 index 025cfd06..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.cs +++ /dev/null @@ -1,317 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net.Sockets; -using GameBase; -using GameProto; - -namespace TEngine -{ - /// - /// 网络消息委托。 - /// - public delegate void CsMsgDelegate(CSPkg csPkg); - - /// - /// 网络管理器。 - /// - internal sealed partial class NetworkManager : Singleton, INetworkManager - { - private readonly Dictionary _networkChannels; - - private Action _networkConnectedEventHandler; - private Action _networkClosedEventHandler; - private Action _networkMissHeartBeatEventHandler; - private Action _networkErrorEventHandler; - private Action _networkCustomErrorEventHandler; - - /// - /// 初始化网络管理器的新实例。 - /// - public NetworkManager() - { - _networkChannels = new Dictionary(StringComparer.Ordinal); - _networkConnectedEventHandler = null; - _networkClosedEventHandler = null; - _networkMissHeartBeatEventHandler = null; - _networkErrorEventHandler = null; - _networkCustomErrorEventHandler = null; - } - - /// - /// 获取网络频道数量。 - /// - public int NetworkChannelCount => _networkChannels.Count; - - /// - /// 网络连接成功事件。 - /// - public event Action NetworkConnected - { - add => _networkConnectedEventHandler += value; - remove => _networkConnectedEventHandler -= value; - } - - /// - /// 网络连接关闭事件。 - /// - public event Action NetworkClosed - { - add => _networkClosedEventHandler += value; - remove => _networkClosedEventHandler -= value; - } - - /// - /// 网络心跳包丢失事件。 - /// - public event Action NetworkMissHeartBeat - { - add => _networkMissHeartBeatEventHandler += value; - remove => _networkMissHeartBeatEventHandler -= value; - } - - /// - /// 网络错误事件。 - /// - public event Action NetworkError - { - add => _networkErrorEventHandler += value; - remove => _networkErrorEventHandler -= value; - } - - /// - /// 用户自定义网络错误事件。 - /// - public event Action NetworkCustomError - { - add => _networkCustomErrorEventHandler += value; - remove => _networkCustomErrorEventHandler -= value; - } - - /// - /// 网络管理器轮询。 - /// - /// 逻辑流逝时间,以秒为单位。 - /// 真实流逝时间,以秒为单位。 - public void Update(float elapseSeconds, float realElapseSeconds) - { - foreach (KeyValuePair networkChannel in _networkChannels) - { - networkChannel.Value.Update(elapseSeconds, realElapseSeconds); - } - } - - /// - /// 关闭并清理网络管理器。 - /// - public void Shutdown() - { - foreach (KeyValuePair networkChannel in _networkChannels) - { - NetworkChannelBase networkChannelBase = networkChannel.Value; - networkChannelBase.NetworkChannelConnected -= OnNetworkChannelConnected; - networkChannelBase.NetworkChannelClosed -= OnNetworkChannelClosed; - networkChannelBase.NetworkChannelMissHeartBeat -= OnNetworkChannelMissHeartBeat; - networkChannelBase.NetworkChannelError -= OnNetworkChannelError; - networkChannelBase.NetworkChannelCustomError -= OnNetworkChannelCustomError; - networkChannelBase.Shutdown(); - } - - _networkChannels.Clear(); - } - - /// - /// 检查是否存在网络频道。 - /// - /// 网络频道名称。 - /// 是否存在网络频道。 - public bool HasNetworkChannel(string name) - { - return _networkChannels.ContainsKey(name ?? string.Empty); - } - - /// - /// 获取网络频道。 - /// - /// 网络频道名称。 - /// 要获取的网络频道。 - public INetworkChannel GetNetworkChannel(string name) - { - if (_networkChannels.TryGetValue(name ?? string.Empty, out var networkChannel)) - { - return networkChannel; - } - - return null; - } - - /// - /// 获取所有网络频道。 - /// - /// 所有网络频道。 - public INetworkChannel[] GetAllNetworkChannels() - { - int index = 0; - INetworkChannel[] results = new INetworkChannel[_networkChannels.Count]; - foreach (KeyValuePair networkChannel in _networkChannels) - { - results[index++] = networkChannel.Value; - } - - return results; - } - - /// - /// 获取所有网络频道。 - /// - /// 所有网络频道。 - public void GetAllNetworkChannels(List results) - { - if (results == null) - { - throw new GameFrameworkException("Results is invalid."); - } - - results.Clear(); - foreach (KeyValuePair networkChannel in _networkChannels) - { - results.Add(networkChannel.Value); - } - } - - /// - /// 创建网络频道。 - /// - /// 网络频道名称。 - /// 网络服务类型。 - /// 网络频道辅助器。 - /// 要创建的网络频道。 - public INetworkChannel CreateNetworkChannel(string name, ServiceType serviceType, - INetworkChannelHelper networkChannelHelper) - { - if (networkChannelHelper == null) - { - throw new GameFrameworkException("Network channel helper is invalid."); - } - - if (networkChannelHelper.PacketHeaderLength < 0) - { - throw new GameFrameworkException("Packet header length is invalid."); - } - - if (HasNetworkChannel(name)) - { - throw new GameFrameworkException(Utility.Text.Format("Already exist network channel '{0}'.", - name ?? string.Empty)); - } - - NetworkChannelBase networkChannel = null; - switch (serviceType) - { - case ServiceType.Tcp: - networkChannel = new TcpNetworkChannel(name, networkChannelHelper); - break; - - case ServiceType.TcpWithSyncReceive: - networkChannel = new TcpWithSyncReceiveNetworkChannel(name, networkChannelHelper); - break; - - case ServiceType.Udp: - networkChannel = new UdpNetworkChannel(name, networkChannelHelper); - break; - - case ServiceType.Kcp: - networkChannel = new KcpNetworkChannel(name, networkChannelHelper); - break; - - default: - throw new GameFrameworkException(Utility.Text.Format("Not supported service type '{0}'.", - serviceType)); - } - - networkChannel.NetworkChannelConnected += OnNetworkChannelConnected; - networkChannel.NetworkChannelClosed += OnNetworkChannelClosed; - networkChannel.NetworkChannelMissHeartBeat += OnNetworkChannelMissHeartBeat; - networkChannel.NetworkChannelError += OnNetworkChannelError; - networkChannel.NetworkChannelCustomError += OnNetworkChannelCustomError; - _networkChannels.Add(name, networkChannel); - return networkChannel; - } - - /// - /// 销毁网络频道。 - /// - /// 网络频道名称。 - /// 是否销毁网络频道成功。 - public bool DestroyNetworkChannel(string name) - { - if (_networkChannels.TryGetValue(name ?? string.Empty, out var networkChannel)) - { - networkChannel.NetworkChannelConnected -= OnNetworkChannelConnected; - networkChannel.NetworkChannelClosed -= OnNetworkChannelClosed; - networkChannel.NetworkChannelMissHeartBeat -= OnNetworkChannelMissHeartBeat; - networkChannel.NetworkChannelError -= OnNetworkChannelError; - networkChannel.NetworkChannelCustomError -= OnNetworkChannelCustomError; - networkChannel.Shutdown(); - return name != null && _networkChannels.Remove(name); - } - - return false; - } - - private void OnNetworkChannelConnected(NetworkChannelBase networkChannel, object userData) - { - if (_networkConnectedEventHandler != null) - { - lock (_networkConnectedEventHandler) - { - _networkConnectedEventHandler(networkChannel, userData); - } - } - } - - private void OnNetworkChannelClosed(NetworkChannelBase networkChannel) - { - if (_networkClosedEventHandler != null) - { - lock (_networkClosedEventHandler) - { - _networkClosedEventHandler(networkChannel); - } - } - } - - private void OnNetworkChannelMissHeartBeat(NetworkChannelBase networkChannel, int missHeartBeatCount) - { - if (_networkMissHeartBeatEventHandler != null) - { - lock (_networkMissHeartBeatEventHandler) - { - _networkMissHeartBeatEventHandler(networkChannel, missHeartBeatCount); - } - } - } - - private void OnNetworkChannelError(NetworkChannelBase networkChannel, NetworkErrorCode errorCode, - SocketError socketErrorCode, string errorMessage) - { - if (_networkErrorEventHandler != null) - { - lock (_networkErrorEventHandler) - { - _networkErrorEventHandler(networkChannel, errorCode, socketErrorCode, errorMessage); - } - } - } - - private void OnNetworkChannelCustomError(NetworkChannelBase networkChannel, object customErrorData) - { - if (_networkCustomErrorEventHandler != null) - { - lock (_networkCustomErrorEventHandler) - { - _networkCustomErrorEventHandler(networkChannel, customErrorData); - } - } - } - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.cs.meta deleted file mode 100644 index 93ac413c..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/NetworkManager.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 96c0584a53cd4b8e88949b77eac8e1ce -timeCreated: 1681994450 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/ServiceType.cs b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/ServiceType.cs deleted file mode 100644 index 5affc3e7..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/ServiceType.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace TEngine -{ - /// - /// 网络服务类型。 - /// - public enum ServiceType : byte - { - /// - /// TCP 网络服务。 - /// - Tcp = 0, - - /// - /// 使用同步接收的 TCP 网络服务。 - /// - TcpWithSyncReceive = 1, - - /// - /// UDP 网络服务。 - /// - Udp = 2, - - /// - /// KCP 网络服务。 - /// - Kcp = 3, - } -} diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/ServiceType.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/ServiceType.cs.meta deleted file mode 100644 index dbbcc036..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/NetworkCore/ServiceType.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: c80c2ca9fea74504a4a79c2ecd01d065 -timeCreated: 1681993754 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/PacketHeader.cs b/Assets/GameScripts/HotFix/GameLogic/Network/PacketHeader.cs deleted file mode 100644 index 104a6f96..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/PacketHeader.cs +++ /dev/null @@ -1,47 +0,0 @@ -using TEngine; - -namespace GameLogic -{ - /// - /// 网络消息包头。 - /// - public class PacketHeader : IPacketHeader, IMemory - { - /// - /// 网络消息包Id。 - /// - public short Id - { - get; - set; - } - - /// - /// 网络消息包长度。 - /// - public int PacketLength - { - get; - set; - } - - /// - /// 网络消息包是否合法。 - /// - public bool IsValid - { - get - { - return PacketLength >= 0; - } - } - - /// - /// 清除网络消息包头。 - /// - public void Clear() - { - PacketLength = 0; - } - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/PacketHeader.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/PacketHeader.cs.meta deleted file mode 100644 index 5bc102de..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/PacketHeader.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 30edc133b73141598b5351d4afc2ad93 -timeCreated: 1682046771 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/ProtoUtil.cs b/Assets/GameScripts/HotFix/GameLogic/Network/ProtoUtil.cs deleted file mode 100644 index ff218291..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/ProtoUtil.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using GameProto; - -namespace GameLogic -{ - public partial class ProtobufUtility - { - public static UInt32 MsgEcho = 0; - - /// - /// 根据msgId来生成一个数据包 - /// - /// - /// - public static CSPkg BuildCsMsg(int msgId) - { - CSPkg tmp = new CSPkg(); - tmp.Head = new CSPkgHead(); - tmp.Head.MsgId = (UInt16)msgId; - tmp.Head.Echo = GetNextEcho(); - // tmp.Body.create(msgId); - return tmp; - } - - private static UInt32 GetNextEcho() - { - return ++MsgEcho; - } - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/ProtoUtil.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/ProtoUtil.cs.meta deleted file mode 100644 index 77f8a672..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/ProtoUtil.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 4d4427af9be14c56b01e4674853c09a8 -timeCreated: 1684334469 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/ProtobufUtility.cs b/Assets/GameScripts/HotFix/GameLogic/Network/ProtobufUtility.cs deleted file mode 100644 index 3515375e..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/ProtobufUtility.cs +++ /dev/null @@ -1,217 +0,0 @@ -using System; -using System.ComponentModel; -using System.IO; -using System.Linq; -using System.Text; -using GameProto; -using Google.Protobuf; -using TEngine; - - -/// -/// ProtoBuf工具 -/// -public partial class ProtobufUtility -{ - private const int BufferHead = 4; - - /// - /// 消息压入内存流。 - /// - /// - /// - public static void ToStream(object message, MemoryStream stream) - { - ((IMessage)message).WriteTo(stream); - } - - /// - /// 消息压入内存流。 - /// - /// - /// - public static void ToStream(object message, Stream stream) - { - ((IMessage)message).WriteTo(stream); - } - - /// - /// 消息压入内存流。 - /// - /// - /// - public static void ToStreamWithHead(CSPkg packet, MemoryStream stream) - { - byte[] data = packet.ToByteArray(); - byte[] head = BitConverter.GetBytes(data.Length); - byte[] ret = head.Concat(data).ToArray(); - stream.Write(ret); - ((MemoryStream)stream).SetLength(BufferHead + data.Length); - } - - /// - /// 比特流解析。 - /// - /// - /// - /// - /// - /// - public static object FromBytes(Type type, byte[] bytes, int index, int count) - { - object message = Activator.CreateInstance(type); - ((IMessage)message).MergeFrom(bytes, index, count); - ISupportInitialize iSupportInitialize = message as ISupportInitialize; - if (iSupportInitialize == null) - { - return message; - } - - iSupportInitialize.EndInit(); - return message; - } - - /// - /// 比特流解析。 - /// - /// - /// - /// - /// - /// - public static object FromBytes(object instance, byte[] bytes, int index, int count) - { - object message = instance; - ((IMessage)message).MergeFrom(bytes, index, count); - ISupportInitialize iSupportInitialize = message as ISupportInitialize; - if (iSupportInitialize == null) - { - return message; - } - - iSupportInitialize.EndInit(); - return message; - } - - /// - /// 从内存流取出。 - /// - /// - /// - /// - public static object FromStream(Type type, MemoryStream stream) - { - object message = Activator.CreateInstance(type); - ((IMessage)message).MergeFrom(stream.GetBuffer(), (int)stream.Position, (int)stream.Length); - ISupportInitialize iSupportInitialize = message as ISupportInitialize; - if (iSupportInitialize == null) - { - return message; - } - - iSupportInitialize.EndInit(); - return message; - } - - /// - /// 从内存流取出。 - /// - /// - /// - /// - public static object FromStream(object message, MemoryStream stream) - { - // TODO 这个message最好从池中获取,减少gc - ((IMessage)message).MergeFrom(stream.GetBuffer(), (int)stream.Position, (int)stream.Length); - ISupportInitialize iSupportInitialize = message as ISupportInitialize; - if (iSupportInitialize == null) - { - return message; - } - - iSupportInitialize.EndInit(); - return message; - } - - public static byte[] ToBytes(object message) - { - return ((IMessage)message).ToByteArray(); - } - - /// - /// 序列化protobuf - /// - /// - /// - public static byte[] Serialize(object message) - { - return ((IMessage)message).ToByteArray(); - } - - /// - /// 反序列化protobuf - /// - /// - /// - /// - /// - /// - public static T Deserialize(byte[] dataBytes, int offset, int bodyCount) where T : IMessage, new() - { - T msg = new T(); - msg = (T)msg.Descriptor.Parser.ParseFrom(dataBytes, offset, bodyCount); - return msg; - } - - /// - /// 反序列化protobuf - /// - /// - /// - /// - /// - public static CSPkg Deserialize(byte[] dataBytes, int offset, int bodyCount) - { - var msg = (CSPkg)CSPkg.Descriptor.Parser.ParseFrom(dataBytes, offset, bodyCount); - return msg; - } - - public static int GetHighOrder(int cmdMerge) - { - return cmdMerge >> 16; - } - - public static int GetLowOrder(int cmdMerge) - { - return cmdMerge & 65535; - } - - - private static readonly StringBuilder StringBuilder = new StringBuilder(); - - public static string GetBuffer(byte[] buffer) - { - StringBuilder.Length = 0; - StringBuilder.Append("["); - for (int i = 0; i < buffer.Length; i++) - { - if (i == buffer.Length - 1) - { - StringBuilder.Append(buffer[i]); - StringBuilder.Append("]"); - } - else - { - StringBuilder.Append(buffer[i]); - StringBuilder.Append(","); - } - } - - return StringBuilder.ToString(); - } - - public static void PrintBuffer(byte[] buffer) - { - Log.Debug(GetBuffer(buffer)); - } -} \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/ProtobufUtility.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/ProtobufUtility.cs.meta deleted file mode 100644 index 400e157c..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/ProtobufUtility.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 972ca4545003463d8710de956f0fde66 -timeCreated: 1682047511 \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/ProtobufUtils.cs b/Assets/GameScripts/HotFix/GameLogic/Network/ProtobufUtils.cs deleted file mode 100644 index 67bf6893..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/ProtobufUtils.cs +++ /dev/null @@ -1,138 +0,0 @@ -// using System; -// using System.ComponentModel; -// using System.IO; -// using ProtoBuf; -// using ProtoBuf.Meta; -// -// /// -// /// ProtoBuf工具 -// /// -// public class ProtobufUtils -// { -// /// -// /// 消息压入内存流。 -// /// -// /// -// /// -// public static void ToStream(object message, MemoryStream stream) -// { -// ((IMessage)message).WriteTo(stream); -// } -// -// /// -// /// 比特流解析。 -// /// -// /// -// /// -// /// -// /// -// /// -// public static object FromBytes(Type type, byte[] bytes, int index, int count) -// { -// object message = Activator.CreateInstance(type); -// ((IMessage)message).MergeFrom(bytes, index, count); -// ISupportInitialize iSupportInitialize = message as ISupportInitialize; -// if (iSupportInitialize == null) -// { -// return message; -// } -// -// iSupportInitialize.EndInit(); -// return message; -// } -// -// /// -// /// 比特流解析。 -// /// -// /// -// /// -// /// -// /// -// /// -// public static object FromBytes(object instance, byte[] bytes, int index, int count) -// { -// object message = instance; -// ((IMessage)message).MergeFrom(bytes, index, count); -// ISupportInitialize iSupportInitialize = message as ISupportInitialize; -// if (iSupportInitialize == null) -// { -// return message; -// } -// -// iSupportInitialize.EndInit(); -// return message; -// } -// -// /// -// /// 从内存流取出。 -// /// -// /// -// /// -// /// -// public static object FromStream(Type type, MemoryStream stream) -// { -// object message = Activator.CreateInstance(type); -// ((IMessage)message).MergeFrom(stream.GetBuffer(), (int)stream.Position, (int)stream.Length); -// ISupportInitialize iSupportInitialize = message as ISupportInitialize; -// if (iSupportInitialize == null) -// { -// return message; -// } -// -// iSupportInitialize.EndInit(); -// return message; -// } -// -// /// -// /// 从内存流取出。 -// /// -// /// -// /// -// /// -// public static object FromStream(object message, MemoryStream stream) -// { -// // TODO 这个message最好从池中获取,减少gc -// ((IMessage)message).MergeFrom(stream.GetBuffer(), (int)stream.Position, (int)stream.Length); -// ISupportInitialize iSupportInitialize = message as ISupportInitialize; -// if (iSupportInitialize == null) -// { -// return message; -// } -// -// iSupportInitialize.EndInit(); -// return message; -// } -// -// /// -// /// 序列化protobuf -// /// -// /// -// /// -// public static byte[] Serialize(object message) -// { -// return ((IMessage)message).ToByteArray(); -// } -// -// /// -// /// 反序列化protobuf -// /// -// /// -// /// -// /// -// public static T Deserialize(byte[] dataBytes) where T : IMessage, new() -// { -// T msg = new T(); -// msg = (T)msg.Descriptor.Parser.ParseFrom(dataBytes); -// return msg; -// } -// -// public static int GetHighOrder(int cmdMerge) -// { -// return cmdMerge >> 16; -// } -// -// public static int GetLowOrder(int cmdMerge) -// { -// return cmdMerge & 65535; -// } -// } \ No newline at end of file diff --git a/Assets/GameScripts/HotFix/GameLogic/Network/ProtobufUtils.cs.meta b/Assets/GameScripts/HotFix/GameLogic/Network/ProtobufUtils.cs.meta deleted file mode 100644 index d22d6e14..00000000 --- a/Assets/GameScripts/HotFix/GameLogic/Network/ProtobufUtils.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 26e2c268a764bad4eb7412ad65f822e2 -timeCreated: 1682047511 \ No newline at end of file