├── ProjectSettings ├── ProjectVersion.txt ├── TagManager.asset ├── AudioManager.asset ├── InputManager.asset ├── NavMeshAreas.asset ├── TimeManager.asset ├── DynamicsManager.asset ├── EditorSettings.asset ├── NetworkManager.asset ├── ProjectSettings.asset ├── QualitySettings.asset ├── GraphicsSettings.asset ├── Physics2DSettings.asset ├── ClusterInputManager.asset ├── EditorBuildSettings.asset └── UnityConnectSettings.asset ├── Assets ├── UnityTest │ ├── KCPTest │ │ ├── KCPTest.unity │ │ ├── KCPTest.unity.meta │ │ ├── KCPPlayer.cs.meta │ │ ├── KCPTest.cs.meta │ │ ├── KCPTest.cs │ │ └── KCPPlayer.cs │ └── KCPTest.meta ├── SGF.meta ├── SGF │ ├── Network │ │ ├── KCP │ │ │ ├── LICENSE.txt.meta │ │ │ ├── kcp.cs.meta │ │ │ ├── KCPSocket.cs.meta │ │ │ ├── switch_queue.cs.meta │ │ │ ├── switch_queue.cs │ │ │ ├── KCPSocket.cs │ │ │ ├── LICENSE.txt │ │ │ └── kcp.cs │ │ └── KCP.meta │ ├── Debuger.meta │ ├── Network.meta │ └── Debuger │ │ ├── Debuger.cs.meta │ │ ├── DebugerExtension.cs.meta │ │ ├── DebugerExtension.cs │ │ └── Debuger.cs └── UnityTest.meta ├── README.md └── LICENSE.txt /ProjectSettings/ProjectVersion.txt: -------------------------------------------------------------------------------- 1 | m_EditorVersion: 5.5.0f3 2 | -------------------------------------------------------------------------------- /ProjectSettings/TagManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slicol/KCP-Socket/HEAD/ProjectSettings/TagManager.asset -------------------------------------------------------------------------------- /ProjectSettings/AudioManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slicol/KCP-Socket/HEAD/ProjectSettings/AudioManager.asset -------------------------------------------------------------------------------- /ProjectSettings/InputManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slicol/KCP-Socket/HEAD/ProjectSettings/InputManager.asset -------------------------------------------------------------------------------- /ProjectSettings/NavMeshAreas.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slicol/KCP-Socket/HEAD/ProjectSettings/NavMeshAreas.asset -------------------------------------------------------------------------------- /ProjectSettings/TimeManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slicol/KCP-Socket/HEAD/ProjectSettings/TimeManager.asset -------------------------------------------------------------------------------- /ProjectSettings/DynamicsManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slicol/KCP-Socket/HEAD/ProjectSettings/DynamicsManager.asset -------------------------------------------------------------------------------- /ProjectSettings/EditorSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slicol/KCP-Socket/HEAD/ProjectSettings/EditorSettings.asset -------------------------------------------------------------------------------- /ProjectSettings/NetworkManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slicol/KCP-Socket/HEAD/ProjectSettings/NetworkManager.asset -------------------------------------------------------------------------------- /ProjectSettings/ProjectSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slicol/KCP-Socket/HEAD/ProjectSettings/ProjectSettings.asset -------------------------------------------------------------------------------- /ProjectSettings/QualitySettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slicol/KCP-Socket/HEAD/ProjectSettings/QualitySettings.asset -------------------------------------------------------------------------------- /Assets/UnityTest/KCPTest/KCPTest.unity: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slicol/KCP-Socket/HEAD/Assets/UnityTest/KCPTest/KCPTest.unity -------------------------------------------------------------------------------- /ProjectSettings/GraphicsSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slicol/KCP-Socket/HEAD/ProjectSettings/GraphicsSettings.asset -------------------------------------------------------------------------------- /ProjectSettings/Physics2DSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slicol/KCP-Socket/HEAD/ProjectSettings/Physics2DSettings.asset -------------------------------------------------------------------------------- /ProjectSettings/ClusterInputManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slicol/KCP-Socket/HEAD/ProjectSettings/ClusterInputManager.asset -------------------------------------------------------------------------------- /ProjectSettings/EditorBuildSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slicol/KCP-Socket/HEAD/ProjectSettings/EditorBuildSettings.asset -------------------------------------------------------------------------------- /ProjectSettings/UnityConnectSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slicol/KCP-Socket/HEAD/ProjectSettings/UnityConnectSettings.asset -------------------------------------------------------------------------------- /Assets/SGF.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 0ef4286a4b9346f4b820d62e321e51e1 3 | folderAsset: yes 4 | timeCreated: 1483520496 5 | licenseType: Free 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/SGF/Network/KCP/LICENSE.txt.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 6fd85560da5d85146953a39d2eebe123 3 | timeCreated: 1483520614 4 | licenseType: Free 5 | TextScriptImporter: 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Assets/UnityTest/KCPTest/KCPTest.unity.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: ca5c2f1471b6c2348af04599a153ff0a 3 | timeCreated: 1483521654 4 | licenseType: Free 5 | DefaultImporter: 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Assets/SGF/Debuger.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 81cec821f5142134199fbcf2c70c918d 3 | folderAsset: yes 4 | timeCreated: 1483520746 5 | licenseType: Free 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/SGF/Network.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 2dcf9eac66dfab94f8e00632261c9fee 3 | folderAsset: yes 4 | timeCreated: 1483520613 5 | licenseType: Free 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/UnityTest.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 35f56f14331b3bb498d04fdaf84a80f7 3 | folderAsset: yes 4 | timeCreated: 1483521260 5 | licenseType: Free 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/SGF/Network/KCP.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: be7fd0d06e6078e4dbb91568a5fdb3f9 3 | folderAsset: yes 4 | timeCreated: 1483520613 5 | licenseType: Free 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/UnityTest/KCPTest.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: d039ef624ded0b448bdf1fe2889be5e0 3 | folderAsset: yes 4 | timeCreated: 1483521260 5 | licenseType: Free 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # KCP-Socket 2 | This is a KCP+UDPSocket Wrapper. 3 | You can use KCP like UdpSocket. 4 | 5 | Because it is simple, you can use it for Unity+Lan Communications 6 | 7 | It refers to kcp-cssharp:https://github.com/limpo1989/kcp-csharp 8 | and the KCP:https://github.com/skywind3000/kcp 9 | -------------------------------------------------------------------------------- /Assets/SGF/Debuger/Debuger.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 82c77083f0b33134c8d6207afdbafe43 3 | timeCreated: 1483520746 4 | licenseType: Free 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/SGF/Network/KCP/kcp.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: bdfcabd15cc730a45818dfd6edc783cc 3 | timeCreated: 1483520613 4 | licenseType: Free 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/SGF/Debuger/DebugerExtension.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 2e880738fdc1eca438fe356f95182e15 3 | timeCreated: 1483520763 4 | licenseType: Free 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/SGF/Network/KCP/KCPSocket.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 0c6e277577c6e774192d38b94c3a1fbe 3 | timeCreated: 1483520613 4 | licenseType: Free 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/SGF/Network/KCP/switch_queue.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: dd465820e4bfc6a46b70d8b3a9636b03 3 | timeCreated: 1483520613 4 | licenseType: Free 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/UnityTest/KCPTest/KCPPlayer.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 9de90598ee130f242b7409696862d3c8 3 | timeCreated: 1483521260 4 | licenseType: Free 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/UnityTest/KCPTest/KCPTest.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 053a361a316c4a7488287bfda98860e8 3 | timeCreated: 1483521260 4 | licenseType: Free 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/UnityTest/KCPTest/KCPTest.cs: -------------------------------------------------------------------------------- 1 | 2 | 3 | using SGF; 4 | using UnityEngine; 5 | 6 | namespace Assets.UnityTest.KCPTest 7 | { 8 | public class KCPTest:MonoBehaviour 9 | { 10 | private KCPPlayer p1, p2; 11 | 12 | void Awake() 13 | { 14 | Debuger.EnableLog = true; 15 | 16 | this.Log("Awake()"); 17 | 18 | p1 = new KCPPlayer(); 19 | p1.Init("Player1", 12345, 12346); 20 | 21 | p2 = new KCPPlayer(); 22 | p2.Init("Player2", 12346, 12345); 23 | 24 | } 25 | 26 | void Update() 27 | { 28 | p1.OnUpdate(); 29 | p2.OnUpdate(); 30 | } 31 | 32 | void OnGUI() 33 | { 34 | if (GUILayout.Button("Player1 SendMessage")) 35 | { 36 | p1.SendMessage(); 37 | } 38 | 39 | if (GUILayout.Button("Player2 SendMessage")) 40 | { 41 | p2.SendMessage(); 42 | } 43 | } 44 | } 45 | 46 | } 47 | 48 | -------------------------------------------------------------------------------- /Assets/SGF/Network/KCP/switch_queue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | 4 | namespace SGF.Network.KCP 5 | { 6 | public class Utility 7 | { 8 | 9 | public static void Swap(ref QT t1, ref QT t2) 10 | { 11 | 12 | QT temp = t1; 13 | t1 = t2; 14 | t2 = temp; 15 | } 16 | } 17 | 18 | public class SwitchQueue where T : class 19 | { 20 | 21 | private Queue mConsumeQueue; 22 | private Queue mProduceQueue; 23 | 24 | public SwitchQueue() 25 | { 26 | mConsumeQueue = new Queue(16); 27 | mProduceQueue = new Queue(16); 28 | } 29 | 30 | public SwitchQueue(int capcity) 31 | { 32 | mConsumeQueue = new Queue(capcity); 33 | mProduceQueue = new Queue(capcity); 34 | } 35 | 36 | // producer 37 | public void Push(T obj) 38 | { 39 | lock (mProduceQueue) 40 | { 41 | mProduceQueue.Enqueue(obj); 42 | } 43 | } 44 | 45 | // consumer. 46 | public T Pop() 47 | { 48 | 49 | return (T)mConsumeQueue.Dequeue(); 50 | } 51 | 52 | public bool Empty() 53 | { 54 | return 0 == mConsumeQueue.Count; 55 | } 56 | 57 | public void Switch() 58 | { 59 | lock (mProduceQueue) 60 | { 61 | Utility.Swap(ref mConsumeQueue, ref mProduceQueue); 62 | } 63 | } 64 | 65 | public void Clear() 66 | { 67 | lock (mProduceQueue) 68 | { 69 | mConsumeQueue.Clear(); 70 | mProduceQueue.Clear(); 71 | } 72 | } 73 | } 74 | 75 | 76 | } 77 | -------------------------------------------------------------------------------- /Assets/UnityTest/KCPTest/KCPPlayer.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Net.Sockets; 3 | using System.Text; 4 | using SGF; 5 | using SGF.Network.KCP; 6 | using UnityEngine; 7 | 8 | 9 | namespace Assets.UnityTest.KCPTest 10 | { 11 | public class KCPPlayer 12 | { 13 | public string LOG_TAG = "KCPPlayer"; 14 | 15 | private KCPSocket m_Socket; 16 | private string m_Name; 17 | private int m_MsgId = 0; 18 | private IPEndPoint m_RemotePoint; 19 | 20 | public void Init(string name, int localPort, int remotePort) 21 | { 22 | m_Name = name; 23 | LOG_TAG = "KCPPlayer[" + m_Name + "]"; 24 | 25 | IPAddress ipa = IPAddress.Parse(Network.player.ipAddress); 26 | m_RemotePoint = new IPEndPoint(ipa, remotePort); 27 | 28 | m_Socket = new KCPSocket(localPort, 1, AddressFamily.InterNetwork); 29 | m_Socket.AddReceiveListener(KCPSocket.IPEP_Any, OnReceiveAny); 30 | m_Socket.AddReceiveListener(m_RemotePoint, OnReceive); 31 | 32 | this.Log("Init() name:{0}, localPort:{1}, remotePort:{2}",name, localPort, remotePort ); 33 | } 34 | 35 | private void OnReceiveAny(byte[] buffer, int size, IPEndPoint remotePoint) 36 | { 37 | string str = Encoding.UTF8.GetString(buffer, 0, size); 38 | this.Log("OnReceiveAny() " + remotePoint + ":" + str); 39 | } 40 | 41 | private void OnReceive(byte[] buffer, int size, IPEndPoint remotePoint) 42 | { 43 | string str = Encoding.UTF8.GetString(buffer, 0, size); 44 | this.Log("OnReceive() " + remotePoint + ":" + str); 45 | } 46 | 47 | public void OnUpdate() 48 | { 49 | if (m_Socket != null) 50 | { 51 | m_Socket.Update(); 52 | } 53 | } 54 | 55 | public void SendMessage() 56 | { 57 | if (m_Socket != null) 58 | { 59 | m_MsgId++; 60 | m_Socket.SendTo(m_Name + "_" + "Message" + m_MsgId, m_RemotePoint); 61 | } 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Assets/SGF/Debuger/DebugerExtension.cs: -------------------------------------------------------------------------------- 1 | //////////////////////////////////////////////////////////////////// 2 | // _ooOoo_ // 3 | // o8888888o // 4 | // 88" . "88 // 5 | // (| ^_^ |) // 6 | // O\ = /O // 7 | // ____/`---'\____ // 8 | // .' \\| |// `. // 9 | // / \\||| : |||// \ // 10 | // / _||||| -:- |||||- \ // 11 | // | | \\\ - /// | | // 12 | // | \_| ''\---/'' | | // 13 | // \ .-\__ `-` ___/-. / // 14 | // ___`. .' /--.--\ `. . ___ // 15 | // ."" '< `.___\_<|>_/___.' >'"". // 16 | // | | : `- \`.;`\ _ /`;.`/ - ` : | | // 17 | // \ \ `-. \_ __\ /__ _/ .-` / / // 18 | // ========`-.____`-.___\_____/___.-`____.-'======== // 19 | // `=---=' // 20 | // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // 21 | // 佛祖保佑 无BUG 不修改 // 22 | //////////////////////////////////////////////////////////////////// 23 | /* 24 | * 描述: 25 | * 作者:slicol 26 | */ 27 | using System; 28 | using System.Collections.Generic; 29 | using System.Diagnostics; 30 | using System.Linq; 31 | using System.Reflection; 32 | using System.Text; 33 | using UnityEngine; 34 | using Debug = UnityEngine.Debug; 35 | using Object = System.Object; 36 | 37 | namespace SGF 38 | { 39 | public static class DebugerExtension 40 | { 41 | [Conditional("EnableLog")] 42 | public static void Log(this object obj, object message) 43 | { 44 | if (!Debuger.EnableLog) 45 | { 46 | return; 47 | } 48 | 49 | Debuger.Log(GetLogTag(obj), (string)message); 50 | } 51 | 52 | 53 | public static void LogError(this object obj, object message) 54 | { 55 | Debuger.LogError(GetLogTag(obj), (string)message); 56 | } 57 | 58 | 59 | public static void LogWarning(this object obj, object message) 60 | { 61 | Debuger.LogWarning(GetLogTag(obj), (string)message); 62 | } 63 | 64 | //---------------------------------------------------------------------- 65 | [Conditional("EnableLog")] 66 | public static void Log(this object obj, string format, params object[] args) 67 | { 68 | if (!Debuger.EnableLog) 69 | { 70 | return; 71 | } 72 | 73 | string message = string.Format(format, args); 74 | Debuger.Log(GetLogTag(obj), message); 75 | } 76 | 77 | 78 | public static void LogError(this object obj, string format, params object[] args) 79 | { 80 | string message = string.Format(format, args); 81 | Debuger.LogError(GetLogTag(obj), message); 82 | } 83 | 84 | 85 | public static void LogWarning(this object obj, string format, params object[] args) 86 | { 87 | string message = string.Format(format, args); 88 | Debuger.LogWarning(GetLogTag(obj), message); 89 | } 90 | 91 | //---------------------------------------------------------------------- 92 | private static string GetLogTag(object obj) 93 | { 94 | FieldInfo fi = obj.GetType().GetField("LOG_TAG"); 95 | if (fi != null) 96 | { 97 | return (string) fi.GetValue(obj); 98 | } 99 | 100 | return obj.GetType().Name; 101 | } 102 | 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /Assets/SGF/Debuger/Debuger.cs: -------------------------------------------------------------------------------- 1 | //////////////////////////////////////////////////////////////////// 2 | // _ooOoo_ // 3 | // o8888888o // 4 | // 88" . "88 // 5 | // (| ^_^ |) // 6 | // O\ = /O // 7 | // ____/`---'\____ // 8 | // .' \\| |// `. // 9 | // / \\||| : |||// \ // 10 | // / _||||| -:- |||||- \ // 11 | // | | \\\ - /// | | // 12 | // | \_| ''\---/'' | | // 13 | // \ .-\__ `-` ___/-. / // 14 | // ___`. .' /--.--\ `. . ___ // 15 | // ."" '< `.___\_<|>_/___.' >'"". // 16 | // | | : `- \`.;`\ _ /`;.`/ - ` : | | // 17 | // \ \ `-. \_ __\ /__ _/ .-` / / // 18 | // ========`-.____`-.___\_____/___.-`____.-'======== // 19 | // `=---=' // 20 | // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // 21 | // 佛祖保佑 无BUG 不修改 // 22 | //////////////////////////////////////////////////////////////////// 23 | /* 24 | * 描述: 25 | * 作者:slicol 26 | */ 27 | using System; 28 | using System.IO; 29 | using System.Text; 30 | 31 | namespace UnityEngine 32 | { 33 | public class Debuger 34 | { 35 | public static bool EnableLog; 36 | public static bool EnableTime = false; 37 | public static bool EnableSave = false; 38 | public static bool EnableStack = false; 39 | public static string LogFileDir = Application.persistentDataPath + "/DebugerLog/"; 40 | public static string LogFileName = ""; 41 | public static string Prefix = "> "; 42 | public static StreamWriter LogFileWriter = null; 43 | 44 | 45 | public static void Log(object message) 46 | { 47 | if (!Debuger.EnableLog) 48 | { 49 | return; 50 | } 51 | 52 | string msg = GetLogTime() + message; 53 | 54 | Debug.Log(Prefix + msg, null); 55 | LogToFile("[I]" + msg); 56 | } 57 | 58 | public static void Log(object message, Object context) 59 | { 60 | if (!Debuger.EnableLog) 61 | { 62 | return; 63 | } 64 | 65 | string msg = GetLogTime() + message; 66 | 67 | Debug.Log(Prefix + msg, context); 68 | LogToFile("[I]" + msg); 69 | } 70 | 71 | public static void LogError(object message) 72 | { 73 | string msg = GetLogTime() + message; 74 | 75 | Debug.LogError(Prefix + msg, null); 76 | LogToFile("[E]" + msg, true); 77 | } 78 | 79 | public static void LogError(object message, Object context) 80 | { 81 | string msg = GetLogTime() + message; 82 | 83 | Debug.LogError(Prefix + msg, context); 84 | LogToFile("[E]" + msg,true); 85 | } 86 | 87 | public static void LogWarning(object message) 88 | { 89 | string msg = GetLogTime() + message; 90 | 91 | Debug.LogWarning(Prefix + msg, null); 92 | LogToFile("[W]" + msg); 93 | } 94 | 95 | public static void LogWarning(object message, Object context) 96 | { 97 | string msg = GetLogTime() + message; 98 | 99 | Debug.LogWarning(Prefix + msg, context); 100 | LogToFile("[W]" + msg); 101 | } 102 | 103 | 104 | //---------------------------------------------------------------------- 105 | 106 | public static void Log(string tag, string message) 107 | { 108 | if (!Debuger.EnableLog) 109 | { 110 | return; 111 | } 112 | 113 | message = GetLogText(tag, message); 114 | Debug.Log(Prefix + message); 115 | LogToFile("[I]" + message); 116 | } 117 | 118 | public static void Log(string tag, string format, params object[] args) 119 | { 120 | if (!Debuger.EnableLog) 121 | { 122 | return; 123 | } 124 | 125 | string message = GetLogText(tag, string.Format(format, args)); 126 | Debug.Log(Prefix + message); 127 | LogToFile("[I]" + message); 128 | } 129 | 130 | public static void LogError(string tag, string message) 131 | { 132 | message = GetLogText(tag, message); 133 | Debug.LogError(Prefix + message); 134 | LogToFile("[E]" + message,true); 135 | } 136 | 137 | public static void LogError(string tag, string format, params object[] args) 138 | { 139 | string message = GetLogText(tag, string.Format(format, args)); 140 | Debug.LogError(Prefix + message); 141 | LogToFile("[E]" + message,true); 142 | } 143 | 144 | 145 | public static void LogWarning(string tag, string message) 146 | { 147 | message = GetLogText(tag, message); 148 | Debug.LogWarning(Prefix + message); 149 | LogToFile("[W]" + message); 150 | } 151 | 152 | public static void LogWarning(string tag, string format, params object[] args) 153 | { 154 | string message = GetLogText(tag, string.Format(format, args)); 155 | Debug.LogWarning(Prefix + message); 156 | LogToFile("[W]" + message); 157 | } 158 | 159 | 160 | //---------------------------------------------------------------------- 161 | private static string GetLogText(string tag, string message) 162 | { 163 | string str = ""; 164 | if (Debuger.EnableTime) 165 | { 166 | DateTime now = DateTime.Now; 167 | str = now.ToString("HH:mm:ss.fff") + " "; 168 | } 169 | 170 | str = str + tag + "::" + message; 171 | return str; 172 | } 173 | 174 | private static string GetLogTime() 175 | { 176 | string str = ""; 177 | if (Debuger.EnableTime) 178 | { 179 | DateTime now = DateTime.Now; 180 | str = now.ToString("HH:mm:ss.fff") + " "; 181 | } 182 | return str; 183 | } 184 | 185 | 186 | 187 | private static void LogToFile(string message, bool EnableStack = false) 188 | { 189 | if (!EnableSave) 190 | { 191 | return; 192 | } 193 | 194 | if (LogFileWriter == null) 195 | { 196 | DateTime now = DateTime.Now; 197 | LogFileName = now.GetDateTimeFormats('s')[0].ToString();//2005-11-05T14:06:25 198 | LogFileName = LogFileName.Replace("-", "_"); 199 | LogFileName = LogFileName.Replace(":", "_"); 200 | LogFileName = LogFileName.Replace(" ", ""); 201 | LogFileName += ".log"; 202 | 203 | string fullpath = LogFileDir + LogFileName; 204 | try 205 | { 206 | if (!Directory.Exists(LogFileDir)) 207 | { 208 | Directory.CreateDirectory(LogFileDir); 209 | } 210 | 211 | LogFileWriter = File.AppendText(fullpath); 212 | LogFileWriter.AutoFlush = true; 213 | } 214 | catch (Exception e) 215 | { 216 | LogFileWriter = null; 217 | Debug.LogError("LogToCache() " + e.Message + e.StackTrace); 218 | return; 219 | } 220 | } 221 | 222 | if (LogFileWriter != null) 223 | { 224 | try 225 | { 226 | LogFileWriter.WriteLine(message); 227 | if (EnableStack || Debuger.EnableStack) 228 | { 229 | LogFileWriter.WriteLine(StackTraceUtility.ExtractStackTrace()); 230 | } 231 | } 232 | catch (Exception) 233 | { 234 | return; 235 | } 236 | } 237 | } 238 | } 239 | } 240 | -------------------------------------------------------------------------------- /Assets/SGF/Network/KCP/KCPSocket.cs: -------------------------------------------------------------------------------- 1 | //////////////////////////////////////////////////////////////////// 2 | // _ooOoo_ // 3 | // o8888888o // 4 | // 88" . "88 // 5 | // (| ^_^ |) // 6 | // O\ = /O // 7 | // ____/`---'\____ // 8 | // .' \\| |// `. // 9 | // / \\||| : |||// \ // 10 | // / _||||| -:- |||||- \ // 11 | // | | \\\ - /// | | // 12 | // | \_| ''\---/'' | | // 13 | // \ .-\__ `-` ___/-. / // 14 | // ___`. .' /--.--\ `. . ___ // 15 | // ."" '< `.___\_<|>_/___.' >'"". // 16 | // | | : `- \`.;`\ _ /`;.`/ - ` : | | // 17 | // \ \ `-. \_ __\ /__ _/ .-` / / // 18 | // ========`-.____`-.___\_____/___.-`____.-'======== // 19 | // `=---=' // 20 | // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // 21 | // 佛祖保佑 无BUG 不修改 // 22 | //////////////////////////////////////////////////////////////////// 23 | /* 24 | * 描述: 25 | * 作者:slicol 26 | */ 27 | using System; 28 | using System.Collections.Generic; 29 | using System.Net; 30 | using System.Net.Sockets; 31 | using System.Text; 32 | using System.Threading; 33 | using UnityEngine; 34 | 35 | namespace SGF.Network.KCP 36 | { 37 | public class KCPSocket 38 | { 39 | #region 工具函数 40 | public static IPEndPoint IPEP_Any = new IPEndPoint(IPAddress.Any, 0); 41 | public static IPEndPoint IPEP_IPv6Any = new IPEndPoint(IPAddress.IPv6Any, 0); 42 | public static IPEndPoint GetIPEndPointAny(AddressFamily family, int port) 43 | { 44 | if (family == AddressFamily.InterNetwork) 45 | { 46 | if (port == 0) 47 | { 48 | return IPEP_Any; 49 | } 50 | 51 | return new IPEndPoint(IPAddress.Any, port); 52 | } 53 | else if (family == AddressFamily.InterNetworkV6) 54 | { 55 | if (port == 0) 56 | { 57 | return IPEP_IPv6Any; 58 | } 59 | 60 | return new IPEndPoint(IPAddress.IPv6Any, port); 61 | } 62 | return null; 63 | } 64 | 65 | 66 | private static readonly DateTime UTCTimeBegin = new DateTime(1970, 1, 1); 67 | 68 | public static UInt32 GetClockMS() 69 | { 70 | return (UInt32)(Convert.ToInt64(DateTime.UtcNow.Subtract(UTCTimeBegin).TotalMilliseconds) & 0xffffffff); 71 | } 72 | 73 | public delegate void KCPReceiveListener(byte[] buff, int size, IPEndPoint remotePoint); 74 | 75 | #endregion 76 | 77 | 78 | public string LOG_TAG = "KCPSocket"; 79 | 80 | private bool m_IsRunning = false; 81 | private Socket m_SystemSocket; 82 | private IPEndPoint m_LocalEndPoint; 83 | private AddressFamily m_AddrFamily; 84 | private Thread m_ThreadRecv; 85 | private byte[] m_RecvBufferTemp = new byte[4096]; 86 | 87 | //KCP参数 88 | private List m_ListKcp; 89 | private uint m_KcpKey = 0; 90 | private KCPReceiveListener m_AnyEPListener; 91 | 92 | //================================================================================= 93 | #region 构造和析构 94 | 95 | public KCPSocket(int bindPort, uint kcpKey, AddressFamily family = AddressFamily.InterNetwork) 96 | { 97 | m_AddrFamily = family; 98 | m_KcpKey = kcpKey; 99 | m_ListKcp = new List(); 100 | 101 | m_SystemSocket = new Socket(m_AddrFamily, SocketType.Dgram, ProtocolType.Udp); 102 | IPEndPoint ipep = GetIPEndPointAny(m_AddrFamily, bindPort); 103 | m_SystemSocket.Bind(ipep); 104 | 105 | bindPort = (m_SystemSocket.LocalEndPoint as IPEndPoint).Port; 106 | LOG_TAG = "KCPSocket[" + bindPort + "-" + kcpKey + "]"; 107 | 108 | m_IsRunning = true; 109 | m_ThreadRecv = new Thread(Thread_Recv) {IsBackground = true}; 110 | m_ThreadRecv.Start(); 111 | 112 | 113 | 114 | #if UNITY_EDITOR_WIN 115 | uint IOC_IN = 0x80000000; 116 | uint IOC_VENDOR = 0x18000000; 117 | uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12; 118 | m_SystemSocket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null); 119 | #endif 120 | 121 | 122 | #if UNITY_EDITOR 123 | UnityEditor.EditorApplication.playmodeStateChanged -= OnEditorPlayModeChanged; 124 | UnityEditor.EditorApplication.playmodeStateChanged += OnEditorPlayModeChanged; 125 | #endif 126 | } 127 | 128 | 129 | #if UNITY_EDITOR 130 | private void OnEditorPlayModeChanged() 131 | { 132 | if (Application.isPlaying == false) 133 | { 134 | this.Log("OnEditorPlayModeChanged()"); 135 | UnityEditor.EditorApplication.playmodeStateChanged -= OnEditorPlayModeChanged; 136 | Dispose(); 137 | } 138 | } 139 | #endif 140 | 141 | public void Dispose() 142 | { 143 | m_IsRunning = false; 144 | m_AnyEPListener = null; 145 | 146 | if (m_ThreadRecv != null) 147 | { 148 | m_ThreadRecv.Interrupt(); 149 | m_ThreadRecv = null; 150 | } 151 | 152 | int cnt = m_ListKcp.Count; 153 | for (int i = 0; i < cnt; i++) 154 | { 155 | m_ListKcp[i].Dispose(); 156 | } 157 | m_ListKcp.Clear(); 158 | 159 | if (m_SystemSocket != null) 160 | { 161 | try 162 | { 163 | m_SystemSocket.Shutdown(SocketShutdown.Both); 164 | } 165 | catch (Exception e) 166 | { 167 | this.LogWarning("Close() " + e.Message + e.StackTrace); 168 | } 169 | 170 | m_SystemSocket.Close(); 171 | m_SystemSocket = null; 172 | } 173 | } 174 | 175 | 176 | public int LocalPort 177 | { 178 | get{return (m_SystemSocket.LocalEndPoint as IPEndPoint).Port;} 179 | } 180 | 181 | public string LocalIP 182 | { 183 | get { return UnityEngine.Network.player.ipAddress; } 184 | } 185 | 186 | public IPEndPoint LocalEndPoint 187 | { 188 | get 189 | { 190 | if (m_LocalEndPoint == null || 191 | m_LocalEndPoint.Address.ToString() != UnityEngine.Network.player.ipAddress) 192 | { 193 | IPAddress ip = IPAddress.Parse(LocalIP); 194 | m_LocalEndPoint = new IPEndPoint(ip, LocalPort); 195 | } 196 | 197 | return m_LocalEndPoint; 198 | } 199 | } 200 | 201 | public Socket SystemSocket { get { return m_SystemSocket; } } 202 | 203 | #endregion 204 | 205 | //================================================================================= 206 | 207 | public bool EnableBroadcast 208 | { 209 | get { return m_SystemSocket.EnableBroadcast; } 210 | set { m_SystemSocket.EnableBroadcast = value; } 211 | } 212 | 213 | //================================================================================= 214 | #region 管理KCP 215 | 216 | private KCPProxy GetKcp(IPEndPoint ipep) 217 | { 218 | if (ipep == null || ipep.Port == 0 || 219 | ipep.Address.Equals(IPAddress.Any) || 220 | ipep.Address.Equals(IPAddress.IPv6Any)) 221 | { 222 | return null; 223 | } 224 | 225 | KCPProxy proxy; 226 | int cnt = m_ListKcp.Count; 227 | for (int i = 0; i < cnt; i++) 228 | { 229 | proxy = m_ListKcp[i]; 230 | if (proxy.RemotePoint.Equals(ipep)) 231 | { 232 | return proxy; 233 | } 234 | } 235 | 236 | proxy = new KCPProxy(m_KcpKey, ipep, m_SystemSocket); 237 | proxy.AddReceiveListener(OnReceiveAny); 238 | m_ListKcp.Add(proxy); 239 | return proxy; 240 | } 241 | 242 | #endregion 243 | 244 | //================================================================================= 245 | #region 发送逻辑 246 | public bool SendTo(byte[] buffer, int size, IPEndPoint remotePoint) 247 | { 248 | if (remotePoint.Address == IPAddress.Broadcast) 249 | { 250 | int cnt = m_SystemSocket.SendTo(buffer, size, SocketFlags.None, remotePoint); 251 | return cnt > 0; 252 | } 253 | else 254 | { 255 | KCPProxy proxy = GetKcp(remotePoint); 256 | if (proxy != null) 257 | { 258 | return proxy.DoSend(buffer, size); 259 | } 260 | } 261 | 262 | return false; 263 | } 264 | 265 | public bool SendTo(string message, IPEndPoint remotePoint) 266 | { 267 | byte[] buffer = Encoding.UTF8.GetBytes(message); 268 | return SendTo(buffer, buffer.Length, remotePoint); 269 | } 270 | 271 | #endregion 272 | 273 | 274 | //================================================================================= 275 | #region 主线程驱动 276 | 277 | public void Update() 278 | { 279 | if (m_IsRunning) 280 | { 281 | //获取时钟 282 | uint current = GetClockMS(); 283 | 284 | int cnt = m_ListKcp.Count; 285 | for (int i = 0; i < cnt; i++) 286 | { 287 | KCPProxy proxy = m_ListKcp[i]; 288 | proxy.Update(current); 289 | } 290 | } 291 | } 292 | 293 | #endregion 294 | 295 | //================================================================================= 296 | #region 接收逻辑 297 | 298 | public void AddReceiveListener(IPEndPoint remotePoint, KCPReceiveListener listener) 299 | { 300 | KCPProxy proxy = GetKcp(remotePoint); 301 | if (proxy != null) 302 | { 303 | proxy.AddReceiveListener(listener); 304 | } 305 | else 306 | { 307 | m_AnyEPListener += listener; 308 | } 309 | } 310 | 311 | public void RemoveReceiveListener(IPEndPoint remotePoint, KCPReceiveListener listener) 312 | { 313 | KCPProxy proxy = GetKcp(remotePoint); 314 | if (proxy != null) 315 | { 316 | proxy.RemoveReceiveListener(listener); 317 | } 318 | else 319 | { 320 | m_AnyEPListener -= listener; 321 | } 322 | } 323 | 324 | public void AddReceiveListener(KCPReceiveListener listener) 325 | { 326 | m_AnyEPListener += listener; 327 | } 328 | 329 | public void RemoveReceiveListener(KCPReceiveListener listener) 330 | { 331 | m_AnyEPListener -= listener; 332 | } 333 | 334 | 335 | private void OnReceiveAny(byte[] buffer, int size, IPEndPoint remotePoint) 336 | { 337 | if (m_AnyEPListener != null) 338 | { 339 | m_AnyEPListener(buffer, size, remotePoint); 340 | } 341 | } 342 | 343 | #endregion 344 | 345 | //================================================================================= 346 | #region 接收线程 347 | 348 | private void Thread_Recv() 349 | { 350 | this.Log("Thread_Recv() Begin ......"); 351 | 352 | while (m_IsRunning) 353 | { 354 | try 355 | { 356 | DoReceive(); 357 | } 358 | catch (Exception e) 359 | { 360 | this.LogError("Thread_Recv() " + e.Message + "\n" + e.StackTrace); 361 | Thread.Sleep(10); 362 | } 363 | } 364 | 365 | this.Log("Thread_Recv() End!"); 366 | } 367 | 368 | private void DoReceive() 369 | { 370 | if (m_SystemSocket.Available <= 0) 371 | { 372 | return; 373 | } 374 | 375 | EndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0); 376 | int cnt = m_SystemSocket.ReceiveFrom(m_RecvBufferTemp, m_RecvBufferTemp.Length, 377 | SocketFlags.None, ref remotePoint); 378 | 379 | if (cnt > 0) 380 | { 381 | KCPProxy proxy = GetKcp((IPEndPoint)remotePoint); 382 | if (proxy != null) 383 | { 384 | proxy.DoReceiveInThread(m_RecvBufferTemp, cnt); 385 | } 386 | } 387 | 388 | } 389 | 390 | #endregion 391 | } 392 | 393 | 394 | 395 | 396 | class KCPProxy 397 | { 398 | 399 | private KCP m_Kcp; 400 | private bool m_NeedKcpUpdateFlag = false; 401 | private uint m_NextKcpUpdateTime = 0; 402 | private SwitchQueue m_RecvQueue = new SwitchQueue(128); 403 | 404 | private IPEndPoint m_RemotePoint; 405 | private Socket m_Socket; 406 | private KCPSocket.KCPReceiveListener m_Listener; 407 | 408 | public IPEndPoint RemotePoint { get { return m_RemotePoint; } } 409 | 410 | 411 | 412 | public KCPProxy(uint key, IPEndPoint remotePoint, Socket socket) 413 | { 414 | m_Socket = socket; 415 | m_RemotePoint = remotePoint; 416 | 417 | m_Kcp = new KCP(key, HandleKcpSend); 418 | m_Kcp.NoDelay(1, 10, 2, 1); 419 | m_Kcp.WndSize(128, 128); 420 | 421 | } 422 | 423 | public void Dispose() 424 | { 425 | m_Socket = null; 426 | 427 | if (m_Kcp != null) 428 | { 429 | m_Kcp.Dispose(); 430 | m_Kcp = null; 431 | } 432 | 433 | m_Listener = null; 434 | } 435 | 436 | //--------------------------------------------- 437 | private void HandleKcpSend(byte[] buff, int size) 438 | { 439 | if (m_Socket != null) 440 | { 441 | m_Socket.SendTo(buff, 0, size, SocketFlags.None, m_RemotePoint); 442 | } 443 | } 444 | 445 | private void HandleKcpSend_Hook(byte[] buff, int size) 446 | { 447 | if (m_Socket != null) 448 | { 449 | m_Socket.SendTo(buff, 0, size, SocketFlags.None, m_RemotePoint); 450 | } 451 | } 452 | 453 | public bool DoSend(byte[] buff, int size) 454 | { 455 | m_NeedKcpUpdateFlag = true; 456 | return m_Kcp.Send(buff, size) >= 0; 457 | } 458 | 459 | //--------------------------------------------- 460 | 461 | public void AddReceiveListener(KCPSocket.KCPReceiveListener listener) 462 | { 463 | m_Listener += listener; 464 | } 465 | 466 | public void RemoveReceiveListener(KCPSocket.KCPReceiveListener listener) 467 | { 468 | m_Listener -= listener; 469 | } 470 | 471 | 472 | 473 | public void DoReceiveInThread(byte[] buffer, int size) 474 | { 475 | byte[] dst = new byte[size]; 476 | Buffer.BlockCopy(buffer, 0, dst, 0, size); 477 | m_RecvQueue.Push(dst); 478 | } 479 | 480 | private void HandleRecvQueue() 481 | { 482 | m_RecvQueue.Switch(); 483 | while (!m_RecvQueue.Empty()) 484 | { 485 | var recvBufferRaw = m_RecvQueue.Pop(); 486 | int ret = m_Kcp.Input(recvBufferRaw); 487 | 488 | //收到的不是一个正确的KCP包 489 | if (ret < 0) 490 | { 491 | if (m_Listener != null) 492 | { 493 | m_Listener(recvBufferRaw, recvBufferRaw.Length, m_RemotePoint); 494 | } 495 | return; 496 | } 497 | 498 | m_NeedKcpUpdateFlag = true; 499 | 500 | for (int size = m_Kcp.PeekSize(); size > 0; size = m_Kcp.PeekSize()) 501 | { 502 | var recvBuffer = new byte[size]; 503 | if (m_Kcp.Recv(recvBuffer) > 0) 504 | { 505 | if (m_Listener != null) 506 | { 507 | m_Listener(recvBuffer, size, m_RemotePoint); 508 | } 509 | } 510 | } 511 | } 512 | } 513 | 514 | //--------------------------------------------- 515 | public void Update(uint currentTimeMS) 516 | { 517 | HandleRecvQueue(); 518 | 519 | if (m_NeedKcpUpdateFlag || currentTimeMS >= m_NextKcpUpdateTime) 520 | { 521 | m_Kcp.Update(currentTimeMS); 522 | m_NextKcpUpdateTime = m_Kcp.Check(currentTimeMS); 523 | m_NeedKcpUpdateFlag = false; 524 | } 525 | } 526 | 527 | //--------------------------------------------- 528 | 529 | } 530 | } 531 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /Assets/SGF/Network/KCP/LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /Assets/SGF/Network/KCP/kcp.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace SGF.Network.KCP 4 | { 5 | public class KCP 6 | { 7 | public const int IKCP_RTO_NDL = 30; // no delay min rto 8 | public const int IKCP_RTO_MIN = 100; // normal min rto 9 | public const int IKCP_RTO_DEF = 200; 10 | public const int IKCP_RTO_MAX = 60000; 11 | public const int IKCP_CMD_PUSH = 81; // cmd: push data 12 | public const int IKCP_CMD_ACK = 82; // cmd: ack 13 | public const int IKCP_CMD_WASK = 83; // cmd: window probe (ask) 14 | public const int IKCP_CMD_WINS = 84; // cmd: window size (tell) 15 | public const int IKCP_ASK_SEND = 1; // need to send IKCP_CMD_WASK 16 | public const int IKCP_ASK_TELL = 2; // need to send IKCP_CMD_WINS 17 | public const int IKCP_WND_SND = 32; 18 | public const int IKCP_WND_RCV = 32; 19 | public const int IKCP_MTU_DEF = 1400; 20 | public const int IKCP_ACK_FAST = 3; 21 | public const int IKCP_INTERVAL = 100; 22 | public const int IKCP_OVERHEAD = 24; 23 | public const int IKCP_DEADLINK = 10; 24 | public const int IKCP_THRESH_INIT = 2; 25 | public const int IKCP_THRESH_MIN = 2; 26 | public const int IKCP_PROBE_INIT = 7000; // 7 secs to probe window size 27 | public const int IKCP_PROBE_LIMIT = 120000; // up to 120 secs to probe window 28 | 29 | 30 | // encode 8 bits unsigned int 31 | public static int ikcp_encode8u(byte[] p, int offset, byte c) 32 | { 33 | p[0 + offset] = c; 34 | return 1; 35 | } 36 | 37 | // decode 8 bits unsigned int 38 | public static int ikcp_decode8u(byte[] p, int offset, ref byte c) 39 | { 40 | c = p[0 + offset]; 41 | return 1; 42 | } 43 | 44 | /* encode 16 bits unsigned int (lsb) */ 45 | public static int ikcp_encode16u(byte[] p, int offset, UInt16 w) 46 | { 47 | p[0 + offset] = (byte)(w >> 0); 48 | p[1 + offset] = (byte)(w >> 8); 49 | return 2; 50 | } 51 | 52 | /* decode 16 bits unsigned int (lsb) */ 53 | public static int ikcp_decode16u(byte[] p, int offset, ref UInt16 c) 54 | { 55 | UInt16 result = 0; 56 | result |= (UInt16)p[0 + offset]; 57 | result |= (UInt16)(p[1 + offset] << 8); 58 | c = result; 59 | return 2; 60 | } 61 | 62 | /* encode 32 bits unsigned int (lsb) */ 63 | public static int ikcp_encode32u(byte[] p, int offset, UInt32 l) 64 | { 65 | p[0 + offset] = (byte)(l >> 0); 66 | p[1 + offset] = (byte)(l >> 8); 67 | p[2 + offset] = (byte)(l >> 16); 68 | p[3 + offset] = (byte)(l >> 24); 69 | return 4; 70 | } 71 | 72 | /* decode 32 bits unsigned int (lsb) */ 73 | public static int ikcp_decode32u(byte[] p, int offset, ref UInt32 c) 74 | { 75 | UInt32 result = 0; 76 | result |= (UInt32)p[0 + offset]; 77 | result |= (UInt32)(p[1 + offset] << 8); 78 | result |= (UInt32)(p[2 + offset] << 16); 79 | result |= (UInt32)(p[3 + offset] << 24); 80 | c = result; 81 | return 4; 82 | } 83 | 84 | public static byte[] slice(byte[] p, int start, int stop) 85 | { 86 | var bytes = new byte[stop - start]; 87 | Array.Copy(p, start, bytes, 0, bytes.Length); 88 | return bytes; 89 | } 90 | 91 | public static T[] slice(T[] p, int start, int stop) 92 | { 93 | var arr = new T[stop - start]; 94 | var index = 0; 95 | for (var i = start; i < stop; i++) 96 | { 97 | arr[index] = p[i]; 98 | index++; 99 | } 100 | 101 | return arr; 102 | } 103 | 104 | public static byte[] append(byte[] p, byte c) 105 | { 106 | var bytes = new byte[p.Length + 1]; 107 | Array.Copy(p, bytes, p.Length); 108 | bytes[p.Length] = c; 109 | return bytes; 110 | } 111 | 112 | public static T[] append(T[] p, T c) 113 | { 114 | var arr = new T[p.Length + 1]; 115 | for (var i = 0; i < p.Length; i++) 116 | arr[i] = p[i]; 117 | arr[p.Length] = c; 118 | return arr; 119 | } 120 | 121 | public static T[] append(T[] p, T[] cs) 122 | { 123 | var arr = new T[p.Length + cs.Length]; 124 | for (var i = 0; i < p.Length; i++) 125 | arr[i] = p[i]; 126 | for (var i = 0; i < cs.Length; i++) 127 | arr[p.Length + i] = cs[i]; 128 | return arr; 129 | } 130 | 131 | static UInt32 _imin_(UInt32 a, UInt32 b) 132 | { 133 | return a <= b ? a : b; 134 | } 135 | 136 | static UInt32 _imax_(UInt32 a, UInt32 b) 137 | { 138 | return a >= b ? a : b; 139 | } 140 | 141 | static UInt32 _ibound_(UInt32 lower, UInt32 middle, UInt32 upper) 142 | { 143 | return _imin_(_imax_(lower, middle), upper); 144 | } 145 | 146 | static Int32 _itimediff(UInt32 later, UInt32 earlier) 147 | { 148 | return ((Int32)(later - earlier)); 149 | } 150 | 151 | // KCP Segment Definition 152 | internal class Segment 153 | { 154 | internal UInt32 conv = 0; 155 | internal UInt32 cmd = 0; 156 | internal UInt32 frg = 0; 157 | internal UInt32 wnd = 0; 158 | internal UInt32 ts = 0; 159 | internal UInt32 sn = 0; 160 | internal UInt32 una = 0; 161 | internal UInt32 resendts = 0; 162 | internal UInt32 rto = 0; 163 | internal UInt32 fastack = 0; 164 | internal UInt32 xmit = 0; 165 | internal byte[] data; 166 | 167 | internal Segment(int size) 168 | { 169 | this.data = new byte[size]; 170 | } 171 | 172 | // encode a segment into buffer 173 | internal int encode(byte[] ptr, int offset) 174 | { 175 | 176 | var offset_ = offset; 177 | 178 | offset += ikcp_encode32u(ptr, offset, conv); 179 | offset += ikcp_encode8u(ptr, offset, (byte)cmd); 180 | offset += ikcp_encode8u(ptr, offset, (byte)frg); 181 | offset += ikcp_encode16u(ptr, offset, (UInt16)wnd); 182 | offset += ikcp_encode32u(ptr, offset, ts); 183 | offset += ikcp_encode32u(ptr, offset, sn); 184 | offset += ikcp_encode32u(ptr, offset, una); 185 | offset += ikcp_encode32u(ptr, offset, (UInt32)data.Length); 186 | 187 | return offset - offset_; 188 | } 189 | } 190 | 191 | // kcp members. 192 | UInt32 conv; UInt32 mtu; UInt32 mss; UInt32 state; 193 | UInt32 snd_una; UInt32 snd_nxt; UInt32 rcv_nxt; 194 | UInt32 ts_recent; UInt32 ts_lastack; UInt32 ssthresh; 195 | UInt32 rx_rttval; UInt32 rx_srtt; UInt32 rx_rto; UInt32 rx_minrto; 196 | UInt32 snd_wnd; UInt32 rcv_wnd; UInt32 rmt_wnd; UInt32 cwnd; UInt32 probe; 197 | UInt32 current; UInt32 interval; UInt32 ts_flush; UInt32 xmit; 198 | UInt32 nodelay; UInt32 updated; 199 | UInt32 ts_probe; UInt32 probe_wait; 200 | UInt32 dead_link; UInt32 incr; 201 | 202 | Segment[] snd_queue = new Segment[0]; 203 | Segment[] rcv_queue = new Segment[0]; 204 | Segment[] snd_buf = new Segment[0]; 205 | Segment[] rcv_buf = new Segment[0]; 206 | 207 | UInt32[] acklist = new UInt32[0]; 208 | 209 | byte[] buffer; 210 | Int32 fastresend; 211 | Int32 nocwnd; 212 | Int32 logmask; 213 | // buffer, size 214 | Action output; 215 | 216 | // create a new kcp control object, 'conv' must equal in two endpoint 217 | // from the same connection. 218 | public KCP(UInt32 conv_, Action output_) 219 | { 220 | conv = conv_; 221 | snd_wnd = IKCP_WND_SND; 222 | rcv_wnd = IKCP_WND_RCV; 223 | rmt_wnd = IKCP_WND_RCV; 224 | mtu = IKCP_MTU_DEF; 225 | mss = mtu - IKCP_OVERHEAD; 226 | 227 | rx_rto = IKCP_RTO_DEF; 228 | rx_minrto = IKCP_RTO_MIN; 229 | interval = IKCP_INTERVAL; 230 | ts_flush = IKCP_INTERVAL; 231 | ssthresh = IKCP_THRESH_INIT; 232 | dead_link = IKCP_DEADLINK; 233 | buffer = new byte[(mtu + IKCP_OVERHEAD) * 3]; 234 | output = output_; 235 | } 236 | 237 | public void Dispose() 238 | { 239 | output = null; 240 | } 241 | 242 | // check the size of next message in the recv queue 243 | public int PeekSize() 244 | { 245 | 246 | if (0 == rcv_queue.Length) return -1; 247 | 248 | var seq = rcv_queue[0]; 249 | 250 | if (0 == seq.frg) return seq.data.Length; 251 | 252 | if (rcv_queue.Length < seq.frg + 1) return -1; 253 | 254 | int length = 0; 255 | 256 | foreach (var item in rcv_queue) 257 | { 258 | length += item.data.Length; 259 | if (0 == item.frg) 260 | break; 261 | } 262 | 263 | return length; 264 | } 265 | 266 | // user/upper level recv: returns size, returns below zero for EAGAIN 267 | public int Recv(byte[] buffer) 268 | { 269 | 270 | if (0 == rcv_queue.Length) return -1; 271 | 272 | var peekSize = PeekSize(); 273 | if (0 > peekSize) return -2; 274 | 275 | if (peekSize > buffer.Length) return -3; 276 | 277 | var fast_recover = false; 278 | if (rcv_queue.Length >= rcv_wnd) fast_recover = true; 279 | 280 | // merge fragment. 281 | var count = 0; 282 | var n = 0; 283 | foreach (var seg in rcv_queue) 284 | { 285 | Array.Copy(seg.data, 0, buffer, n, seg.data.Length); 286 | n += seg.data.Length; 287 | count++; 288 | if (0 == seg.frg) break; 289 | } 290 | 291 | if (0 < count) 292 | { 293 | rcv_queue = slice(rcv_queue, count, rcv_queue.Length); 294 | } 295 | 296 | // move available data from rcv_buf -> rcv_queue 297 | count = 0; 298 | foreach (var seg in rcv_buf) 299 | { 300 | if (seg.sn == rcv_nxt && rcv_queue.Length < rcv_wnd) 301 | { 302 | rcv_queue = append(rcv_queue, seg); 303 | rcv_nxt++; 304 | count++; 305 | } 306 | else 307 | { 308 | break; 309 | } 310 | } 311 | 312 | if (0 < count) rcv_buf = slice(rcv_buf, count, rcv_buf.Length); 313 | 314 | // fast recover 315 | if (rcv_queue.Length < rcv_wnd && fast_recover) 316 | { 317 | // ready to send back IKCP_CMD_WINS in ikcp_flush 318 | // tell remote my window size 319 | probe |= IKCP_ASK_TELL; 320 | } 321 | 322 | return n; 323 | } 324 | 325 | // user/upper level send, returns below zero for error 326 | public int Send(byte[] buffer, int bufferSize) 327 | { 328 | 329 | if (0 == bufferSize) return -1; 330 | 331 | var count = 0; 332 | 333 | if (bufferSize < mss) 334 | count = 1; 335 | else 336 | count = (int)(bufferSize + mss - 1) / (int)mss; 337 | 338 | if (255 < count) return -2; 339 | 340 | if (0 == count) count = 1; 341 | 342 | var offset = 0; 343 | 344 | for (var i = 0; i < count; i++) 345 | { 346 | var size = 0; 347 | if (bufferSize > mss) 348 | size = (int)mss; 349 | else 350 | size = bufferSize - offset; 351 | 352 | var seg = new Segment(size); 353 | Array.Copy(buffer, offset, seg.data, 0, size); 354 | offset += size; 355 | seg.frg = (UInt32)(count - i - 1); 356 | snd_queue = append(snd_queue, seg); 357 | } 358 | 359 | return 0; 360 | } 361 | 362 | // update ack. 363 | void update_ack(Int32 rtt) 364 | { 365 | if (0 == rx_srtt) 366 | { 367 | rx_srtt = (UInt32)rtt; 368 | rx_rttval = (UInt32)rtt / 2; 369 | } 370 | else 371 | { 372 | Int32 delta = (Int32)((UInt32)rtt - rx_srtt); 373 | if (0 > delta) delta = -delta; 374 | 375 | rx_rttval = (3 * rx_rttval + (uint)delta) / 4; 376 | rx_srtt = (UInt32)((7 * rx_srtt + rtt) / 8); 377 | if (rx_srtt < 1) rx_srtt = 1; 378 | } 379 | 380 | var rto = (int)(rx_srtt + _imax_(1, 4 * rx_rttval)); 381 | rx_rto = _ibound_(rx_minrto, (UInt32)rto, IKCP_RTO_MAX); 382 | } 383 | 384 | void shrink_buf() 385 | { 386 | if (snd_buf.Length > 0) 387 | snd_una = snd_buf[0].sn; 388 | else 389 | snd_una = snd_nxt; 390 | } 391 | 392 | void parse_ack(UInt32 sn) 393 | { 394 | 395 | if (_itimediff(sn, snd_una) < 0 || _itimediff(sn, snd_nxt) >= 0) return; 396 | 397 | var index = 0; 398 | foreach (var seg in snd_buf) 399 | { 400 | if (sn == seg.sn) 401 | { 402 | snd_buf = append(slice(snd_buf, 0, index), slice(snd_buf, index + 1, snd_buf.Length)); 403 | break; 404 | } 405 | else 406 | { 407 | seg.fastack++; 408 | } 409 | 410 | index++; 411 | } 412 | } 413 | 414 | void parse_una(UInt32 una) 415 | { 416 | var count = 0; 417 | foreach (var seg in snd_buf) 418 | { 419 | if (_itimediff(una, seg.sn) > 0) 420 | count++; 421 | else 422 | break; 423 | } 424 | 425 | if (0 < count) snd_buf = slice(snd_buf, count, snd_buf.Length); 426 | } 427 | 428 | void ack_push(UInt32 sn, UInt32 ts) 429 | { 430 | acklist = append(acklist, new UInt32[2] { sn, ts }); 431 | } 432 | 433 | void ack_get(int p, ref UInt32 sn, ref UInt32 ts) 434 | { 435 | sn = acklist[p * 2 + 0]; 436 | ts = acklist[p * 2 + 1]; 437 | } 438 | 439 | void parse_data(Segment newseg) 440 | { 441 | var sn = newseg.sn; 442 | if (_itimediff(sn, rcv_nxt + rcv_wnd) >= 0 || _itimediff(sn, rcv_nxt) < 0) return; 443 | 444 | var n = rcv_buf.Length - 1; 445 | var after_idx = -1; 446 | var repeat = false; 447 | for (var i = n; i >= 0; i--) 448 | { 449 | var seg = rcv_buf[i]; 450 | if (seg.sn == sn) 451 | { 452 | repeat = true; 453 | break; 454 | } 455 | 456 | if (_itimediff(sn, seg.sn) > 0) 457 | { 458 | after_idx = i; 459 | break; 460 | } 461 | } 462 | 463 | if (!repeat) 464 | { 465 | if (after_idx == -1) 466 | rcv_buf = append(new Segment[1] { newseg }, rcv_buf); 467 | else 468 | rcv_buf = append(slice(rcv_buf, 0, after_idx + 1), append(new Segment[1] { newseg }, slice(rcv_buf, after_idx + 1, rcv_buf.Length))); 469 | } 470 | 471 | // move available data from rcv_buf -> rcv_queue 472 | var count = 0; 473 | foreach (var seg in rcv_buf) 474 | { 475 | if (seg.sn == rcv_nxt && rcv_queue.Length < rcv_wnd) 476 | { 477 | rcv_queue = append(rcv_queue, seg); 478 | rcv_nxt++; 479 | count++; 480 | } 481 | else 482 | { 483 | break; 484 | } 485 | } 486 | 487 | if (0 < count) 488 | { 489 | rcv_buf = slice(rcv_buf, count, rcv_buf.Length); 490 | } 491 | } 492 | 493 | // when you received a low level packet (eg. UDP packet), call it 494 | public int Input(byte[] data) 495 | { 496 | 497 | var s_una = snd_una; 498 | if (data.Length < IKCP_OVERHEAD) return 0; 499 | 500 | var offset = 0; 501 | 502 | while (true) 503 | { 504 | UInt32 ts = 0; 505 | UInt32 sn = 0; 506 | UInt32 length = 0; 507 | UInt32 una = 0; 508 | UInt32 conv_ = 0; 509 | 510 | UInt16 wnd = 0; 511 | 512 | byte cmd = 0; 513 | byte frg = 0; 514 | 515 | if (data.Length - offset < IKCP_OVERHEAD) break; 516 | 517 | offset += ikcp_decode32u(data, offset, ref conv_); 518 | 519 | if (conv != conv_) return -1; 520 | 521 | offset += ikcp_decode8u(data, offset, ref cmd); 522 | offset += ikcp_decode8u(data, offset, ref frg); 523 | offset += ikcp_decode16u(data, offset, ref wnd); 524 | offset += ikcp_decode32u(data, offset, ref ts); 525 | offset += ikcp_decode32u(data, offset, ref sn); 526 | offset += ikcp_decode32u(data, offset, ref una); 527 | offset += ikcp_decode32u(data, offset, ref length); 528 | 529 | if (data.Length - offset < length) return -2; 530 | 531 | switch (cmd) 532 | { 533 | case IKCP_CMD_PUSH: 534 | case IKCP_CMD_ACK: 535 | case IKCP_CMD_WASK: 536 | case IKCP_CMD_WINS: 537 | break; 538 | default: 539 | return -3; 540 | } 541 | 542 | rmt_wnd = (UInt32)wnd; 543 | parse_una(una); 544 | shrink_buf(); 545 | 546 | if (IKCP_CMD_ACK == cmd) 547 | { 548 | if (_itimediff(current, ts) >= 0) 549 | { 550 | update_ack(_itimediff(current, ts)); 551 | } 552 | parse_ack(sn); 553 | shrink_buf(); 554 | } 555 | else if (IKCP_CMD_PUSH == cmd) 556 | { 557 | if (_itimediff(sn, rcv_nxt + rcv_wnd) < 0) 558 | { 559 | ack_push(sn, ts); 560 | if (_itimediff(sn, rcv_nxt) >= 0) 561 | { 562 | var seg = new Segment((int)length); 563 | seg.conv = conv_; 564 | seg.cmd = (UInt32)cmd; 565 | seg.frg = (UInt32)frg; 566 | seg.wnd = (UInt32)wnd; 567 | seg.ts = ts; 568 | seg.sn = sn; 569 | seg.una = una; 570 | 571 | if (length > 0) Array.Copy(data, offset, seg.data, 0, length); 572 | 573 | parse_data(seg); 574 | } 575 | } 576 | } 577 | else if (IKCP_CMD_WASK == cmd) 578 | { 579 | // ready to send back IKCP_CMD_WINS in Ikcp_flush 580 | // tell remote my window size 581 | probe |= IKCP_ASK_TELL; 582 | } 583 | else if (IKCP_CMD_WINS == cmd) 584 | { 585 | // do nothing 586 | } 587 | else 588 | { 589 | return -3; 590 | } 591 | 592 | offset += (int)length; 593 | } 594 | 595 | if (_itimediff(snd_una, s_una) > 0) 596 | { 597 | if (cwnd < rmt_wnd) 598 | { 599 | var mss_ = mss; 600 | if (cwnd < ssthresh) 601 | { 602 | cwnd++; 603 | incr += mss_; 604 | } 605 | else 606 | { 607 | if (incr < mss_) 608 | { 609 | incr = mss_; 610 | } 611 | incr += (mss_ * mss_) / incr + (mss_ / 16); 612 | if ((cwnd + 1) * mss_ <= incr) cwnd++; 613 | } 614 | if (cwnd > rmt_wnd) 615 | { 616 | cwnd = rmt_wnd; 617 | incr = rmt_wnd * mss_; 618 | } 619 | } 620 | } 621 | 622 | return 0; 623 | } 624 | 625 | Int32 wnd_unused() 626 | { 627 | if (rcv_queue.Length < rcv_wnd) 628 | return (Int32)(int)rcv_wnd - rcv_queue.Length; 629 | return 0; 630 | } 631 | 632 | // flush pending data 633 | void flush() 634 | { 635 | var current_ = current; 636 | var buffer_ = buffer; 637 | var change = 0; 638 | var lost = 0; 639 | 640 | if (0 == updated) return; 641 | 642 | var seg = new Segment(0); 643 | seg.conv = conv; 644 | seg.cmd = IKCP_CMD_ACK; 645 | seg.wnd = (UInt32)wnd_unused(); 646 | seg.una = rcv_nxt; 647 | 648 | // flush acknowledges 649 | var count = acklist.Length / 2; 650 | var offset = 0; 651 | for (var i = 0; i < count; i++) 652 | { 653 | if (offset + IKCP_OVERHEAD > mtu) 654 | { 655 | output(buffer, offset); 656 | //Array.Clear(buffer, 0, offset); 657 | offset = 0; 658 | } 659 | ack_get(i, ref seg.sn, ref seg.ts); 660 | offset += seg.encode(buffer, offset); 661 | } 662 | acklist = new UInt32[0]; 663 | 664 | // probe window size (if remote window size equals zero) 665 | if (0 == rmt_wnd) 666 | { 667 | if (0 == probe_wait) 668 | { 669 | probe_wait = IKCP_PROBE_INIT; 670 | ts_probe = current + probe_wait; 671 | } 672 | else 673 | { 674 | if (_itimediff(current, ts_probe) >= 0) 675 | { 676 | if (probe_wait < IKCP_PROBE_INIT) 677 | probe_wait = IKCP_PROBE_INIT; 678 | probe_wait += probe_wait / 2; 679 | if (probe_wait > IKCP_PROBE_LIMIT) 680 | probe_wait = IKCP_PROBE_LIMIT; 681 | ts_probe = current + probe_wait; 682 | probe |= IKCP_ASK_SEND; 683 | } 684 | } 685 | } 686 | else 687 | { 688 | ts_probe = 0; 689 | probe_wait = 0; 690 | } 691 | 692 | // flush window probing commands 693 | if ((probe & IKCP_ASK_SEND) != 0) 694 | { 695 | seg.cmd = IKCP_CMD_WASK; 696 | if (offset + IKCP_OVERHEAD > (int)mtu) 697 | { 698 | output(buffer, offset); 699 | //Array.Clear(buffer, 0, offset); 700 | offset = 0; 701 | } 702 | offset += seg.encode(buffer, offset); 703 | } 704 | 705 | probe = 0; 706 | 707 | // calculate window size 708 | var cwnd_ = _imin_(snd_wnd, rmt_wnd); 709 | if (0 == nocwnd) 710 | cwnd_ = _imin_(cwnd, cwnd_); 711 | 712 | count = 0; 713 | for (var k = 0; k < snd_queue.Length; k++) 714 | { 715 | if (_itimediff(snd_nxt, snd_una + cwnd_) >= 0) break; 716 | 717 | var newseg = snd_queue[k]; 718 | newseg.conv = conv; 719 | newseg.cmd = IKCP_CMD_PUSH; 720 | newseg.wnd = seg.wnd; 721 | newseg.ts = current_; 722 | newseg.sn = snd_nxt; 723 | newseg.una = rcv_nxt; 724 | newseg.resendts = current_; 725 | newseg.rto = rx_rto; 726 | newseg.fastack = 0; 727 | newseg.xmit = 0; 728 | snd_buf = append(snd_buf, newseg); 729 | snd_nxt++; 730 | count++; 731 | } 732 | 733 | if (0 < count) 734 | { 735 | snd_queue = slice(snd_queue, count, snd_queue.Length); 736 | } 737 | 738 | // calculate resent 739 | var resent = (UInt32)fastresend; 740 | if (fastresend <= 0) resent = 0xffffffff; 741 | var rtomin = rx_rto >> 3; 742 | if (nodelay != 0) rtomin = 0; 743 | 744 | // flush data segments 745 | foreach (var segment in snd_buf) 746 | { 747 | var needsend = false; 748 | var debug = _itimediff(current_, segment.resendts); 749 | if (0 == segment.xmit) 750 | { 751 | needsend = true; 752 | segment.xmit++; 753 | segment.rto = rx_rto; 754 | segment.resendts = current_ + segment.rto + rtomin; 755 | } 756 | else if (_itimediff(current_, segment.resendts) >= 0) 757 | { 758 | needsend = true; 759 | segment.xmit++; 760 | xmit++; 761 | if (0 == nodelay) 762 | segment.rto += rx_rto; 763 | else 764 | segment.rto += rx_rto / 2; 765 | segment.resendts = current_ + segment.rto; 766 | lost = 1; 767 | } 768 | else if (segment.fastack >= resent) 769 | { 770 | needsend = true; 771 | segment.xmit++; 772 | segment.fastack = 0; 773 | segment.resendts = current_ + segment.rto; 774 | change++; 775 | } 776 | 777 | if (needsend) 778 | { 779 | segment.ts = current_; 780 | segment.wnd = seg.wnd; 781 | segment.una = rcv_nxt; 782 | 783 | var need = IKCP_OVERHEAD + segment.data.Length; 784 | if (offset + need >= mtu) 785 | { 786 | output(buffer, offset); 787 | //Array.Clear(buffer, 0, offset); 788 | offset = 0; 789 | } 790 | 791 | offset += segment.encode(buffer, offset); 792 | if (segment.data.Length > 0) 793 | { 794 | Array.Copy(segment.data, 0, buffer, offset, segment.data.Length); 795 | offset += segment.data.Length; 796 | } 797 | 798 | if (segment.xmit >= dead_link) 799 | { 800 | state = 0; 801 | } 802 | } 803 | } 804 | 805 | // flash remain segments 806 | if (offset > 0) 807 | { 808 | output(buffer, offset); 809 | //Array.Clear(buffer, 0, offset); 810 | offset = 0; 811 | } 812 | 813 | // update ssthresh 814 | if (change != 0) 815 | { 816 | var inflight = snd_nxt - snd_una; 817 | ssthresh = inflight / 2; 818 | if (ssthresh < IKCP_THRESH_MIN) 819 | ssthresh = IKCP_THRESH_MIN; 820 | cwnd = ssthresh + resent; 821 | incr = cwnd * mss; 822 | } 823 | 824 | if (lost != 0) 825 | { 826 | ssthresh = cwnd / 2; 827 | if (ssthresh < IKCP_THRESH_MIN) 828 | ssthresh = IKCP_THRESH_MIN; 829 | cwnd = 1; 830 | incr = mss; 831 | } 832 | 833 | if (cwnd < 1) 834 | { 835 | cwnd = 1; 836 | incr = mss; 837 | } 838 | } 839 | 840 | // update state (call it repeatedly, every 10ms-100ms), or you can ask 841 | // ikcp_check when to call it again (without ikcp_input/_send calling). 842 | // 'current' - current timestamp in millisec. 843 | public void Update(UInt32 current_) 844 | { 845 | 846 | current = current_; 847 | 848 | if (0 == updated) 849 | { 850 | updated = 1; 851 | ts_flush = current; 852 | } 853 | 854 | var slap = _itimediff(current, ts_flush); 855 | 856 | if (slap >= 10000 || slap < -10000) 857 | { 858 | ts_flush = current; 859 | slap = 0; 860 | } 861 | 862 | if (slap >= 0) 863 | { 864 | ts_flush += interval; 865 | if (_itimediff(current, ts_flush) >= 0) 866 | ts_flush = current + interval; 867 | flush(); 868 | } 869 | } 870 | 871 | // Determine when should you invoke ikcp_update: 872 | // returns when you should invoke ikcp_update in millisec, if there 873 | // is no ikcp_input/_send calling. you can call ikcp_update in that 874 | // time, instead of call update repeatly. 875 | // Important to reduce unnacessary ikcp_update invoking. use it to 876 | // schedule ikcp_update (eg. implementing an epoll-like mechanism, 877 | // or optimize ikcp_update when handling massive kcp connections) 878 | public UInt32 Check(UInt32 current_) 879 | { 880 | 881 | if (0 == updated) return current_; 882 | 883 | var ts_flush_ = ts_flush; 884 | var tm_flush_ = 0x7fffffff; 885 | var tm_packet = 0x7fffffff; 886 | var minimal = 0; 887 | 888 | if (_itimediff(current_, ts_flush_) >= 10000 || _itimediff(current_, ts_flush_) < -10000) 889 | { 890 | ts_flush_ = current_; 891 | } 892 | 893 | if (_itimediff(current_, ts_flush_) >= 0) return current_; 894 | 895 | tm_flush_ = (int)_itimediff(ts_flush_, current_); 896 | 897 | foreach (var seg in snd_buf) 898 | { 899 | var diff = _itimediff(seg.resendts, current_); 900 | if (diff <= 0) return current_; 901 | if (diff < tm_packet) tm_packet = (int)diff; 902 | } 903 | 904 | minimal = (int)tm_packet; 905 | if (tm_packet >= tm_flush_) minimal = (int)tm_flush_; 906 | if (minimal >= interval) minimal = (int)interval; 907 | 908 | return current_ + (UInt32)minimal; 909 | } 910 | 911 | // change MTU size, default is 1400 912 | public int SetMtu(Int32 mtu_) 913 | { 914 | if (mtu_ < 50 || mtu_ < (Int32)IKCP_OVERHEAD) return -1; 915 | 916 | var buffer_ = new byte[(mtu_ + IKCP_OVERHEAD) * 3]; 917 | if (null == buffer_) return -2; 918 | 919 | mtu = (UInt32)mtu_; 920 | mss = mtu - IKCP_OVERHEAD; 921 | buffer = buffer_; 922 | return 0; 923 | } 924 | 925 | public int Interval(Int32 interval_) 926 | { 927 | if (interval_ > 5000) 928 | { 929 | interval_ = 5000; 930 | } 931 | else if (interval_ < 10) 932 | { 933 | interval_ = 10; 934 | } 935 | interval = (UInt32)interval_; 936 | return 0; 937 | } 938 | 939 | // fastest: ikcp_nodelay(kcp, 1, 20, 2, 1) 940 | // nodelay: 0:disable(default), 1:enable 941 | // interval: internal update timer interval in millisec, default is 100ms 942 | // resend: 0:disable fast resend(default), 1:enable fast resend 943 | // nc: 0:normal congestion control(default), 1:disable congestion control 944 | public int NoDelay(int nodelay_, int interval_, int resend_, int nc_) 945 | { 946 | 947 | if (nodelay_ > 0) 948 | { 949 | nodelay = (UInt32)nodelay_; 950 | if (nodelay_ != 0) 951 | rx_minrto = IKCP_RTO_NDL; 952 | else 953 | rx_minrto = IKCP_RTO_MIN; 954 | } 955 | 956 | if (interval_ >= 0) 957 | { 958 | if (interval_ > 5000) 959 | { 960 | interval_ = 5000; 961 | } 962 | else if (interval_ < 10) 963 | { 964 | interval_ = 10; 965 | } 966 | interval = (UInt32)interval_; 967 | } 968 | 969 | if (resend_ >= 0) fastresend = resend_; 970 | 971 | if (nc_ >= 0) nocwnd = nc_; 972 | 973 | return 0; 974 | } 975 | 976 | // set maximum window size: sndwnd=32, rcvwnd=32 by default 977 | public int WndSize(int sndwnd, int rcvwnd) 978 | { 979 | if (sndwnd > 0) 980 | snd_wnd = (UInt32)sndwnd; 981 | 982 | if (rcvwnd > 0) 983 | rcv_wnd = (UInt32)rcvwnd; 984 | return 0; 985 | } 986 | 987 | // get how many packet is waiting to be sent 988 | public int WaitSnd() 989 | { 990 | return snd_buf.Length + snd_queue.Length; 991 | } 992 | } 993 | 994 | 995 | } 996 | --------------------------------------------------------------------------------