├── bin ├── libudpkit_ios.a ├── libudpkit_android.so └── libudpkit_win32.dll ├── proj ├── android │ ├── libs │ │ └── android-support-v4.jar │ ├── res │ │ ├── values │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ ├── drawable-hdpi │ │ │ └── ic_launcher.png │ │ ├── drawable-mdpi │ │ │ └── ic_launcher.png │ │ ├── drawable-xhdpi │ │ │ └── ic_launcher.png │ │ ├── values-v11 │ │ │ └── styles.xml │ │ └── values-v14 │ │ │ └── styles.xml │ ├── .settings │ │ └── org.eclipse.jdt.core.prefs │ ├── gen │ │ └── fholm │ │ │ └── udpkit │ │ │ └── nativeandroid │ │ │ ├── BuildConfig.java │ │ │ └── R.java │ ├── jni │ │ └── Android.mk │ ├── .classpath │ ├── AndroidManifest.xml │ ├── project.properties │ └── .project ├── ios │ └── udpkit_ios.xcodeproj │ │ ├── project.xcworkspace │ │ └── contents.xcworkspacedata │ │ └── xcuserdata │ │ └── fredrik.xcuserdatad │ │ └── xcschemes │ │ ├── xcschememanagement.plist │ │ └── udpkit_ios.xcscheme ├── win32 │ ├── libudpkit_win32.sln │ ├── libudpkit_win32.vcxproj.filters │ └── libudpkit_win32.vcxproj └── managed │ ├── udpkit.unity.csproj │ ├── udpkit.platform.managed.csproj │ ├── udpkit.platform.ios.csproj │ ├── udpkit.platform.android.csproj │ ├── udpkit.dev.csproj │ ├── udpkit.platform.win32.csproj │ ├── udpkit.examples.chat.csproj │ ├── udpkit.examples.simple.csproj │ ├── udpkit.stresstest.csproj │ └── udpkit.csproj ├── src ├── udpkit.examples.unity │ ├── Assets │ │ ├── Scene.unity │ │ ├── Scene.unity.meta │ │ ├── Plugins.meta │ │ ├── Plugins │ │ │ ├── iOS │ │ │ │ └── libudpkit_ios.a │ │ │ ├── iOS.meta │ │ │ ├── Android.meta │ │ │ ├── Android │ │ │ │ ├── libudpkit_android.so.meta │ │ │ │ └── libudpkit_android.so │ │ │ ├── udpUnityUtils.cs.meta │ │ │ └── udpUnityUtils.cs │ │ ├── demoGUI.cs.meta │ │ ├── demoPeer.cs.meta │ │ ├── demoSerializer.cs.meta │ │ ├── demoSerializer.cs │ │ ├── demoGUI.cs │ │ └── demoPeer.cs │ └── ProjectSettings │ │ ├── AudioManager.asset │ │ ├── InputManager.asset │ │ ├── TagManager.asset │ │ ├── TimeManager.asset │ │ ├── EditorSettings.asset │ │ ├── NavMeshLayers.asset │ │ ├── NetworkManager.asset │ │ ├── DynamicsManager.asset │ │ ├── GraphicsSettings.asset │ │ ├── Physics2DSettings.asset │ │ ├── ProjectSettings.asset │ │ ├── QualitySettings.asset │ │ └── EditorBuildSettings.asset ├── udpkit.dev │ ├── App.config │ ├── Properties │ │ └── AssemblyInfo.cs │ └── main.cs ├── udpkit.stresstest │ ├── App.config │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── udpSequenceGenerator.cs │ ├── udpRecvChannel.cs │ ├── udpSendChannel.cs │ └── Program.cs ├── udpkit.examples.chat │ ├── App.config │ ├── Properties │ │ └── AssemblyInfo.cs │ └── Program.cs ├── udpkit.examples.simple │ ├── App.config │ ├── Properties │ │ └── AssemblyInfo.cs │ └── Program.cs ├── udpkit │ ├── udpPrecisionTimer.cs │ ├── udpSendHandle.cs │ ├── udpCommand.cs │ ├── udpException.cs │ ├── udpUtils.cs │ ├── udpConnectionStats.cs │ ├── udpPlatform.cs │ ├── udpSocketMultiplexer.cs │ ├── udpAssert.cs │ ├── udpSet.cs │ ├── udpRingBuffer.cs │ ├── udpSerializer.cs │ ├── udpHeader.cs │ ├── udpEndpoint.cs │ ├── udpAddress.cs │ ├── udpMath.cs │ ├── udpLog.cs │ ├── udpByteConverter.cs │ ├── udpEvent.cs │ └── udpConfig.cs ├── AssemblyInfo.cs ├── udpkit.lib │ ├── timers.h │ ├── common.cpp │ ├── timers.cpp │ ├── socket.h │ ├── common.h │ └── socket.cpp ├── udpkit.platform.managed │ ├── udpPrecisionTimer.cs │ └── udpPlatformManaged.cs ├── udpkit.platform.native │ ├── udpNativeInvoke.cs │ └── udpPlatformNative.cs └── slimmath │ └── half.cs ├── .gitignore ├── license.txt ├── readme.txt └── .gitattributes /bin/libudpkit_ios.a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/bin/libudpkit_ios.a -------------------------------------------------------------------------------- /bin/libudpkit_android.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/bin/libudpkit_android.so -------------------------------------------------------------------------------- /bin/libudpkit_win32.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/bin/libudpkit_win32.dll -------------------------------------------------------------------------------- /proj/android/libs/android-support-v4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/proj/android/libs/android-support-v4.jar -------------------------------------------------------------------------------- /proj/android/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | udpkit.nativeAndroid 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/udpkit.examples.unity/Assets/Scene.unity: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/src/udpkit.examples.unity/Assets/Scene.unity -------------------------------------------------------------------------------- /proj/android/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/proj/android/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /proj/android/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/proj/android/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /proj/android/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/proj/android/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /src/udpkit.examples.unity/Assets/Scene.unity.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 1b1a4947fa21b294fa81217bbb3530ba 3 | DefaultImporter: 4 | userData: 5 | -------------------------------------------------------------------------------- /src/udpkit.examples.unity/Assets/Plugins.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 533ea146ea42f174497fed515e1fe915 3 | folderAsset: yes 4 | DefaultImporter: 5 | userData: 6 | -------------------------------------------------------------------------------- /src/udpkit.examples.unity/Assets/Plugins/iOS/libudpkit_ios.a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/src/udpkit.examples.unity/Assets/Plugins/iOS/libudpkit_ios.a -------------------------------------------------------------------------------- /src/udpkit.examples.unity/ProjectSettings/AudioManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/src/udpkit.examples.unity/ProjectSettings/AudioManager.asset -------------------------------------------------------------------------------- /src/udpkit.examples.unity/ProjectSettings/InputManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/src/udpkit.examples.unity/ProjectSettings/InputManager.asset -------------------------------------------------------------------------------- /src/udpkit.examples.unity/ProjectSettings/TagManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/src/udpkit.examples.unity/ProjectSettings/TagManager.asset -------------------------------------------------------------------------------- /src/udpkit.examples.unity/ProjectSettings/TimeManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/src/udpkit.examples.unity/ProjectSettings/TimeManager.asset -------------------------------------------------------------------------------- /src/udpkit.examples.unity/Assets/Plugins/iOS.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 9145911a2083dfb4885e726cad0deafa 3 | folderAsset: yes 4 | DefaultImporter: 5 | userData: 6 | -------------------------------------------------------------------------------- /src/udpkit.examples.unity/ProjectSettings/EditorSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/src/udpkit.examples.unity/ProjectSettings/EditorSettings.asset -------------------------------------------------------------------------------- /src/udpkit.examples.unity/ProjectSettings/NavMeshLayers.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/src/udpkit.examples.unity/ProjectSettings/NavMeshLayers.asset -------------------------------------------------------------------------------- /src/udpkit.examples.unity/ProjectSettings/NetworkManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/src/udpkit.examples.unity/ProjectSettings/NetworkManager.asset -------------------------------------------------------------------------------- /src/udpkit.examples.unity/Assets/Plugins/Android.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: be645715ece3c0e44bf320ea13c53233 3 | folderAsset: yes 4 | DefaultImporter: 5 | userData: 6 | -------------------------------------------------------------------------------- /src/udpkit.examples.unity/Assets/Plugins/Android/libudpkit_android.so.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: f92d336c7da2c7c4284eebb942952fb7 3 | DefaultImporter: 4 | userData: 5 | -------------------------------------------------------------------------------- /src/udpkit.examples.unity/ProjectSettings/DynamicsManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/src/udpkit.examples.unity/ProjectSettings/DynamicsManager.asset -------------------------------------------------------------------------------- /src/udpkit.examples.unity/ProjectSettings/GraphicsSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/src/udpkit.examples.unity/ProjectSettings/GraphicsSettings.asset -------------------------------------------------------------------------------- /src/udpkit.examples.unity/ProjectSettings/Physics2DSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/src/udpkit.examples.unity/ProjectSettings/Physics2DSettings.asset -------------------------------------------------------------------------------- /src/udpkit.examples.unity/ProjectSettings/ProjectSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/src/udpkit.examples.unity/ProjectSettings/ProjectSettings.asset -------------------------------------------------------------------------------- /src/udpkit.examples.unity/ProjectSettings/QualitySettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/src/udpkit.examples.unity/ProjectSettings/QualitySettings.asset -------------------------------------------------------------------------------- /src/udpkit.examples.unity/ProjectSettings/EditorBuildSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/src/udpkit.examples.unity/ProjectSettings/EditorBuildSettings.asset -------------------------------------------------------------------------------- /src/udpkit.examples.unity/Assets/Plugins/Android/libudpkit_android.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanhaiwang/udpkit/HEAD/src/udpkit.examples.unity/Assets/Plugins/Android/libudpkit_android.so -------------------------------------------------------------------------------- /src/udpkit.dev/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/udpkit.stresstest/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/udpkit.examples.chat/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/udpkit.examples.simple/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /proj/android/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 3 | org.eclipse.jdt.core.compiler.compliance=1.6 4 | org.eclipse.jdt.core.compiler.source=1.6 5 | -------------------------------------------------------------------------------- /proj/android/gen/fholm/udpkit/nativeandroid/BuildConfig.java: -------------------------------------------------------------------------------- 1 | /** Automatically generated file. DO NOT MODIFY */ 2 | package fholm.udpkit.nativeandroid; 3 | 4 | public final class BuildConfig { 5 | public final static boolean DEBUG = true; 6 | } -------------------------------------------------------------------------------- /proj/ios/udpkit_ios.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/udpkit.examples.unity/Assets/demoGUI.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 7d076d2a770cd0f42950a7ab8a43b228 3 | MonoImporter: 4 | serializedVersion: 2 5 | defaultReferences: [] 6 | executionOrder: 0 7 | icon: {instanceID: 0} 8 | userData: 9 | -------------------------------------------------------------------------------- /src/udpkit.examples.unity/Assets/demoPeer.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: cae2093199fb7f9409d0532c1a5f0b88 3 | MonoImporter: 4 | serializedVersion: 2 5 | defaultReferences: [] 6 | executionOrder: 0 7 | icon: {instanceID: 0} 8 | userData: 9 | -------------------------------------------------------------------------------- /src/udpkit.examples.unity/Assets/demoSerializer.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 0c11bc30f61a8624fa51deaa703b870d 3 | MonoImporter: 4 | serializedVersion: 2 5 | defaultReferences: [] 6 | executionOrder: 0 7 | icon: {instanceID: 0} 8 | userData: 9 | -------------------------------------------------------------------------------- /src/udpkit.examples.unity/Assets/Plugins/udpUnityUtils.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 986c3cf193970e043964d43f55979b92 3 | MonoImporter: 4 | serializedVersion: 2 5 | defaultReferences: [] 6 | executionOrder: 0 7 | icon: {instanceID: 0} 8 | userData: 9 | -------------------------------------------------------------------------------- /proj/android/jni/Android.mk: -------------------------------------------------------------------------------- 1 | LOCAL_PATH := $(call my-dir) 2 | include $(CLEAR_VARS) 3 | LOCAL_LDLIBS := -llog 4 | LOCAL_MODULE := udpkit_android 5 | LOCAL_SRC_FILES := ../../../src/udpkit.lib/common.cpp ../../../src/udpkit.lib/socket.cpp ../../../src/udpkit.lib/timers.cpp 6 | include $(BUILD_SHARED_LIBRARY) -------------------------------------------------------------------------------- /proj/android/res/values-v11/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/udpkit.examples.unity/Assets/demoSerializer.cs: -------------------------------------------------------------------------------- 1 | using UdpKit; 2 | 3 | public class demoSerializer : UdpSerializer { 4 | public override bool Pack (ref UdpBitStream stream, ref object o) { 5 | throw new System.NotImplementedException(); 6 | } 7 | 8 | public override bool Unpack (ref UdpBitStream stream, ref object o) { 9 | throw new System.NotImplementedException(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /proj/android/res/values-v14/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /proj/android/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/udpkit/udpPrecisionTimer.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | 3 | namespace udpkit { 4 | class udpPrecisionTimer { 5 | static readonly long start = Stopwatch.GetTimestamp(); 6 | static readonly double freq = 1.0 / (double) Stopwatch.Frequency; 7 | 8 | internal static uint getCurrentTime () { 9 | long diff = Stopwatch.GetTimestamp() - start; 10 | double seconds = (double) diff * freq; 11 | return (uint) (seconds * 1000.0); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.suo 2 | obj 3 | bin 4 | *.userprefs 5 | *tlog* 6 | *.log 7 | *.obj 8 | *.idb 9 | *.pdb 10 | *.user 11 | *.sdf 12 | *.opensdf 13 | *.exp 14 | *.ilk 15 | *.lib 16 | *.dll 17 | *.pidb 18 | *.dll.meta 19 | *.a 20 | *.a.meta 21 | *swp 22 | *.so 23 | *.xcuserstate 24 | *.xckptlist 25 | *.xccheckout 26 | src/udpkit.examples.unity/*_Data/* 27 | src/udpkit.examples.unity/*.exe 28 | src/udpkit.examples.unity/Library 29 | src/udpkit.examples.unity/Temp 30 | src/udpkit.examples.unity/*.sln 31 | src/udpkit.examples.unity/*.csproj 32 | -------------------------------------------------------------------------------- /proj/android/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 9 | 10 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /proj/android/project.properties: -------------------------------------------------------------------------------- 1 | # This file is automatically generated by Android Tools. 2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED! 3 | # 4 | # This file must be checked in Version Control Systems. 5 | # 6 | # To customize properties used by the Ant build system edit 7 | # "ant.properties", and override values to adapt the script to your 8 | # project structure. 9 | # 10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): 11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt 12 | 13 | # Project target. 14 | target=android-19 15 | android.library=true 16 | -------------------------------------------------------------------------------- /proj/ios/udpkit_ios.xcodeproj/xcuserdata/fredrik.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | udpkit_ios.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 35D9975C184F59E6008F33D2 16 | 17 | primary 18 | 19 | 20 | 35D9976C184F59E6008F33D2 21 | 22 | primary 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /proj/android/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 14 | 15 | 16 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/udpkit.examples.unity/Assets/demoGUI.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | public class demoGUI : MonoBehaviour { 4 | 5 | void OnGUI () { 6 | float w = Screen.width; 7 | float h = Screen.height; 8 | float buttonHeight = h * 0.2f; 9 | float buttonWidth = w * 0.35f; 10 | float buttonMarginLR = w * 0.1f; 11 | float buttonMarginTB = h * 0.4f; 12 | 13 | if (GUI.Button(new Rect(buttonMarginLR, buttonMarginTB, buttonWidth, buttonHeight), "Server")) { 14 | gameObject.AddComponent().isServer = true; 15 | } 16 | 17 | if (GUI.Button(new Rect(buttonMarginLR + buttonWidth + buttonMarginLR, buttonMarginTB, buttonWidth, buttonHeight), "Client")) { 18 | gameObject.AddComponent().isServer = false; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/udpkit.examples.unity/Assets/Plugins/udpUnityUtils.cs: -------------------------------------------------------------------------------- 1 | using UdpKit; 2 | 3 | public static class UdpKitUnityUtils { 4 | public static UdpSocket CreatePlatformSpecificSocket () where TSerializer : UdpSerializer, new() { 5 | return CreatePlatformSpecificSocket(new UdpConfig()); 6 | } 7 | 8 | public static UdpSocket CreatePlatformSpecificSocket (UdpConfig config) where TSerializer : UdpSerializer, new() { 9 | #if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBPLAYER 10 | return UdpSocket.Create(config); 11 | #elif UNITY_IPHONE 12 | return UdpSocket.Create(config); 13 | #elif UNITY_ANDROID 14 | return UdpSocket.Create(config); 15 | #else 16 | throw new System.NotImplementedException ("UdpKit doesn't support the current platform"); 17 | #endif 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /proj/android/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | udpkit.nativeAndroid 4 | 5 | 6 | 7 | 8 | 9 | com.android.ide.eclipse.adt.ResourceManagerBuilder 10 | 11 | 12 | 13 | 14 | com.android.ide.eclipse.adt.PreCompilerBuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.jdt.core.javabuilder 20 | 21 | 22 | 23 | 24 | com.android.ide.eclipse.adt.ApkBuilder 25 | 26 | 27 | 28 | 29 | 30 | com.android.ide.eclipse.adt.AndroidNature 31 | org.eclipse.jdt.core.javanature 32 | 33 | 34 | -------------------------------------------------------------------------------- /proj/win32/libudpkit_win32.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.21005.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libudpkit_win32", "libudpkit_win32.vcxproj", "{085D3B6D-76D2-4DCD-879C-257B170FBEC5}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Win32 = Debug|Win32 11 | Release|Win32 = Release|Win32 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {085D3B6D-76D2-4DCD-879C-257B170FBEC5}.Debug|Win32.ActiveCfg = Debug|Win32 15 | {085D3B6D-76D2-4DCD-879C-257B170FBEC5}.Debug|Win32.Build.0 = Debug|Win32 16 | {085D3B6D-76D2-4DCD-879C-257B170FBEC5}.Release|Win32.ActiveCfg = Release|Win32 17 | {085D3B6D-76D2-4DCD-879C-257B170FBEC5}.Release|Win32.Build.0 = Release|Win32 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. -------------------------------------------------------------------------------- /readme.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. -------------------------------------------------------------------------------- /src/udpkit.examples.unity/Assets/demoPeer.cs: -------------------------------------------------------------------------------- 1 | using UdpKit; 2 | using UnityEngine; 3 | 4 | public class demoPeer : MonoBehaviour { 5 | UdpSocket socket; 6 | 7 | [HideInInspector] 8 | internal bool isServer; 9 | 10 | [HideInInspector] 11 | internal string serverAddress = "127.0.0.1:14000"; 12 | 13 | void Awake () { 14 | UdpLog.SetWriter(s => Debug.Log(s)); 15 | } 16 | 17 | void Start () { 18 | socket = UdpKitUnityUtils.CreatePlatformSpecificSocket(); 19 | 20 | if (isServer) { 21 | socket.Start(new UdpEndPoint(serverAddress)); 22 | } else { 23 | socket.Start(UdpEndPoint.Any); 24 | socket.Connect(new UdpEndPoint(serverAddress)); 25 | } 26 | } 27 | 28 | void OnDestroy () { 29 | socket.Close(); 30 | } 31 | 32 | void Update () { 33 | UdpEvent ev = default(UdpEvent); 34 | 35 | while (socket.Poll(ref ev)) { 36 | switch (ev.EventType) { 37 | case UdpEventType.Connected: 38 | UdpLog.User("Client connect from {0}", ev.Connection.RemoteEndPoint); 39 | break; 40 | } 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | #if UDPKIT_DLL_UDPKIT 6 | [assembly: AssemblyTitle("udpkit")] 7 | [assembly: AssemblyProduct("udpkit")] 8 | #elif UDPKIT_DLL_PLATFORM_ANDROID 9 | [assembly: AssemblyTitle("udpkit.platform.android")] 10 | [assembly: AssemblyProduct("udpkit.platform.android")] 11 | #elif UDPKIT_DLL_PLATFORM_IOS 12 | [assembly: AssemblyTitle("udpkit.platform.ios")] 13 | [assembly: AssemblyProduct("udpkit.platform.ios")] 14 | #elif UDPKIT_DLL_PLATFORM_WIN32 15 | [assembly: AssemblyTitle("udpkit.platform.win32")] 16 | [assembly: AssemblyProduct("udpkit.platform.win32")] 17 | #elif UDPKIT_DLL_PLATFORM_MANAGED 18 | [assembly: AssemblyTitle("udpkit.platform.managed")] 19 | [assembly: AssemblyProduct("udpkit.platform.managed")] 20 | #elif UDPKIT_DLL_UNITY 21 | [assembly: AssemblyTitle("udpkit.unity")] 22 | [assembly: AssemblyProduct("udpkit.unity")] 23 | #endif 24 | 25 | [assembly: AssemblyDescription(".Net/Mono/Unity networking library for games")] 26 | [assembly: AssemblyConfiguration("")] 27 | [assembly: AssemblyCompany("")] 28 | [assembly: AssemblyCopyright("Copyright © 2012-2013 Fredrik Holmstrom")] 29 | [assembly: AssemblyTrademark("")] 30 | [assembly: AssemblyCulture("")] 31 | [assembly: ComVisible(false)] 32 | [assembly: AssemblyVersion("0.1.0.0")] 33 | [assembly: AssemblyFileVersion("0.1.0.0")] 34 | -------------------------------------------------------------------------------- /src/udpkit.lib/timers.h: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | #include "common.h" 26 | #include 27 | 28 | #ifdef UDPKIT_IOS 29 | #include 30 | #endif 31 | 32 | #ifndef UDPKIT_WIN 33 | EXPORT_API U32 udpGetHighPrecisionTime(); 34 | #endif 35 | -------------------------------------------------------------------------------- /src/udpkit/udpSendHandle.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | namespace UdpKit { 26 | struct UdpHandle { 27 | public uint SendTime; 28 | public ushort ObjSequence; 29 | public bool IsObject; 30 | public object Object; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/udpkit/udpCommand.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | namespace UdpKit { 26 | internal enum UdpCommandType : byte { 27 | Connect = 2, 28 | Accepted = 4, 29 | Refused = 6, 30 | Disconnected = 8, 31 | Ping = 10, 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/udpkit.dev/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("udpkitdev")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("udpkitdev")] 13 | [assembly: AssemblyCopyright("Copyright © 2013")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("06be3e38-9839-4281-b1d2-b996e866564b")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /src/udpkit.stresstest/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("udpkit.stresstest")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("udpkit.stresstest")] 13 | [assembly: AssemblyCopyright("Copyright © 2013")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("cf1f9691-e683-4bf8-a1a1-f6bb190e02e6")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /src/udpkit.examples.chat/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("udpkit.examples.complete")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("udpkit.examples.complete")] 13 | [assembly: AssemblyCopyright("Copyright © 2013")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("06964735-49d3-49ce-bd95-1e7411192d78")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /src/udpkit.examples.simple/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("udpkit.examples.simple")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("udpkit.examples.simple")] 13 | [assembly: AssemblyCopyright("Copyright © 2013")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("47576deb-2282-493c-a582-b8cb00215a32")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /src/udpkit/udpException.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System; 26 | 27 | namespace UdpKit { 28 | public class UdpException : Exception { 29 | internal UdpException () : base() { } 30 | internal UdpException (string msg) : base(msg) { } 31 | internal UdpException (string fmt, params object[] args) : this(string.Format(fmt, args)) { } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /proj/win32/libudpkit_win32.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Header Files 20 | 21 | 22 | Header Files 23 | 24 | 25 | Header Files 26 | 27 | 28 | 29 | 30 | Source Files 31 | 32 | 33 | Source Files 34 | 35 | 36 | Source Files 37 | 38 | 39 | -------------------------------------------------------------------------------- /src/udpkit/udpUtils.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System; 26 | using System.Diagnostics; 27 | using System.Threading; 28 | 29 | namespace UdpKit { 30 | internal static class UdpUtils { 31 | /* 32 | public static int enumToInt (T value) where T : struct { 33 | throw new NotImplementedException(); 34 | } 35 | 36 | public static T intToEnum (int value) where T : struct { 37 | throw new NotImplementedException(); 38 | } 39 | */ 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /proj/android/gen/fholm/udpkit/nativeandroid/R.java: -------------------------------------------------------------------------------- 1 | /* AUTO-GENERATED FILE. DO NOT MODIFY. 2 | * 3 | * This class was automatically generated by the 4 | * aapt tool from the resource data it found. It 5 | * should not be modified by hand. 6 | */ 7 | 8 | package fholm.udpkit.nativeandroid; 9 | 10 | public final class R { 11 | public static final class attr { 12 | } 13 | public static final class drawable { 14 | public static int ic_launcher=0x7f020000; 15 | } 16 | public static final class string { 17 | public static int app_name=0x7f030000; 18 | } 19 | public static final class style { 20 | /** 21 | Base application theme, dependent on API level. This theme is replaced 22 | by AppBaseTheme from res/values-vXX/styles.xml on newer devices. 23 | 24 | 25 | Theme customizations available in newer API levels can go in 26 | res/values-vXX/styles.xml, while customizations related to 27 | backward-compatibility can go here. 28 | 29 | 30 | Base application theme for API 11+. This theme completely replaces 31 | AppBaseTheme from res/values/styles.xml on API 11+ devices. 32 | 33 | API 11 theme customizations can go here. 34 | 35 | Base application theme for API 14+. This theme completely replaces 36 | AppBaseTheme from BOTH res/values/styles.xml and 37 | res/values-v11/styles.xml on API 14+ devices. 38 | 39 | API 14 theme customizations can go here. 40 | */ 41 | public static int AppBaseTheme=0x7f040000; 42 | /** Application theme. 43 | All customizations that are NOT specific to a particular API-level can go here. 44 | */ 45 | public static int AppTheme=0x7f040001; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/udpkit.platform.managed/udpPrecisionTimer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System.Diagnostics; 26 | 27 | namespace UdpKit { 28 | class UdpPrecisionTimer { 29 | static readonly long start = Stopwatch.GetTimestamp(); 30 | static readonly double freq = 1.0 / (double) Stopwatch.Frequency; 31 | 32 | internal static uint GetCurrentTime () { 33 | long diff = Stopwatch.GetTimestamp() - start; 34 | double seconds = (double) diff * freq; 35 | return (uint) (seconds * 1000.0); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/udpkit.lib/common.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | #include "common.h" 26 | 27 | EXPORT_API const char* udpPlatform() { 28 | #ifdef UDPKIT_WIN32 29 | return "win32"; 30 | #elif UDPKIT_WIN64 31 | return "win64"; 32 | #elif UDPKIT_IOS_SIMULATOR 33 | return "ios_simulator"; 34 | #elif UDPKIT_IOS 35 | return "ios"; 36 | #elif UDPKIT_OSX 37 | return "osx"; 38 | #elif UDPKIT_ANDROID 39 | return "android"; 40 | #elif UDPKIT_LINUX 41 | return "linux"; 42 | #else 43 | return "unknown"; 44 | #endif 45 | } 46 | 47 | EXPORT_API const char* udpPlatformErrorString(int errorCode) { 48 | return strerror(errorCode); 49 | } -------------------------------------------------------------------------------- /src/udpkit.stresstest/udpSequenceGenerator.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | namespace UdpKit.stresstest { 26 | struct udpSequenceGenerator { 27 | uint mask; 28 | uint sequence; 29 | 30 | public udpSequenceGenerator (int bits) 31 | : this(bits, 0u) { 32 | } 33 | 34 | public udpSequenceGenerator (int bits, uint start) { 35 | mask = (1u << bits) - 1u; 36 | sequence = start & mask; 37 | } 38 | 39 | public uint next () { 40 | sequence += 1u; 41 | sequence &= mask; 42 | return sequence; 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /src/udpkit/udpConnectionStats.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | namespace UdpKit { 26 | public struct UdpConnectionStats { 27 | public uint BytesSent; 28 | public uint BytesReceived; 29 | public uint PacketsSent; 30 | public uint PacketsLost; 31 | public uint PacketsDelivered; 32 | public uint PacketsReceived; 33 | public uint CommandSent; 34 | public uint CommandsReceived; 35 | 36 | internal void PacketReceived () { 37 | PacketsReceived += 1; 38 | } 39 | 40 | internal void PacketSent () { 41 | PacketsSent += 1; 42 | } 43 | 44 | internal void PacketLost () { 45 | PacketsLost += 1; 46 | } 47 | 48 | internal void PacketDelivered () { 49 | PacketsDelivered += 1; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/udpkit/udpPlatform.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | namespace UdpKit { 26 | public enum UdpSocketInterfaceError { 27 | None = 0, 28 | Unknown = 1, 29 | WouldBlock = 2 30 | } 31 | 32 | public abstract class UdpPlatform { 33 | public abstract UdpSocketInterfaceError Error { get; } 34 | public abstract UdpEndPoint EndPoint { get; } 35 | public abstract long PlatformError { get; } 36 | public abstract string PlatformErrorString { get; } 37 | public abstract uint PlatformPrecisionTime { get; } 38 | public abstract bool Close (); 39 | public abstract bool Bind (UdpEndPoint endpoing); 40 | public abstract bool RecvPoll (int timeoutInMs); 41 | public abstract bool RecvFrom (byte[] buffer, int bufferSize, ref int bytesReceived, ref UdpEndPoint remoteEndpoint); 42 | public abstract bool SendTo (byte[] buffer, int bytesToSend, UdpEndPoint endpoint, ref int bytesSent); 43 | } 44 | } -------------------------------------------------------------------------------- /src/udpkit/udpSocketMultiplexer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System; 26 | using System.Collections.Generic; 27 | using System.Threading; 28 | 29 | namespace UdpKit { 30 | public class UdpSocketMultiplexer { 31 | 32 | int index; 33 | UdpSocket[] sockets; 34 | 35 | internal UdpSocketMultiplexer (params UdpSocket[] sockets) { 36 | this.index = 0; 37 | this.sockets = sockets; 38 | } 39 | 40 | public bool Poll (ref UdpEvent ev) { 41 | bool allowRestart = true; 42 | 43 | RESTART: 44 | for (int i = index; i < sockets.Length; ++i) { 45 | if (sockets[i].Poll(ref ev)) { 46 | index = i + 1; 47 | return true; 48 | } 49 | } 50 | 51 | if (allowRestart) { 52 | index = 0; 53 | allowRestart = false; 54 | goto RESTART; 55 | } 56 | 57 | return false; 58 | } 59 | 60 | } 61 | 62 | } -------------------------------------------------------------------------------- /src/udpkit.lib/timers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | #include "timers.h" 26 | 27 | #ifdef UDPKIT_ANDROID 28 | EXPORT_API U32 udpGetHighPrecisionTime() 29 | { 30 | timespec spec = timespec(); 31 | clock_gettime(CLOCK_MONOTONIC, &spec); 32 | 33 | return (spec.tv_sec * 1000) + (spec.tv_nsec / 1000 / 1000); 34 | } 35 | #elif UDPKIT_IOS 36 | 37 | double mach_clock() 38 | { 39 | static bool init = 0; 40 | static mach_timebase_info_data_t tbInfo; 41 | static double conversionFactor; 42 | 43 | if (!init) 44 | { 45 | init = 1 ; 46 | mach_timebase_info(&tbInfo); 47 | conversionFactor = tbInfo.numer / (1e9 * tbInfo.denom); 48 | } 49 | 50 | return mach_absolute_time() * conversionFactor; 51 | } 52 | 53 | double mach_clock_diff() 54 | { 55 | static double lastTime = 0; 56 | double currentTime = mach_clock(); 57 | double diff = currentTime - lastTime; 58 | lastTime = currentTime; 59 | return diff; 60 | } 61 | 62 | EXPORT_API U32 udpGetHighPrecisionTime() 63 | { 64 | return (U32) (mach_clock_diff() * 1000.0); 65 | } 66 | #endif -------------------------------------------------------------------------------- /src/udpkit/udpAssert.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System; 26 | using System.Diagnostics; 27 | using System.Threading; 28 | 29 | namespace UdpKit { 30 | static class UdpAssert { 31 | [Conditional("DEBUG")] 32 | internal static void Assert (bool condition) { 33 | if (!condition) 34 | throw new UdpException("assert failed"); 35 | } 36 | 37 | [Conditional("DEBUG")] 38 | internal static void Assert (bool condition, string message) { 39 | if (!condition) 40 | throw new UdpException(String.Concat("assert failed: ", message)); 41 | } 42 | 43 | [Conditional("DEBUG")] 44 | internal static void Assert (bool condition, string message, params object[] args) { 45 | if (!condition) 46 | throw new UdpException(String.Concat("assert failed: ", String.Format(message, args))); 47 | } 48 | 49 | [Conditional("DEBUG")] 50 | internal static void AssertThread (Thread thread) { 51 | Assert(ReferenceEquals(Thread.CurrentThread, thread), "expected thread to be '{0}', but was '{1}'", thread.Name, Thread.CurrentThread.Name); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/udpkit/udpSet.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System.Collections.Generic; 26 | 27 | namespace UdpKit { 28 | class UdpSet { 29 | public int Count { 30 | get { return set.Count; } 31 | } 32 | 33 | public bool Remove (T value) { 34 | return set.Remove(value); 35 | } 36 | 37 | #if HAS_HASHSET 38 | readonly HashSet set; 39 | 40 | public UdpSet (IEqualityComparer comparer) { 41 | set = new HashSet(comparer); 42 | } 43 | 44 | public bool Add (T value) { 45 | return set.Add(value); 46 | } 47 | 48 | public bool Contains (T value) { 49 | return set.Contains(value); 50 | } 51 | #else 52 | readonly Dictionary set; 53 | 54 | public UdpSet (IEqualityComparer comparer) { 55 | set = new Dictionary(comparer); 56 | } 57 | 58 | public bool Add (T value) { 59 | if (set.ContainsKey(value)) 60 | return false; 61 | 62 | set.Add(value, null); 63 | return true; 64 | } 65 | 66 | public bool Contains (T value) { 67 | return set.ContainsKey(value); 68 | } 69 | #endif 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/udpkit/udpRingBuffer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | namespace UdpKit { 26 | class UdpRingBuffer where T : struct { 27 | int head; 28 | int tail; 29 | int count; 30 | 31 | readonly T[] array; 32 | 33 | public bool Full { 34 | get { return count == array.Length; } 35 | } 36 | 37 | public bool Empty { 38 | get { return count == 0; } 39 | } 40 | 41 | public float FillRatio { 42 | get { return UdpMath.Clamp((float) count / (float) array.Length, 0f, 1f); } 43 | } 44 | 45 | public UdpRingBuffer (int size) { 46 | array = new T[size]; 47 | } 48 | 49 | public void Enqueue (T item) { 50 | if (count == array.Length) 51 | throw new UdpException("buffer is full"); 52 | 53 | array[head] = item; 54 | head = (head + 1) % array.Length; 55 | count += 1; 56 | } 57 | 58 | public T Dequeue () { 59 | if (count == 0) 60 | throw new UdpException("buffer is empty"); 61 | 62 | T item = array[tail]; 63 | array[tail] = default(T); 64 | tail = (tail + 1) % array.Length; 65 | count -= 1; 66 | return item; 67 | } 68 | 69 | public T Peek () { 70 | if (count == 0) 71 | throw new UdpException("buffer is empty"); 72 | 73 | return array[tail]; 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /proj/ios/udpkit_ios.xcodeproj/xcuserdata/fredrik.xcuserdatad/xcschemes/udpkit_ios.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 52 | 53 | 54 | 55 | 61 | 62 | 64 | 65 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /src/udpkit/udpSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System.Collections.Generic; 26 | 27 | namespace UdpKit { 28 | public delegate UdpSerializer UdpSerializerFactory (); 29 | 30 | public abstract class UdpSerializer { 31 | readonly Queue sendQueue = new Queue(); 32 | 33 | internal bool HasQueuedObjects { 34 | get { return sendQueue.Count > 0; } 35 | } 36 | 37 | internal object NextObject () { 38 | return sendQueue.Dequeue(); 39 | } 40 | 41 | /// 42 | /// The connection which owns this serializer 43 | /// 44 | public UdpConnection Connection { 45 | get; 46 | internal set; 47 | } 48 | 49 | /// 50 | /// Queue an object for immediate sending after the current object has been packed 51 | /// 52 | /// The object to send 53 | public void SendNext (object o) { 54 | sendQueue.Enqueue(o); 55 | } 56 | 57 | /// 58 | /// Reject an object from being sent, sending it back to the event-thread 59 | /// 60 | /// The object to reject 61 | public void Reject (object o) { 62 | Connection.socket.Raise(UdpEvent.PUBLIC_OBJECT_REJECTED, Connection, o); 63 | } 64 | 65 | public abstract bool Pack (ref UdpBitStream stream, ref object o); 66 | public abstract bool Unpack (ref UdpBitStream stream, ref object o); 67 | 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /proj/managed/udpkit.unity.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {AAC3E356-494B-41FF-84D4-87BD05F0AA60} 8 | Library 9 | Properties 10 | UdpKit 11 | udpkit.unity 12 | v2.0 13 | 512 14 | 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | TRACE;DEBUG;UDPKIT_DLL_UNITY 22 | prompt 23 | 4 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE;UDPKIT_DLL_UNITY 30 | prompt 31 | 4 32 | 33 | 34 | 35 | 36 | ..\..\..\..\..\..\..\Program Files (x86)\Unity\Editor\Data\Managed\UnityEngine.dll 37 | 38 | 39 | 40 | 41 | Properties\AssemblyInfo.cs 42 | 43 | 44 | udpBitStreamExtensions.cs 45 | 46 | 47 | 48 | 49 | {82a76ef8-2122-437c-b34d-62d28ebfa0ba} 50 | udpkit 51 | 52 | 53 | 54 | 61 | -------------------------------------------------------------------------------- /proj/managed/udpkit.platform.managed.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {38C8731B-99F5-47C4-BCF7-9BDB55EAC94C} 8 | Library 9 | Properties 10 | UdpKit 11 | udpkit.platform.managed 12 | v2.0 13 | 512 14 | 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | TRACE;DEBUG;UDPKIT_DLL_PLATFORM_MANAGED 22 | prompt 23 | 4 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE;UDPKIT_DLL_PLATFORM_MANAGED 30 | prompt 31 | 4 32 | 33 | 34 | 35 | 36 | 37 | 38 | {82a76ef8-2122-437c-b34d-62d28ebfa0ba} 39 | udpkit 40 | 41 | 42 | 43 | 44 | Properties\AssemblyInfo.cs 45 | 46 | 47 | udpPlatformManaged.cs 48 | 49 | 50 | udpPrecisionTimer.cs 51 | 52 | 53 | 54 | 55 | 62 | -------------------------------------------------------------------------------- /proj/managed/udpkit.platform.ios.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {22C204CA-5052-484F-A661-A6A7A80ACBE2} 8 | Library 9 | Properties 10 | UdpKit 11 | udpkit.platform.ios 12 | v2.0 13 | 512 14 | 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | TRACE;DEBUG;UDPKIT_IOS; UDPKIT_DLL_PLATFORM_IOS 22 | prompt 23 | 4 24 | true 25 | 26 | 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE;UDPKIT_IOS; UDPKIT_DLL_PLATFORM_IOS 31 | prompt 32 | 4 33 | true 34 | 35 | 36 | 37 | 38 | 39 | 40 | {82a76ef8-2122-437c-b34d-62d28ebfa0ba} 41 | udpkit 42 | 43 | 44 | 45 | 46 | Properties\AssemblyInfo.cs 47 | 48 | 49 | udpNativeInvoke.cs 50 | 51 | 52 | udpPlatformNative.cs 53 | 54 | 55 | 56 | 63 | -------------------------------------------------------------------------------- /proj/managed/udpkit.platform.android.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {1589840C-F956-4F9B-B671-5DFA8A1A5B7B} 8 | Library 9 | Properties 10 | UdpKit 11 | udpkit.platform.android 12 | v2.0 13 | 512 14 | 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | TRACE;DEBUG;UDPKIT_ANDROID; UDPKIT_DLL_PLATFORM_ANDROID 22 | prompt 23 | 4 24 | true 25 | 26 | 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE;UDPKIT_ANDROID; UDPKIT_DLL_PLATFORM_ANDROID 31 | prompt 32 | 4 33 | true 34 | 35 | 36 | 37 | 38 | 39 | 40 | Properties\AssemblyInfo.cs 41 | 42 | 43 | udpNativeInvoke.cs 44 | 45 | 46 | udpPlatformNative.cs 47 | 48 | 49 | 50 | 51 | {82a76ef8-2122-437c-b34d-62d28ebfa0ba} 52 | udpkit 53 | 54 | 55 | 56 | 63 | -------------------------------------------------------------------------------- /src/udpkit.lib/socket.h: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | #include "common.h" 26 | 27 | #define UDPKIT_SOCKET_OK 0 28 | #define UDPKIT_SOCKET_ERROR -1 29 | #define UDPKIT_SOCKET_NOTVALID -2 30 | #define UDPKIT_SOCKET_NODATA -3 31 | #define UDPKIT_CHECK_RESULT(result) \ 32 | if (result == SOCKET_ERROR) { \ 33 | socket->lastError = udpLastError(); \ 34 | return UDPKIT_SOCKET_ERROR; \ 35 | } \ 36 | 37 | #define UDPKIT_CHECK_VALIDSOCKET(s) \ 38 | if (s == NULL || s->nativeSocket == INVALID_SOCKET) { \ 39 | return UDPKIT_SOCKET_NOTVALID; \ 40 | } \ 41 | 42 | #if UDPKIT_WIN 43 | #ifndef _WIN32_WINNT_WINXP 44 | #define UDPKIT_WIN_WSAPOLL 45 | #endif 46 | 47 | #include 48 | #include 49 | #include 50 | #pragma comment(lib, "Ws2_32.lib") 51 | #else 52 | #include 53 | #include 54 | #include 55 | #include 56 | #include 57 | #include 58 | #include 59 | #include 60 | #include 61 | 62 | #define INVALID_SOCKET -1 63 | #define SOCKET_ERROR -1 64 | #endif 65 | 66 | struct udpEndPoint { 67 | U32 address; 68 | U16 port; 69 | }; 70 | 71 | struct udpSocket { 72 | S32 nativeSocket; 73 | S32 lastError; 74 | U32 sendBufferSize; 75 | U32 recvBufferSize; 76 | udpEndPoint endPoint; 77 | }; 78 | 79 | EXPORT_API udpSocket* udpCreate(); 80 | EXPORT_API S32 udpBind(udpSocket* socket, udpEndPoint addr); 81 | EXPORT_API S32 udpSendTo(udpSocket* socket, char* buffer, S32 size, udpEndPoint addr); 82 | EXPORT_API S32 udpRecvFrom(udpSocket* socket, char* buffer, S32 size, udpEndPoint* addr); 83 | EXPORT_API S32 udpRecvPoll(udpSocket* socket, S32 timeoutMs); 84 | EXPORT_API S32 udpLastError(udpSocket* socket); 85 | EXPORT_API S32 udpClose(udpSocket* socket); 86 | EXPORT_API S32 udpGetEndPoint(udpSocket* socket, udpEndPoint* endPoint); 87 | -------------------------------------------------------------------------------- /proj/managed/udpkit.dev.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {66EF8FB2-CBCA-4085-9B7C-69E6792AC19F} 8 | Exe 9 | Properties 10 | UdpKit.dev 11 | udpkit.dev 12 | v2.0 13 | 512 14 | 15 | 16 | 17 | x86 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | main.cs 42 | 43 | 44 | Properties\AssemblyInfo.cs 45 | 46 | 47 | 48 | 49 | {82a76ef8-2122-437c-b34d-62d28ebfa0ba} 50 | udpkit 51 | 52 | 53 | {38c8731b-99f5-47c4-bcf7-9bdb55eac94c} 54 | udpkit.platform.managed 55 | 56 | 57 | 58 | 59 | App.config 60 | 61 | 62 | 63 | 70 | -------------------------------------------------------------------------------- /src/udpkit.lib/common.h: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | #if _WIN64 26 | #define UDPKIT_WIN64 1 27 | #define UDPKIT_WIN 1 28 | #define UDPKIT_SUFFIX win64_ 29 | #elif _WIN32 30 | #define UDPKIT_WIN32 1 31 | #define UDPKIT_WIN 1 32 | #define UDPKIT_SUFFIX win32_ 33 | #elif __APPLE__ 34 | #include "TargetConditionals.h" 35 | #if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR 36 | #define UDPKIT_IOS 1 37 | #define UDPKIT_IOS_SIMULATOR 1 38 | #define UDPKIT_SUFFIX ios_ 39 | #elif TARGET_OS_IPHONE 40 | #define UDPKIT_IOS 1 41 | #define UDPKIT_SUFFIX ios_ 42 | #else 43 | #define UDPKIT_OSX 1 44 | #define UDPKIT_SUFFIX osx_ 45 | #endif 46 | #elif __ANDROID__ 47 | #define UDPKIT_ANDROID 1 48 | #define UDPKIT_SUFFIX android_ 49 | #elif __linux 50 | #define UDPKIT_LINUX 1 51 | #define UDPKIT_SUFFIX linux_ 52 | #endif 53 | 54 | #if defined(_DEBUG) || defined(DEBUG) 55 | #define UDPKIT_DEBUG 56 | #endif 57 | 58 | #ifndef UNICODE 59 | #define UNICODE 60 | #endif 61 | 62 | #if UDPKIT_WIN 63 | #define WIN32_LEAN_AND_MEAN 64 | #define EXPORT_API extern "C" __declspec(dllexport) 65 | #else 66 | #define EXPORT_API extern "C" 67 | #endif 68 | 69 | typedef signed char S8; 70 | typedef unsigned char U8; 71 | typedef signed short S16; 72 | typedef unsigned short U16; 73 | typedef signed int S32; 74 | typedef unsigned int U32; 75 | typedef signed long long S64; 76 | typedef unsigned long long U64; 77 | 78 | #ifndef UDPKIT_ANDROID 79 | static_assert(sizeof(U8) == 1 && sizeof(S8) == 1, "U8 and S8 must be 1 byte"); 80 | static_assert(sizeof(U16) == 2 && sizeof(S16) == 2, "U16 and S16 must be 2 bytes"); 81 | static_assert(sizeof(U32) == 4 && sizeof(S32) == 4, "U32 and S32 must be 4 bytes"); 82 | static_assert(sizeof(U64) == 8 && sizeof(S64) == 8, "U64 and S64 must be 8 bytes"); 83 | #endif 84 | 85 | #include 86 | #include 87 | 88 | EXPORT_API const char* udpPlatform(); 89 | EXPORT_API const char* udpPlatformErrorString(int errorCode); -------------------------------------------------------------------------------- /proj/managed/udpkit.platform.win32.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {34C61ED8-5D87-4070-A979-E89FB7839F23} 8 | Library 9 | Properties 10 | UdpKit 11 | udpkit.platform.win32 12 | v2.0 13 | 512 14 | 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | TRACE;DEBUG;UDPKIT_WIN32; UDPKIT_DLL_PLATFORM_WIN32 22 | prompt 23 | 4 24 | true 25 | 26 | 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE;UDPKIT_WIN32; UUDPKIT_DLL_PLATFORM_WIN32 31 | prompt 32 | 4 33 | true 34 | 35 | 36 | 37 | 38 | 39 | 40 | {82a76ef8-2122-437c-b34d-62d28ebfa0ba} 41 | udpkit 42 | 43 | 44 | 45 | 46 | Properties\AssemblyInfo.cs 47 | 48 | 49 | udpPrecisionTimer.cs 50 | 51 | 52 | udpNativeInvoke.cs 53 | 54 | 55 | udpPlatformNative.cs 56 | 57 | 58 | 59 | 66 | -------------------------------------------------------------------------------- /proj/managed/udpkit.examples.chat.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {FA5E4A73-6C64-4E88-8406-D569F1DFD8C9} 8 | Exe 9 | Properties 10 | UdpKit.Examples.Chat 11 | udpkit.examples.chat 12 | v2.0 13 | 512 14 | 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | App.config 41 | 42 | 43 | 44 | 45 | Program.cs 46 | 47 | 48 | Properties\AssemblyInfo.cs 49 | 50 | 51 | 52 | 53 | {82a76ef8-2122-437c-b34d-62d28ebfa0ba} 54 | udpkit 55 | 56 | 57 | {38c8731b-99f5-47c4-bcf7-9bdb55eac94c} 58 | udpkit.platform.managed 59 | 60 | 61 | 62 | 69 | -------------------------------------------------------------------------------- /proj/managed/udpkit.examples.simple.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {F9E8E09B-5ED3-44A8-877E-8A3B38CFA8C0} 8 | Exe 9 | Properties 10 | UdpKit 11 | udpkit.examples.simple 12 | v2.0 13 | 512 14 | 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | Program.cs 41 | 42 | 43 | Properties\AssemblyInfo.cs 44 | 45 | 46 | 47 | 48 | App.config 49 | 50 | 51 | 52 | 53 | {82a76ef8-2122-437c-b34d-62d28ebfa0ba} 54 | udpkit 55 | 56 | 57 | {38c8731b-99f5-47c4-bcf7-9bdb55eac94c} 58 | udpkit.platform.managed 59 | 60 | 61 | 62 | 69 | -------------------------------------------------------------------------------- /src/udpkit.stresstest/udpRecvChannel.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System; 26 | using System.Collections.Generic; 27 | using System.Text; 28 | 29 | namespace UdpKit.stresstest { 30 | 31 | class udpRecvChannel { 32 | int tail; 33 | int mask; 34 | int shift; 35 | uint next; 36 | 37 | readonly node[] nodes; 38 | 39 | struct node { 40 | public bool received; 41 | public uint sequence; 42 | public T value; 43 | } 44 | 45 | public udpRecvChannel (int windowBits, int sequenceBits) { 46 | nodes = new node[1 << windowBits]; 47 | shift = 32 - sequenceBits; 48 | mask = nodes.Length - 1; 49 | } 50 | 51 | public bool tryRemove (ref uint sequence, ref T value) { 52 | node n = nodes[tail]; 53 | 54 | if (n.received) { 55 | value = n.value; 56 | sequence = n.sequence; 57 | nodes[tail] = default(node); 58 | 59 | tail += 1; 60 | tail &= mask; 61 | 62 | next = sequence + 1; 63 | } 64 | 65 | return n.received; 66 | } 67 | 68 | public bool tryAdd (uint sequence, T value) { 69 | int distance = sequenceDistance(sequence, next); 70 | int index = (tail + distance) & mask; 71 | 72 | if (distance < 0 || distance >= nodes.Length) { 73 | return false; 74 | } 75 | 76 | node n = nodes[index]; 77 | if (n.received == false) { 78 | n.received = true; 79 | n.sequence = sequence; 80 | n.value = value; 81 | nodes[index] = n; 82 | } 83 | 84 | return true; 85 | } 86 | 87 | int sequenceDistance (uint from, uint to) { 88 | from <<= shift; 89 | to <<= shift; 90 | return ((int) (from - to)) >> shift; 91 | } 92 | } 93 | 94 | } -------------------------------------------------------------------------------- /src/udpkit/udpHeader.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | namespace UdpKit { 26 | struct UdpHeader { 27 | public const int SEQ_BITS = 15; 28 | public const int SEQ_PADD = 16 - SEQ_BITS; 29 | public const int SEQ_MASK = (1 << SEQ_BITS) - 1; 30 | 31 | public ushort ObjSequence; 32 | public ushort AckSequence; 33 | public ulong AckHistory; 34 | public ushort AckTime; 35 | public bool IsObject; 36 | public ushort BitSize; 37 | public uint Now; 38 | 39 | public void Pack (UdpBitStream buffer, UdpSocket socket) { 40 | buffer.WriteUShort(PadSequence(ObjSequence), 16); 41 | buffer.WriteUShort(PadSequence(AckSequence), 16); 42 | buffer.WriteULong(AckHistory, socket.Config.AckRedundancy); 43 | 44 | if (socket.Config.CalculateNetworkPing) { 45 | buffer.WriteUShort(AckTime, 16); 46 | } 47 | 48 | if (socket.Config.WritePacketBitSize) { 49 | buffer.WriteUShort(BitSize, 16); 50 | } 51 | } 52 | 53 | public void Unpack (UdpBitStream buffer, UdpSocket socket) { 54 | ObjSequence = TrimSequence(buffer.ReadUShort(16)); 55 | AckSequence = TrimSequence(buffer.ReadUShort(16)); 56 | AckHistory = buffer.ReadULong(socket.Config.AckRedundancy); 57 | 58 | if (socket.Config.CalculateNetworkPing) { 59 | AckTime = buffer.ReadUShort(16); 60 | } 61 | 62 | if (socket.Config.WritePacketBitSize) { 63 | BitSize = buffer.ReadUShort(16); 64 | } 65 | } 66 | 67 | public static int GetSize (UdpSocket socket) { 68 | return 16 + 16 + socket.Config.AckRedundancy + (socket.Config.CalculateNetworkPing ? 16 : 0) + (socket.Config.WritePacketBitSize ? 16 : 0); 69 | } 70 | 71 | ushort PadSequence (ushort sequence) { 72 | sequence <<= SEQ_PADD; 73 | 74 | if (IsObject) 75 | sequence |= ((1 << SEQ_PADD) - 1); 76 | 77 | return sequence; 78 | } 79 | 80 | ushort TrimSequence (ushort sequence) { 81 | sequence >>= SEQ_PADD; 82 | return sequence; 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /proj/managed/udpkit.stresstest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {77F1C845-07A9-4B09-9209-723A66964334} 8 | Exe 9 | Properties 10 | UdpKit.stresstest 11 | udpkit.stresstest 12 | v2.0 13 | 512 14 | 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | Program.cs 41 | 42 | 43 | Properties\AssemblyInfo.cs 44 | 45 | 46 | udpRecvChannel.cs 47 | 48 | 49 | udpSendChannel.cs 50 | 51 | 52 | udpSequenceGenerator.cs 53 | 54 | 55 | 56 | 57 | {82a76ef8-2122-437c-b34d-62d28ebfa0ba} 58 | udpkit 59 | 60 | 61 | {38c8731b-99f5-47c4-bcf7-9bdb55eac94c} 62 | udpkit.platform.managed 63 | 64 | 65 | 66 | 67 | App.config 68 | 69 | 70 | 71 | 78 | -------------------------------------------------------------------------------- /src/udpkit/udpEndpoint.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System.Collections.Generic; 26 | using System.Runtime.InteropServices; 27 | 28 | namespace UdpKit { 29 | [StructLayout(LayoutKind.Sequential, Pack = 1)] 30 | public struct UdpEndPoint { 31 | public static readonly UdpEndPoint Any = new UdpEndPoint(UdpIPv4Address.Any, 0); 32 | public readonly UdpIPv4Address Address; 33 | public readonly ushort Port; 34 | 35 | public UdpEndPoint (string endpoint) { 36 | string[] parts = endpoint.Split(':'); 37 | this.Address = new UdpIPv4Address(parts[0]); 38 | this.Port = ushort.Parse(parts[1]); 39 | } 40 | 41 | public UdpEndPoint (UdpIPv4Address address, ushort port) { 42 | this.Address = address; 43 | this.Port = port; 44 | } 45 | 46 | public override int GetHashCode () { 47 | return (int) (Address.Packet ^ Port); 48 | } 49 | 50 | public override bool Equals (object obj) { 51 | if (obj is UdpEndPoint) { 52 | return Compare(this, (UdpEndPoint) obj) == 0; 53 | } 54 | 55 | return false; 56 | } 57 | 58 | public override string ToString () { 59 | return string.Format("{0}.{1}.{2}.{3}:{4}", Address.Byte3, Address.Byte2, Address.Byte1, Address.Byte0, Port); 60 | } 61 | 62 | public static bool operator == (UdpEndPoint x, UdpEndPoint y) { 63 | return Compare(x, y) == 0; 64 | } 65 | 66 | public static bool operator != (UdpEndPoint x, UdpEndPoint y) { 67 | return Compare(x, y) != 0; 68 | } 69 | 70 | internal static int Compare (UdpEndPoint x, UdpEndPoint y) { 71 | if (x.Address.Packet > y.Address.Packet) return 1; 72 | if (x.Address.Packet < y.Address.Packet) return -1; 73 | 74 | if (x.Port > y.Port) return 1; 75 | if (x.Port < y.Port) return -1; 76 | 77 | return 0; 78 | } 79 | } 80 | 81 | public class UdpEndPointComparer : IEqualityComparer { 82 | bool IEqualityComparer.Equals (UdpEndPoint x, UdpEndPoint y) { 83 | return UdpEndPoint.Compare(x, y) == 0; 84 | } 85 | 86 | int IEqualityComparer.GetHashCode (UdpEndPoint obj) { 87 | return obj.GetHashCode(); 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/udpkit/udpAddress.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System.Net; 26 | using System.Runtime.InteropServices; 27 | 28 | namespace UdpKit { 29 | [StructLayout(LayoutKind.Explicit, Pack = 1)] 30 | public struct UdpIPv4Address { 31 | public static readonly UdpIPv4Address Any = new UdpIPv4Address(); 32 | public static readonly UdpIPv4Address Localhost = new UdpIPv4Address(127, 0, 0, 1); 33 | 34 | [FieldOffset(0)] 35 | public readonly uint Packet; 36 | [FieldOffset(0)] 37 | public readonly byte Byte0; 38 | [FieldOffset(1)] 39 | public readonly byte Byte1; 40 | [FieldOffset(2)] 41 | public readonly byte Byte2; 42 | [FieldOffset(3)] 43 | public readonly byte Byte3; 44 | 45 | public UdpIPv4Address (long addr) { 46 | Byte0 = Byte1 = Byte2 = Byte3 = 0; 47 | Packet = (uint) IPAddress.NetworkToHostOrder((int) addr); 48 | } 49 | 50 | public UdpIPv4Address (string ip) { 51 | string[] parts = ip.Split('.'); 52 | Packet = 0; 53 | Byte0 = byte.Parse(parts[3]); 54 | Byte1 = byte.Parse(parts[2]); 55 | Byte2 = byte.Parse(parts[1]); 56 | Byte3 = byte.Parse(parts[0]); 57 | } 58 | 59 | public UdpIPv4Address (byte a, byte b, byte c, byte d) { 60 | Packet = 0; 61 | Byte0 = d; 62 | Byte1 = c; 63 | Byte2 = b; 64 | Byte3 = a; 65 | } 66 | 67 | public override int GetHashCode () { 68 | return (int) Packet; 69 | } 70 | 71 | public override bool Equals (object obj) { 72 | if (obj is UdpIPv4Address) { 73 | return Compare(this, (UdpIPv4Address) obj) == 0; 74 | } 75 | 76 | return false; 77 | } 78 | 79 | public override string ToString () { 80 | return string.Format("{0}.{1}.{2}.{3}", Byte3, Byte2, Byte1, Byte0); 81 | } 82 | 83 | public static bool operator == (UdpIPv4Address x, UdpIPv4Address y) { 84 | return Compare(x, y) == 0; 85 | } 86 | 87 | public static bool operator != (UdpIPv4Address x, UdpIPv4Address y) { 88 | return Compare(x, y) != 0; 89 | } 90 | 91 | static int Compare (UdpIPv4Address x, UdpIPv4Address y) { 92 | if (x.Packet > y.Packet) return 1; 93 | if (x.Packet < y.Packet) return -1; 94 | return 0; 95 | } 96 | 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/udpkit.platform.native/udpNativeInvoke.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System; 26 | using System.Runtime.InteropServices; 27 | using System.Security; 28 | 29 | namespace UdpKit { 30 | internal static unsafe class UdpNativeInvoke { 31 | 32 | public const string DLL_NAME = 33 | 34 | #if UDPKIT_IOS 35 | "__Internal"; 36 | #elif UDPKIT_ANDROID 37 | "updkit_android"; 38 | #elif UDPKIT_WIN32 39 | "libudpkit_win32"; 40 | #endif 41 | 42 | public const int UDPKIT_SOCKET_OK = 0; 43 | public const int UDPKIT_SOCKET_ERROR = -1; 44 | public const int UDPKIT_SOCKET_NOTVALID = -2; 45 | public const int UDPKIT_SOCKET_NODATA = -3; 46 | 47 | [DllImport(DLL_NAME, ExactSpelling = true)] 48 | [SuppressUnmanagedCodeSecurity] 49 | public static extern IntPtr udpCreate (); 50 | 51 | [DllImport(DLL_NAME, ExactSpelling = true)] 52 | [SuppressUnmanagedCodeSecurity] 53 | public static extern Int32 udpBind (IntPtr socket, UdpEndPoint addr); 54 | 55 | [DllImport(DLL_NAME, ExactSpelling = true)] 56 | [SuppressUnmanagedCodeSecurity] 57 | public static extern Int32 udpSendTo (IntPtr socket, IntPtr buffer, int size, UdpEndPoint addr); 58 | 59 | [DllImport(DLL_NAME, ExactSpelling = true)] 60 | [SuppressUnmanagedCodeSecurity] 61 | public static extern Int32 udpRecvFrom (IntPtr socket, IntPtr buffer, int size, UdpEndPoint* addr); 62 | 63 | [DllImport(DLL_NAME, ExactSpelling = true)] 64 | [SuppressUnmanagedCodeSecurity] 65 | public static extern Int32 udpRecvPoll (IntPtr socket, int timeout); 66 | 67 | [DllImport(DLL_NAME, ExactSpelling = true)] 68 | [SuppressUnmanagedCodeSecurity] 69 | public static extern Int32 udpLastError (IntPtr socket); 70 | 71 | [DllImport(DLL_NAME, ExactSpelling = true)] 72 | [SuppressUnmanagedCodeSecurity] 73 | public static extern Int32 udpGetEndPoint (IntPtr socket, UdpEndPoint* addr); 74 | 75 | [DllImport(DLL_NAME, ExactSpelling = true)] 76 | [SuppressUnmanagedCodeSecurity] 77 | public static extern Int32 udpClose (IntPtr socket); 78 | 79 | [DllImport(DLL_NAME, ExactSpelling = true)] 80 | [SuppressUnmanagedCodeSecurity] 81 | static extern IntPtr udpPlatform (); 82 | public static string udpGetPlatform () { return Marshal.PtrToStringAnsi(udpPlatform()); } 83 | 84 | [DllImport(DLL_NAME, ExactSpelling = true)] 85 | [SuppressUnmanagedCodeSecurity] 86 | static extern IntPtr udpPlatformErrorString (int code); 87 | public static string udpGetPlatformErrorString (int code) { return Marshal.PtrToStringAnsi(udpPlatformErrorString(code)); } 88 | 89 | [DllImport(DLL_NAME, ExactSpelling = true)] 90 | [SuppressUnmanagedCodeSecurity] 91 | public static extern UInt32 udpGetHighPrecisionTime(); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/udpkit.dev/main.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System; 26 | using System.Threading; 27 | using UdpKit; 28 | 29 | namespace udpkitdev { 30 | class main { 31 | static Thread serverThread; 32 | static Thread clientThread; 33 | 34 | class Serializer : UdpSerializer { 35 | public override bool Pack (ref UdpBitStream buffer, ref object o) { 36 | buffer.WriteUInt((uint) o, 32); 37 | return true; 38 | } 39 | 40 | public override bool Unpack (ref UdpBitStream buffer, ref object o) { 41 | o = buffer.ReadUInt(32); 42 | return true; 43 | } 44 | } 45 | 46 | static void EventLoop (UdpSocket socket) { 47 | UdpConnection c = null; 48 | 49 | while (true) { 50 | UdpEvent ev = default(UdpEvent); 51 | 52 | if (socket.Poll(ref ev)) { 53 | UdpLog.User(ev.EventType.ToString()); 54 | 55 | switch (ev.EventType) { 56 | case UdpEventType.ConnectRequest: 57 | socket.Accept(ev.EndPoint); 58 | break; 59 | 60 | case UdpEventType.Connected: 61 | c = ev.Connection; 62 | break; 63 | 64 | } 65 | } 66 | 67 | if (c != null) { 68 | c.Send(10u); 69 | } 70 | 71 | Thread.Sleep(100); 72 | } 73 | } 74 | 75 | static void Server () { 76 | UdpSocket socket = UdpSocket.Create(); 77 | socket.Start(new UdpEndPoint(UdpIPv4Address.Localhost, 14000)); 78 | EventLoop(socket); 79 | } 80 | 81 | static void Client () { 82 | UdpSocket socket = UdpSocket.Create(); 83 | socket.Start(new UdpEndPoint(UdpIPv4Address.Localhost, 0)); 84 | socket.Connect(new UdpEndPoint(UdpIPv4Address.Localhost, 14000)); 85 | EventLoop(socket); 86 | } 87 | 88 | static void Main (string[] args) { 89 | Console.BufferHeight = 5000; 90 | 91 | UdpLog.SetWriter(Console.WriteLine); 92 | 93 | serverThread = new Thread(Server); 94 | serverThread.IsBackground = true; 95 | serverThread.Name = "server"; 96 | serverThread.Start(); 97 | 98 | clientThread = new Thread(Client); 99 | clientThread.IsBackground = true; 100 | clientThread.Name = "client"; 101 | clientThread.Start(); 102 | 103 | Console.ReadLine(); 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/udpkit.examples.simple/Program.cs: -------------------------------------------------------------------------------- 1 | //#define DISABLE_AUTO_ACCEPT 2 | //#define ENABLE_MANUAL_ACCEPT 3 | 4 | using System; 5 | using System.Threading; 6 | using UdpKit; 7 | 8 | namespace UdpKit.Examples.Simple { 9 | class DummySerializer : UdpSerializer { 10 | public override bool Pack (ref UdpBitStream stream, ref object o) { 11 | throw new NotImplementedException(); 12 | } 13 | 14 | public override bool Unpack (ref UdpBitStream stream, ref object o) { 15 | throw new NotImplementedException(); 16 | } 17 | } 18 | 19 | class Program { 20 | static void Client () { 21 | UdpSocket client = UdpSocket.Create(); 22 | client.Start(UdpEndPoint.Any); 23 | client.Connect(new UdpEndPoint(UdpIPv4Address.Localhost, 14000)); 24 | 25 | while (true) { 26 | UdpEvent ev = default(UdpEvent); 27 | 28 | while (client.Poll(ref ev)) { 29 | UdpLog.User("Event raised {0}", ev.EventType); 30 | 31 | switch (ev.EventType) { 32 | case UdpEventType.Connected: 33 | UdpLog.User("Connected to server at {0}", ev.Connection.RemoteEndPoint); 34 | break; 35 | 36 | #if DISABLE_AUTO_ACCEPT 37 | case UdpEventType.ConnectFailed: 38 | UdpLog.User("Connection to {0} failed", ev.EndPoint); 39 | break; 40 | #endif 41 | } 42 | } 43 | 44 | // Simulate ~60fps game loop 45 | Thread.Sleep(16); 46 | } 47 | } 48 | 49 | static void Server () { 50 | #if DISABLE_AUTO_ACCEPT 51 | UdpConfig config = new UdpConfig(); 52 | config.AutoAcceptIncommingConnections = false; 53 | #else 54 | UdpConfig config = new UdpConfig(); 55 | #endif 56 | UdpSocket server = UdpSocket.Create(config); 57 | server.Start(new UdpEndPoint(UdpIPv4Address.Localhost, 14000)); 58 | 59 | while (true) { 60 | UdpEvent ev = default(UdpEvent); 61 | 62 | while (server.Poll(ref ev)) { 63 | UdpLog.User("Event raised {0}", ev.EventType); 64 | 65 | switch (ev.EventType) { 66 | case UdpEventType.Connected: 67 | UdpLog.User("Client connected from {0}, total clients connected: {1}", ev.Connection.RemoteEndPoint, server.ConnectionCount); 68 | break; 69 | 70 | #if ENABLE_MANUAL_ACCEPT 71 | case UdpEventType.ConnectRequest: 72 | UdpLog.User("Connection requested from {0}", ev.EndPoint); 73 | server.Accept(ev.EndPoint); 74 | break; 75 | #endif 76 | } 77 | } 78 | 79 | // Simulate ~60fps game loop 80 | Thread.Sleep(16); 81 | } 82 | } 83 | 84 | static void Main (string[] args) { 85 | Console.WriteLine("Example: Simple"); 86 | Console.WriteLine("Press [S] to start server"); 87 | Console.WriteLine("Press [C] to start client"); 88 | Console.Write("... "); 89 | 90 | UdpLog.SetWriter(Console.WriteLine); 91 | 92 | switch (Console.ReadKey(true).Key) { 93 | case ConsoleKey.S: 94 | Console.WriteLine("Server"); 95 | Server(); 96 | break; 97 | 98 | case ConsoleKey.C: 99 | Console.WriteLine("Client"); 100 | Client(); 101 | break; 102 | 103 | default: 104 | Main(args); 105 | break; 106 | } 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/udpkit/udpMath.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | namespace UdpKit { 26 | internal static class UdpMath { 27 | internal static bool IsSet (uint mask, uint flag) { 28 | return (mask & flag) == flag; 29 | } 30 | 31 | internal static uint NextPow2 (uint v) { 32 | v--; 33 | v |= v >> 1; 34 | v |= v >> 2; 35 | v |= v >> 4; 36 | v |= v >> 8; 37 | v |= v >> 16; 38 | v++; 39 | return v; 40 | } 41 | 42 | internal static int HighBit (uint v) { 43 | if (v == 0) 44 | return 0; 45 | 46 | int r = 0; 47 | 48 | do { 49 | r += 1; 50 | } while ((v >>= 1) > 0); 51 | 52 | return r; 53 | } 54 | 55 | internal static int BytesRequired (int bits) { 56 | return (bits + 7) >> 3; 57 | } 58 | 59 | internal static int SeqDistance (ushort from, ushort to, int shift) { 60 | from <<= shift; 61 | to <<= shift; 62 | return ((short) (from - to)) >> shift; 63 | } 64 | 65 | internal static ushort SeqNext (ushort seq, ushort mask) { 66 | seq += 1; 67 | seq &= mask; 68 | return seq; 69 | } 70 | 71 | internal static ushort SeqPrev (ushort seq, ushort mask) { 72 | seq -= 1; 73 | seq &= mask; 74 | return seq; 75 | } 76 | 77 | internal static ushort Clamp (ushort value, ushort min, ushort max) { 78 | if (value < min) 79 | return min; 80 | 81 | if (value > max) 82 | return max; 83 | 84 | return value; 85 | } 86 | 87 | internal static float Clamp (float value, float min, float max) { 88 | if (value < min) 89 | return min; 90 | 91 | if (value > max) 92 | return max; 93 | 94 | return value; 95 | } 96 | 97 | internal static int Clamp (int value, int min, int max) { 98 | if (value < min) 99 | return min; 100 | 101 | if (value > max) 102 | return max; 103 | 104 | return value; 105 | } 106 | 107 | internal static uint Clamp (uint value, uint min, uint max) { 108 | if (value < min) 109 | return min; 110 | 111 | if (value > max) 112 | return max; 113 | 114 | return value; 115 | } 116 | 117 | internal static byte Clamp (byte value, byte min, byte max) { 118 | if (value < min) 119 | return min; 120 | 121 | if (value > max) 122 | return max; 123 | 124 | return value; 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/udpkit/udpLog.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System; 26 | using System.Diagnostics; 27 | using System.Threading; 28 | 29 | namespace UdpKit { 30 | public static class UdpLog { 31 | public delegate void Writer (string msg); 32 | 33 | public const uint INFO = 1; 34 | public const uint USER = 2; 35 | public const uint DEBUG = 4; 36 | public const uint WARN = 8; 37 | 38 | static uint enabled = INFO | USER | DEBUG | WARN; 39 | static Writer writer = null; 40 | static readonly object sync = new object(); 41 | 42 | static void Write (string message) { 43 | lock (UdpLog.sync) { 44 | Writer callback = UdpLog.writer; 45 | 46 | if (callback != null) 47 | callback(message); 48 | } 49 | } 50 | 51 | static string Time () { 52 | return DateTime.Now.ToString("H:mm:ss:fff"); 53 | } 54 | 55 | static string ThreadName () { 56 | return " | thread #" + Thread.CurrentThread.ManagedThreadId.ToString().PadLeft(3, '0'); 57 | } 58 | 59 | static internal void Info (string format, params object[] args) { 60 | if (UdpMath.IsSet(UdpLog.enabled, UdpLog.INFO)) 61 | Write(String.Concat(Time(), ThreadName(), " | info | ", String.Format(format, args))); 62 | } 63 | 64 | static public void User (string format, params object[] args) { 65 | if (UdpMath.IsSet(UdpLog.enabled, UdpLog.USER)) 66 | Write(String.Concat(Time(), ThreadName(), " | user | ", String.Format(format, args))); 67 | } 68 | 69 | [Conditional("DEBUG")] 70 | static internal void Debug (string format, params object[] args) { 71 | #if DEBUG 72 | if (UdpMath.IsSet(UdpLog.enabled, UdpLog.DEBUG)) 73 | Write(String.Concat(Time(), ThreadName(), " | debug | ", String.Format(format, args), "\r\n", Environment.StackTrace)); 74 | #endif 75 | } 76 | 77 | static internal void Warn (string format, params object[] args) { 78 | 79 | if (UdpMath.IsSet(UdpLog.enabled, UdpLog.WARN)) { 80 | #if DEBUG 81 | Write(String.Concat(Time(), ThreadName(), " | warn | ", String.Format(format, args), "\r\n", Environment.StackTrace)); 82 | #else 83 | write(String.Concat(timePadded(), threadName(), " | warn | ", String.Format(format, args))); 84 | #endif 85 | } 86 | } 87 | 88 | static internal void Error (string format, params object[] args) { 89 | #if DEBUG 90 | Write(String.Concat(Time(), ThreadName(), " | error | ", String.Format(format, args), "\r\n", Environment.StackTrace)); 91 | #else 92 | write(String.Concat(timePadded(), threadName(), " | error | ", String.Format(format, args))); 93 | #endif 94 | } 95 | 96 | static public void SetWriter (UdpLog.Writer callback) { 97 | UdpLog.writer = callback; 98 | } 99 | 100 | static public void Disable (uint flag) { 101 | enabled &= ~flag; 102 | } 103 | 104 | static public void Enable (uint flag) { 105 | enabled |= flag; 106 | } 107 | } 108 | } -------------------------------------------------------------------------------- /src/udpkit.platform.native/udpPlatformNative.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System; 26 | 27 | namespace UdpKit { 28 | public sealed unsafe class 29 | #if UDPKIT_IOS 30 | UdpPlatformIOS 31 | #elif UDPKIT_ANDROID 32 | UdpPlatformAndroid 33 | #elif UDPKIT_WIN32 34 | UdpPlatformWin32 35 | #endif 36 | : UdpPlatform { 37 | IntPtr ptr; 38 | 39 | public override UdpEndPoint EndPoint { 40 | get { 41 | UdpEndPoint ep = default(UdpEndPoint); 42 | 43 | if (UdpNativeInvoke.udpGetEndPoint(ptr, &ep) == UdpNativeInvoke.UDPKIT_SOCKET_OK) { 44 | return ep; 45 | } 46 | 47 | return UdpEndPoint.Any; 48 | } 49 | } 50 | 51 | public override UdpSocketInterfaceError Error { 52 | get { return UdpSocketInterfaceError.Unknown; } 53 | } 54 | 55 | public override long PlatformError { 56 | get { return UdpNativeInvoke.udpLastError(ptr); } 57 | } 58 | 59 | public override string PlatformErrorString { 60 | get { return UdpNativeInvoke.udpGetPlatformErrorString((int)PlatformError); } 61 | } 62 | 63 | #if UDPKIT_IOS || UDPKIT_ANDROID 64 | public override uint PlatformPrecisionTime { 65 | get { return UdpNativeInvoke.udpGetHighPrecisionTime(); } 66 | } 67 | #elif UDPKIT_WIN32 68 | public override uint PlatformPrecisionTime { 69 | get { return UdpPrecisionTimer.GetCurrentTime(); } 70 | } 71 | #endif 72 | 73 | public 74 | #if UDPKIT_IOS 75 | UdpPlatformIOS 76 | #elif UDPKIT_ANDROID 77 | UdpPlatformAndroid 78 | #elif UDPKIT_WIN32 79 | UdpPlatformWin32 80 | #endif 81 | () { 82 | ptr = UdpNativeInvoke.udpCreate(); 83 | } 84 | 85 | 86 | public override bool Close () { 87 | return UdpNativeInvoke.udpClose(ptr) == UdpNativeInvoke.UDPKIT_SOCKET_OK; 88 | } 89 | 90 | public override bool Bind (UdpEndPoint endpoint) { 91 | return UdpNativeInvoke.udpBind(ptr, endpoint) == UdpNativeInvoke.UDPKIT_SOCKET_OK; 92 | } 93 | 94 | public override bool RecvPoll (int timeoutInMs) { 95 | return UdpNativeInvoke.udpRecvPoll(ptr, timeoutInMs) == UdpNativeInvoke.UDPKIT_SOCKET_OK; 96 | } 97 | 98 | public override bool RecvFrom (byte[] buffer, int bufferSize, ref int bytesReceived, ref UdpEndPoint remoteEndpoint) { 99 | UdpEndPoint nativeEndpoint = default(UdpEndPoint); 100 | 101 | fixed (byte* p = buffer) { 102 | bytesReceived = UdpNativeInvoke.udpRecvFrom(ptr, new IntPtr(p), bufferSize, &nativeEndpoint); 103 | } 104 | 105 | if (bytesReceived > 0) { 106 | remoteEndpoint = nativeEndpoint; 107 | return true; 108 | } 109 | 110 | return false; 111 | } 112 | 113 | public override bool SendTo (byte[] buffer, int bytesToSend, UdpEndPoint endpoint, ref int bytesSent) { 114 | fixed (byte* p = buffer) { 115 | return bytesToSend == (bytesSent = UdpNativeInvoke.udpSendTo(ptr, new IntPtr(p), bytesToSend, endpoint)); 116 | } 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /proj/win32/libudpkit_win32.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | 14 | {085D3B6D-76D2-4DCD-879C-257B170FBEC5} 15 | Win32Proj 16 | libudpkit_win32 17 | 18 | 19 | 20 | DynamicLibrary 21 | true 22 | v120 23 | Unicode 24 | 25 | 26 | DynamicLibrary 27 | false 28 | v120 29 | true 30 | Unicode 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | true 44 | 45 | 46 | false 47 | 48 | 49 | 50 | 51 | 52 | Level3 53 | Disabled 54 | WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBUDPKIT_WIN32_EXPORTS;%(PreprocessorDefinitions) 55 | 56 | 57 | Windows 58 | true 59 | 60 | 61 | 62 | 63 | Level3 64 | 65 | 66 | MaxSpeed 67 | true 68 | true 69 | WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBUDPKIT_WIN32_EXPORTS;%(PreprocessorDefinitions) 70 | 71 | 72 | Windows 73 | true 74 | true 75 | true 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /src/udpkit/udpByteConverter.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System; 26 | using System.Runtime.InteropServices; 27 | 28 | namespace UdpKit { 29 | [StructLayout(LayoutKind.Explicit)] 30 | public struct UdpByteConverter { 31 | [FieldOffset(0)] 32 | public Int16 Signed16; 33 | [FieldOffset(0)] 34 | public UInt16 Unsigned16; 35 | [FieldOffset(0)] 36 | public Char Char; 37 | [FieldOffset(0)] 38 | public Int32 Signed32; 39 | [FieldOffset(0)] 40 | public UInt32 Unsigned32; 41 | [FieldOffset(0)] 42 | public Int64 Signed64; 43 | [FieldOffset(0)] 44 | public UInt64 Unsigned64; 45 | [FieldOffset(0)] 46 | public Single Float32; 47 | [FieldOffset(0)] 48 | public Double Float64; 49 | 50 | [FieldOffset(0)] 51 | public Byte Byte0; 52 | [FieldOffset(1)] 53 | public Byte Byte1; 54 | [FieldOffset(2)] 55 | public Byte Byte2; 56 | [FieldOffset(3)] 57 | public Byte Byte3; 58 | [FieldOffset(4)] 59 | public Byte Byte4; 60 | [FieldOffset(5)] 61 | public Byte Byte5; 62 | [FieldOffset(6)] 63 | public Byte Byte6; 64 | [FieldOffset(7)] 65 | public Byte Byte7; 66 | 67 | public static implicit operator UdpByteConverter (Int16 val) { 68 | UdpByteConverter bytes = default(UdpByteConverter); 69 | bytes.Signed16 = val; 70 | return bytes; 71 | } 72 | 73 | public static implicit operator UdpByteConverter (UInt16 val) { 74 | UdpByteConverter bytes = default(UdpByteConverter); 75 | bytes.Unsigned16 = val; 76 | return bytes; 77 | } 78 | 79 | public static implicit operator UdpByteConverter (Char val) { 80 | UdpByteConverter bytes = default(UdpByteConverter); 81 | bytes.Char = val; 82 | return bytes; 83 | } 84 | 85 | public static implicit operator UdpByteConverter (UInt32 val) { 86 | UdpByteConverter bytes = default(UdpByteConverter); 87 | bytes.Unsigned32 = val; 88 | return bytes; 89 | } 90 | 91 | public static implicit operator UdpByteConverter (Int32 val) { 92 | UdpByteConverter bytes = default(UdpByteConverter); 93 | bytes.Signed32 = val; 94 | return bytes; 95 | } 96 | 97 | public static implicit operator UdpByteConverter (UInt64 val) { 98 | UdpByteConverter bytes = default(UdpByteConverter); 99 | bytes.Unsigned64 = val; 100 | return bytes; 101 | } 102 | 103 | public static implicit operator UdpByteConverter (Int64 val) { 104 | UdpByteConverter bytes = default(UdpByteConverter); 105 | bytes.Signed64 = val; 106 | return bytes; 107 | } 108 | 109 | public static implicit operator UdpByteConverter (Single val) { 110 | UdpByteConverter bytes = default(UdpByteConverter); 111 | bytes.Float32 = val; 112 | return bytes; 113 | } 114 | 115 | public static implicit operator UdpByteConverter (Double val) { 116 | UdpByteConverter bytes = default(UdpByteConverter); 117 | bytes.Float64 = val; 118 | return bytes; 119 | } 120 | } 121 | } -------------------------------------------------------------------------------- /src/udpkit/udpEvent.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System.Runtime.InteropServices; 26 | 27 | namespace UdpKit { 28 | public enum UdpSendFailReason { 29 | None, 30 | StreamOverflow, 31 | NotConnected, 32 | PacketWindowFull, 33 | SocketError, 34 | SerializerReturnedFalse 35 | } 36 | 37 | public enum UdpEventType { 38 | ConnectRequest = UdpEvent.PUBLIC_CONNECT_REQUEST, 39 | ConnectFailed = UdpEvent.PUBLIC_CONNECT_FAILED, 40 | ConnectRefused = UdpEvent.PUBLIC_CONNECT_REFUSED, 41 | Connected = UdpEvent.PUBLIC_CONNECTED, 42 | Disconnected = UdpEvent.PUBLIC_DISCONNECTED, 43 | ObjectSendFailed = UdpEvent.PUBLIC_OBJECT_SEND_FAILED, 44 | ObjectRejected = UdpEvent.PUBLIC_OBJECT_REJECTED, 45 | ObjectDelivered = UdpEvent.PUBLIC_OBJECT_DELIVERED, 46 | ObjectLost = UdpEvent.PUBLIC_OBJECT_LOST, 47 | ObjectReceived = UdpEvent.PUBLIC_OBJECT_RECEIVED 48 | } 49 | 50 | [StructLayout(LayoutKind.Explicit)] 51 | public struct UdpEvent { 52 | 53 | struct UdpEventReferenceObjects { 54 | public UdpConnection Connection; 55 | public object Object; 56 | } 57 | 58 | internal const int INTERNAL_START = 1; 59 | internal const int INTERNAL_CONNECT = 3; 60 | internal const int INTERNAL_ACCEPT = 5; 61 | internal const int INTERNAL_REFUSE = 7; 62 | internal const int INTERNAL_DISCONNECT = 9; 63 | internal const int INTERNAL_CLOSE = 11; 64 | internal const int INTERNAL_SEND = 13; 65 | internal const int INTERNAL_CONNECTION_OPTION = 15; 66 | 67 | internal const int PUBLIC_CONNECT_REQUEST = 2; 68 | internal const int PUBLIC_CONNECT_FAILED = 4; 69 | internal const int PUBLIC_CONNECT_REFUSED = 6; 70 | internal const int PUBLIC_CONNECTED = 8; 71 | internal const int PUBLIC_DISCONNECTED = 10; 72 | internal const int PUBLIC_OBJECT_SEND_FAILED = 12; 73 | internal const int PUBLIC_OBJECT_REJECTED = 14; 74 | internal const int PUBLIC_OBJECT_DELIVERED = 16; 75 | internal const int PUBLIC_OBJECT_LOST = 18; 76 | internal const int PUBLIC_OBJECT_RECEIVED = 20; 77 | 78 | [FieldOffset(0)] 79 | internal int Type; 80 | 81 | [FieldOffset(4)] 82 | UdpEndPoint endPoint; 83 | 84 | [FieldOffset(4)] 85 | internal UdpConnectionOption Option; 86 | 87 | [FieldOffset(4)] 88 | UdpSendFailReason failReason; 89 | 90 | [FieldOffset(8)] 91 | internal int OptionIntValue; 92 | 93 | [FieldOffset(8)] 94 | internal int OptionFloatValue; 95 | 96 | [FieldOffset(16)] 97 | UdpEventReferenceObjects Refs; 98 | 99 | internal bool IsInternal { 100 | get { return (Type & 1) == 1; } 101 | } 102 | 103 | public UdpEventType EventType { 104 | get { return (UdpEventType) Type; } 105 | } 106 | 107 | public UdpEndPoint EndPoint { 108 | get { return endPoint; } 109 | internal set { endPoint = value; } 110 | } 111 | 112 | public UdpSendFailReason FailedReason { 113 | get { return failReason; } 114 | internal set { failReason = value; } 115 | } 116 | 117 | public UdpConnection Connection { 118 | get { return Refs.Connection; } 119 | internal set { Refs.Connection = value; } 120 | } 121 | 122 | public object Object { 123 | get { return Refs.Object; } 124 | internal set { Refs.Object = value; } 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /proj/managed/udpkit.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {82A76EF8-2122-437C-B34D-62D28EBFA0BA} 8 | Library 9 | Properties 10 | UdpKit 11 | udpkit 12 | v2.0 13 | 512 14 | 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | TRACE;DEBUG;UDPKIT_DLL_UDPKIT 22 | prompt 23 | 4 24 | false 25 | 26 | 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | true 34 | 35 | 36 | 37 | 38 | 39 | 40 | Properties\AssemblyInfo.cs 41 | 42 | 43 | half.cs 44 | 45 | 46 | udpAddress.cs 47 | 48 | 49 | udpAssert.cs 50 | 51 | 52 | udpBitStream.cs 53 | 54 | 55 | udpByteConverter.cs 56 | 57 | 58 | udpCommand.cs 59 | 60 | 61 | udpConfig.cs 62 | 63 | 64 | udpConnection.cs 65 | 66 | 67 | udpConnectionStats.cs 68 | 69 | 70 | udpEndpoint.cs 71 | 72 | 73 | udpEvent.cs 74 | 75 | 76 | udpException.cs 77 | 78 | 79 | udpHeader.cs 80 | 81 | 82 | udpLog.cs 83 | 84 | 85 | udpMath.cs 86 | 87 | 88 | udpPlatform.cs 89 | 90 | 91 | udpRingBuffer.cs 92 | 93 | 94 | udpSendHandle.cs 95 | 96 | 97 | udpSerializer.cs 98 | 99 | 100 | udpSet.cs 101 | 102 | 103 | udpSocket.cs 104 | 105 | 106 | udpSocketMultiplexer.cs 107 | 108 | 109 | udpUtils.cs 110 | 111 | 112 | 113 | 120 | -------------------------------------------------------------------------------- /src/udpkit.stresstest/udpSendChannel.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System; 26 | using System.Collections.Generic; 27 | using System.Text; 28 | 29 | namespace UdpKit.stresstest { 30 | 31 | class udpSendChannel { 32 | int tail; 33 | int mask; 34 | int shift; 35 | int count; 36 | node[] nodes; 37 | udpSequenceGenerator generator; 38 | 39 | enum state { 40 | empty, 41 | queued, 42 | pending, 43 | delivered 44 | } 45 | 46 | struct node { 47 | public state state; 48 | public uint sequence; 49 | public T value; 50 | } 51 | 52 | public bool isFull { 53 | get { return count == nodes.Length; } 54 | } 55 | 56 | public bool isEmpty { 57 | get { return count == 0; } 58 | } 59 | 60 | public int inQueue { 61 | get { return count; } 62 | } 63 | 64 | public udpSendChannel (int windowBits, int sequenceBits) { 65 | nodes = new node[1 << windowBits]; 66 | shift = 32 - sequenceBits; 67 | mask = nodes.Length - 1; 68 | generator = new udpSequenceGenerator(sequenceBits, uint.MaxValue); 69 | } 70 | 71 | public bool tryNack (uint sequence) { 72 | return tryChangeState(sequence, state.queued); 73 | } 74 | 75 | public bool tryAck (uint sequence) { 76 | return tryChangeState(sequence, state.delivered); 77 | } 78 | 79 | bool tryChangeState (uint sequence, state state) { 80 | if (count == 0) { 81 | return false; 82 | } 83 | 84 | int distance = sequenceDistance(sequence, nodes[tail].sequence); 85 | if (distance < 0 || distance >= count) { 86 | return false; 87 | } 88 | 89 | nodes[(tail + distance) & mask].state = state; 90 | return true; 91 | } 92 | 93 | public bool tryNextSend (ref uint sequence, ref T value) { 94 | if (count == 0) 95 | return false; 96 | 97 | for (int i = 0; i < count; ++i) { 98 | int index = (tail + i) & mask; 99 | 100 | if (nodes[index].state == state.queued) { 101 | sequence = nodes[index].sequence; 102 | value = nodes[index].value; 103 | nodes[index].state = state.pending; 104 | return true; 105 | } 106 | } 107 | 108 | return false; 109 | } 110 | 111 | public bool tryRemoveAcked (ref uint sequence, ref T value) { 112 | if (count > 0 && nodes[tail].state == state.delivered) { 113 | sequence = nodes[tail].sequence; 114 | value = nodes[tail].value; 115 | nodes[tail] = new node(); 116 | 117 | tail += 1; 118 | tail &= mask; 119 | 120 | count -= 1; 121 | return true; 122 | } 123 | 124 | return false; 125 | } 126 | 127 | public bool tryInsert (T value) { 128 | if (count == 0) { 129 | nodes[tail].sequence = generator.next(); 130 | nodes[tail].state = state.queued; 131 | nodes[tail].value = value; 132 | } else { 133 | if (count == nodes.Length) { 134 | return false; 135 | } 136 | 137 | int index = (tail + count) & mask; 138 | nodes[index].state = state.queued; 139 | nodes[index].sequence = generator.next(); 140 | nodes[index].value = value; 141 | } 142 | 143 | count += 1; 144 | return true; 145 | } 146 | 147 | int sequenceDistance (uint from, uint to) { 148 | from <<= shift; 149 | to <<= shift; 150 | return ((int) (from - to)) >> shift; 151 | } 152 | } 153 | } -------------------------------------------------------------------------------- /src/udpkit.platform.managed/udpPlatformManaged.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System; 26 | using System.Net; 27 | using System.Net.Sockets; 28 | 29 | namespace UdpKit { 30 | public sealed class UdpPlatformManaged : UdpPlatform { 31 | Socket socket; 32 | EndPoint recvEndPoint; 33 | IPAddress convertAddress; 34 | IPEndPoint convertEndPoint; 35 | SocketError socketError; 36 | 37 | public UdpPlatformManaged () { 38 | socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 39 | socket.Blocking = false; 40 | 41 | SetConnReset(socket); 42 | 43 | recvEndPoint = new IPEndPoint(IPAddress.Any, 0); 44 | convertEndPoint = new IPEndPoint(IPAddress.Any, 0); 45 | convertAddress = new IPAddress(0L); 46 | } 47 | 48 | public override UdpSocketInterfaceError Error { 49 | get { 50 | switch (socketError) { 51 | case SocketError.WouldBlock: 52 | return UdpSocketInterfaceError.WouldBlock; 53 | 54 | default: 55 | return UdpSocketInterfaceError.Unknown; 56 | } 57 | } 58 | } 59 | 60 | public override UdpEndPoint EndPoint { 61 | get { return ConvertEndPoint((IPEndPoint) socket.LocalEndPoint); } 62 | } 63 | 64 | public override long PlatformError { 65 | get { return (long) socketError; } 66 | } 67 | 68 | public override string PlatformErrorString { 69 | get { return socketError.ToString(); } 70 | } 71 | 72 | public override uint PlatformPrecisionTime { 73 | get { return UdpPrecisionTimer.GetCurrentTime(); } 74 | } 75 | 76 | public override bool Close () { 77 | try { 78 | socket.Close(); 79 | return true; 80 | } catch (SocketException exn) { 81 | socketError = exn.SocketErrorCode; 82 | return false; 83 | } 84 | } 85 | 86 | public override bool Bind (UdpEndPoint endpoint) { 87 | try { 88 | socket.Bind(ConvertEndPoint(endpoint)); 89 | return true; 90 | } catch (SocketException exn) { 91 | socketError = exn.SocketErrorCode; 92 | return false; 93 | } 94 | } 95 | 96 | public override bool RecvPoll (int timeoutInMs) { 97 | try { 98 | return socket.Poll(timeoutInMs * 1000, SelectMode.SelectRead); 99 | } catch (SocketException exn) { 100 | socketError = exn.SocketErrorCode; 101 | return false; 102 | } 103 | } 104 | 105 | public override bool RecvFrom (byte[] buffer, int bufferSize, ref int bytesReceived, ref UdpEndPoint remoteEndpoint) { 106 | try { 107 | bytesReceived = socket.ReceiveFrom(buffer, 0, bufferSize, SocketFlags.None, ref recvEndPoint); 108 | 109 | if (bytesReceived > 0) { 110 | remoteEndpoint = ConvertEndPoint((IPEndPoint) recvEndPoint); 111 | return true; 112 | } else { 113 | return false; 114 | } 115 | } catch (SocketException exn) { 116 | socketError = exn.SocketErrorCode; 117 | return false; 118 | } 119 | } 120 | 121 | public override bool SendTo (byte[] buffer, int bytesToSend, UdpEndPoint endpoint, ref int bytesSent) { 122 | try { 123 | bytesSent = socket.SendTo(buffer, 0, bytesToSend, SocketFlags.None, ConvertEndPoint(endpoint)); 124 | return bytesSent == bytesToSend; 125 | } catch (SocketException exn) { 126 | socketError = exn.SocketErrorCode; 127 | return false; 128 | } 129 | } 130 | 131 | #pragma warning disable 618 132 | UdpEndPoint ConvertEndPoint (IPEndPoint endpoint) { 133 | return new UdpEndPoint(new UdpIPv4Address(endpoint.Address.Address), (ushort) endpoint.Port); 134 | } 135 | 136 | IPEndPoint ConvertEndPoint (UdpEndPoint endpoint) { 137 | long netOrder = IPAddress.HostToNetworkOrder((int) endpoint.Address.Packet); 138 | convertAddress.Address = netOrder; 139 | convertEndPoint.Address = convertAddress; 140 | convertEndPoint.Port = endpoint.Port; 141 | return convertEndPoint; 142 | } 143 | #pragma warning restore 618 144 | 145 | void SetConnReset (Socket s) { 146 | try { 147 | const uint IOC_IN = 0x80000000; 148 | const uint IOC_VENDOR = 0x18000000; 149 | uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12; 150 | s.IOControl((int) SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null); 151 | } catch { } 152 | } 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /src/udpkit/udpConfig.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System.Threading; 26 | 27 | namespace UdpKit { 28 | public class UdpConfig { 29 | /// 30 | /// The default MTU for new connections, default: 512 (bytes) 31 | /// 32 | public int DefaultMtu = 512; 33 | 34 | /// 35 | /// The default network ping for new connections, default: 0.1f (seconds) 36 | /// 37 | public float DefaultNetworkPing = 0.1f; 38 | 39 | /// 40 | /// The default aliased ping for new connections, default: 0.15f (seconds) 41 | /// 42 | public float DefaultAliasedPing = 0.15f; 43 | 44 | /// 45 | /// The default value of "AlwaysSendMtu" setting for new connections, default: false 46 | /// 47 | public bool DefaultAlwaysSendMtu = false; 48 | 49 | /// 50 | /// If we allow serialization to overflow MTU of the connection, default: false 51 | /// 52 | public bool AllowPacketOverflow = false; 53 | 54 | /// 55 | /// The max ping allowed for a connection, default: 4000 (milliseconds) 56 | /// 57 | public uint MaxPing = 4000; 58 | 59 | /// 60 | /// The timeout until we should make a new connect request, default: 1000 (milliseconds) 61 | /// 62 | public uint ConnectRequestTimeout = 1000; 63 | 64 | /// 65 | /// How many attempts we should make to connect before failing, default: 5 66 | /// 67 | public uint ConnectRequestAttempts = 5; 68 | 69 | /// 70 | /// How long before we time-out a connection we have not heard anything from, default: 5000 (ms) 71 | /// 72 | public uint ConnectionTimeout = 5000; 73 | 74 | /// 75 | /// How long we should wait to send a ping packet to the remote end if we 76 | /// have not sent anything recently, default: 100 (ms) 77 | /// 78 | public uint PingTimeout = 100; 79 | 80 | /// 81 | /// How many packets we can receive before we force an ack packet to be sent, default: 8 82 | /// 83 | public uint RecvWithoutAckLimit = 8; 84 | 85 | /// 86 | /// How many % of the packets we should drop to simulate packet loss, default: 0 87 | /// 88 | public float SimulatedLoss = 0f; 89 | 90 | /// 91 | /// The smallest allowed MTU, default: 128 92 | /// 93 | public int MtuMin = 128; 94 | 95 | /// 96 | /// The largest allowed MTU, default: 2048 97 | /// 98 | public int MtuMax = 2048; 99 | 100 | /// 101 | /// How large our packet window is, this means how many packets we can have "in transit" at once, before 102 | /// forcefully disconnecting the remote, default: 256 103 | /// 104 | public int PacketWindow = 256; 105 | 106 | /// 107 | /// How many connections we allow, default: 64 108 | /// 109 | public int ConnectionLimit = 64; 110 | 111 | /// 112 | /// If we allow incomming connections, default: true 113 | /// 114 | public bool AllowIncommingConnections = true; 115 | 116 | /// 117 | /// IF we automatically accept incomming connections if we have slots free, default: true 118 | /// 119 | public bool AutoAcceptIncommingConnections = true; 120 | 121 | /// 122 | /// If we should calculate network ping, this adds a 2 byte overhead to each packet, default: true 123 | /// 124 | public bool CalculateNetworkPing = true; 125 | 126 | /// 127 | /// If we should write the packet bit size into the packet itself, this adds a 2 byte overhead to each packet, default: true 128 | /// 129 | public bool WritePacketBitSize = true; 130 | 131 | /// 132 | /// If we allow clients which are connecting to a server to implicitly accept the connection 133 | /// if we get a non-rejected and non-accepted packet from the server, meaning the accept packet 134 | /// was lost, default: true 135 | /// 136 | public bool AllowImplicitAccept = true; 137 | 138 | /// 139 | /// How many bits we should reserve for acking in the packet header, default: 64 140 | /// 141 | public int AckRedundancy = 64; 142 | 143 | /// 144 | /// How large the event queues should by default, default: 4096 145 | /// 146 | public int InitialEventQueueSize = 4096; 147 | 148 | internal UdpConfig Duplicate () { 149 | return (UdpConfig) MemberwiseClone(); 150 | } 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /src/slimmath/half.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2007-2010 SlimDX Group 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | using System.Runtime.InteropServices; 24 | 25 | namespace SlimMath { 26 | internal static class HalfUtilities { 27 | static readonly uint[] HalfToFloatMantissaTable = new uint[2048]; 28 | static readonly uint[] HalfToFloatExponentTable = new uint[64]; 29 | static readonly uint[] HalfToFloatOffsetTable = new uint[64]; 30 | static readonly ushort[] FloatToHalfBaseTable = new ushort[512]; 31 | static readonly byte[] FloatToHalfShiftTable = new byte[512]; 32 | 33 | [StructLayout(LayoutKind.Explicit)] 34 | struct FloatToUint { 35 | [FieldOffset(0)] 36 | public uint uintValue; 37 | 38 | [FieldOffset(0)] 39 | public float floatValue; 40 | } 41 | 42 | static HalfUtilities () { 43 | int i; 44 | 45 | //Mantissa table 46 | 47 | //0 => 0 48 | HalfToFloatMantissaTable[0] = 0; 49 | 50 | //Transform subnormal to normalized 51 | for (i = 1; i < 1024; i++) { 52 | uint m = ((uint) i) << 13; 53 | uint e = 0; 54 | 55 | while ((m & 0x00800000) == 0) { 56 | e -= 0x00800000; 57 | m <<= 1; 58 | } 59 | 60 | m &= ~0x00800000U; 61 | e += 0x38800000; 62 | HalfToFloatMantissaTable[i] = m | e; 63 | } 64 | 65 | //Normal case 66 | for (i = 1024; i < 2048; i++) 67 | HalfToFloatMantissaTable[i] = 0x38000000 + (((uint) (i - 1024)) << 13); 68 | 69 | //Exponent table 70 | 71 | //0 => 0 72 | HalfToFloatExponentTable[0] = 0; 73 | 74 | for (i = 1; i < 63; i++) { 75 | if (i < 31) { 76 | //Positive Numbers 77 | HalfToFloatExponentTable[i] = ((uint) i) << 23; 78 | } else { 79 | //Negative Numbers 80 | HalfToFloatExponentTable[i] = 0x80000000 + (((uint) (i - 32)) << 23); 81 | } 82 | } 83 | HalfToFloatExponentTable[31] = 0x47800000; 84 | HalfToFloatExponentTable[32] = 0x80000000; 85 | HalfToFloatExponentTable[63] = 0xC7800000; 86 | 87 | //Offset table 88 | HalfToFloatOffsetTable[0] = 0; 89 | for (i = 1; i < 64; i++) 90 | HalfToFloatOffsetTable[i] = 1024; 91 | HalfToFloatOffsetTable[32] = 0; 92 | 93 | //Float to Half tables 94 | for (i = 0; i < 256; i++) { 95 | int e = i - 127; 96 | if (e < -24) { 97 | //Very small numbers map to zero 98 | FloatToHalfBaseTable[i | 0x000] = 0x0000; 99 | FloatToHalfBaseTable[i | 0x100] = 0x8000; 100 | FloatToHalfShiftTable[i | 0x000] = 24; 101 | FloatToHalfShiftTable[i | 0x100] = 24; 102 | } else if (e < -14) { 103 | //Small numbers map to denorms 104 | FloatToHalfBaseTable[i | 0x000] = (ushort) ((0x0400 >> (-e - 14))); 105 | FloatToHalfBaseTable[i | 0x100] = (ushort) ((0x0400 >> (-e - 14)) | 0x8000); 106 | FloatToHalfShiftTable[i | 0x000] = (byte) (-e - 1); 107 | FloatToHalfShiftTable[i | 0x100] = (byte) (-e - 1); 108 | } else if (e <= 15) { 109 | //Normal numbers just lose precision 110 | FloatToHalfBaseTable[i | 0x000] = (ushort) (((e + 15) << 10)); 111 | FloatToHalfBaseTable[i | 0x100] = (ushort) (((e + 15) << 10) | 0x8000); 112 | FloatToHalfShiftTable[i | 0x000] = 13; 113 | FloatToHalfShiftTable[i | 0x100] = 13; 114 | } else if (e < 128) { 115 | //Large numbers map to Infinity 116 | FloatToHalfBaseTable[i | 0x000] = 0x7C00; 117 | FloatToHalfBaseTable[i | 0x100] = 0xFC00; 118 | FloatToHalfShiftTable[i | 0x000] = 24; 119 | FloatToHalfShiftTable[i | 0x100] = 24; 120 | } else { 121 | //Infinity and NaN's stay Infinity and NaN's 122 | FloatToHalfBaseTable[i | 0x000] = 0x7C00; 123 | FloatToHalfBaseTable[i | 0x100] = 0xFC00; 124 | FloatToHalfShiftTable[i | 0x000] = 13; 125 | FloatToHalfShiftTable[i | 0x100] = 13; 126 | } 127 | } 128 | } 129 | 130 | public static float Unpack (ushort value) { 131 | var conv = new FloatToUint(); 132 | conv.uintValue = HalfToFloatMantissaTable[HalfToFloatOffsetTable[value >> 10] + (((uint) value) & 0x3ff)] + HalfToFloatExponentTable[value >> 10]; 133 | return conv.floatValue; 134 | } 135 | 136 | public static ushort Pack (float value) { 137 | FloatToUint conv = new FloatToUint(); 138 | conv.floatValue = value; 139 | return (ushort) (FloatToHalfBaseTable[(conv.uintValue >> 23) & 0x1ff] + ((conv.uintValue & 0x007fffff) >> FloatToHalfShiftTable[(conv.uintValue >> 23) & 0x1ff])); 140 | } 141 | } 142 | } -------------------------------------------------------------------------------- /src/udpkit.lib/socket.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2012-2013 Fredrik Holmstrom (fredrik.johan.holmstrom@gmail.com) 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | #include "socket.h" 26 | 27 | static int udpStartCalls = 0; 28 | 29 | static bool udpStart() { 30 | bool ok = true; 31 | 32 | #if UDPKIT_WIN 33 | if (udpStartCalls == 0) { 34 | WSADATA wsaData = { 0 }; 35 | ok = WSAStartup(MAKEWORD(2, 2), &wsaData) == 0; 36 | } 37 | #endif 38 | 39 | udpStartCalls += 1; 40 | return ok; 41 | } 42 | 43 | static void udpShutdown() { 44 | udpStartCalls -= 1; 45 | 46 | #ifdef UDPKIT_WIN 47 | if (udpStartCalls == 0) { 48 | WSACleanup(); 49 | } 50 | #endif 51 | } 52 | 53 | static S32 udpLastError() { 54 | #ifdef UDPKIT_WIN 55 | return WSAGetLastError(); 56 | #else 57 | return errno; 58 | #endif 59 | } 60 | 61 | EXPORT_API udpSocket* udpCreate() { 62 | if (udpStart()) { 63 | udpSocket* socket = new udpSocket(); 64 | socket->endPoint = udpEndPoint(); 65 | socket->lastError = 0; 66 | socket->recvBufferSize = 1 << 15; 67 | socket->sendBufferSize = 1 << 15; 68 | socket->nativeSocket = INVALID_SOCKET; 69 | socket->nativeSocket = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); 70 | 71 | if (socket->nativeSocket == INVALID_SOCKET) { 72 | return NULL; 73 | } 74 | 75 | return socket; 76 | } 77 | else { 78 | return NULL; 79 | } 80 | } 81 | 82 | EXPORT_API S32 udpBind(udpSocket* socket, udpEndPoint addr) { 83 | S32 result = 0; 84 | 85 | UDPKIT_CHECK_VALIDSOCKET(socket); 86 | 87 | sockaddr_in bind; 88 | bind.sin_family = AF_INET; 89 | bind.sin_addr.s_addr = htonl(addr.address); 90 | bind.sin_port = htons(addr.port); 91 | 92 | #if UDPKIT_WIN 93 | #else 94 | //U32 reuseaddr = 1; 95 | //result = setsockopt(socket->nativeSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&reuseaddr, sizeof(reuseaddr)); 96 | //UDPKIT_CHECK_RESULT(result); 97 | #endif 98 | 99 | result = ::bind(socket->nativeSocket, (sockaddr*)&bind, sizeof(bind)); 100 | UDPKIT_CHECK_RESULT(result); 101 | 102 | result = setsockopt(socket->nativeSocket, SOL_SOCKET, SO_RCVBUF, (char *)&socket->recvBufferSize, sizeof(socket->recvBufferSize)); 103 | UDPKIT_CHECK_RESULT(result); 104 | 105 | result = setsockopt(socket->nativeSocket, SOL_SOCKET, SO_SNDBUF, (char *)&socket->sendBufferSize, sizeof(socket->sendBufferSize)); 106 | UDPKIT_CHECK_RESULT(result); 107 | 108 | #if UDPKIT_WIN 109 | DWORD nonblock = 1; 110 | result = ioctlsocket(socket->nativeSocket, FIONBIO, &nonblock); 111 | UDPKIT_CHECK_RESULT(result); 112 | #else 113 | U32 notblock = 1; 114 | result = ioctl(socket->nativeSocket, FIONBIO, ¬block); 115 | UDPKIT_CHECK_RESULT(result); 116 | #endif 117 | 118 | sockaddr address; 119 | socklen_t addressSize = sizeof(address); 120 | getsockname(socket->nativeSocket, (sockaddr*)&address, &addressSize); 121 | socket->endPoint.address = ntohl(((sockaddr_in*)&address)->sin_addr.s_addr); 122 | socket->endPoint.port = ntohs(((sockaddr_in*)&address)->sin_port); 123 | 124 | return UDPKIT_SOCKET_OK; 125 | } 126 | 127 | EXPORT_API S32 udpSendTo(udpSocket* socket, char* buffer, S32 size, udpEndPoint addr) { 128 | UDPKIT_CHECK_VALIDSOCKET(socket); 129 | 130 | sockaddr_in to; 131 | to.sin_family = AF_INET; 132 | to.sin_addr.s_addr = htonl(addr.address); 133 | to.sin_port = htons(addr.port); 134 | 135 | S32 result = ::sendto(socket->nativeSocket, buffer, size, 0, (sockaddr*)&to, sizeof(to)); 136 | UDPKIT_CHECK_RESULT(result); 137 | 138 | return result; 139 | } 140 | 141 | EXPORT_API S32 udpRecvFrom(udpSocket* socket, char* buffer, S32 size, udpEndPoint* addr) { 142 | UDPKIT_CHECK_VALIDSOCKET(socket); 143 | 144 | sockaddr_in from; 145 | socklen_t fromSize = sizeof(from); 146 | 147 | S32 result = ::recvfrom(socket->nativeSocket, buffer, size, 0, (sockaddr*)&from, &fromSize); 148 | UDPKIT_CHECK_RESULT(result); 149 | 150 | addr->port = ntohs(from.sin_port); 151 | addr->address = ntohl(from.sin_addr.s_addr); 152 | 153 | return result; 154 | } 155 | 156 | EXPORT_API S32 udpRecvPoll(udpSocket* socket, S32 timeoutMs) { 157 | UDPKIT_CHECK_VALIDSOCKET(socket); 158 | 159 | #if defined(UDPKIT_WIN) && defined(UDPKIT_WIN_WSAPOLL) 160 | WSAPOLLFD poll; 161 | poll.fd = socket->nativeSocket; 162 | poll.events = POLLRDNORM; 163 | 164 | S32 result = ::WSAPoll(&poll, 1, timeoutMs); 165 | UDPKIT_CHECK_RESULT(result); 166 | 167 | if (poll.revents & POLLRDNORM) { 168 | return UDPKIT_SOCKET_OK; 169 | } 170 | 171 | return UDPKIT_SOCKET_NODATA; 172 | #else 173 | fd_set set; 174 | timeval tv; 175 | 176 | FD_ZERO(&set); 177 | FD_SET(socket->nativeSocket, &set); 178 | 179 | tv.tv_sec = 0; 180 | tv.tv_usec = timeoutMs * 1000; 181 | 182 | S32 result = select(1, &set, NULL, NULL, &tv); 183 | if (result == SOCKET_ERROR) { 184 | return UDPKIT_SOCKET_ERROR; 185 | } 186 | 187 | if (FD_ISSET(socket->nativeSocket, &set)) { 188 | return UDPKIT_SOCKET_OK; 189 | } 190 | 191 | return UDPKIT_SOCKET_NODATA; 192 | #endif 193 | } 194 | 195 | EXPORT_API S32 udpLastError(udpSocket* socket) { 196 | return socket->lastError; 197 | } 198 | 199 | EXPORT_API S32 udpGetEndPoint(udpSocket* socket, udpEndPoint* endPoint) { 200 | *endPoint = udpEndPoint(); 201 | UDPKIT_CHECK_VALIDSOCKET(socket); 202 | *endPoint = socket->endPoint; 203 | return UDPKIT_SOCKET_OK; 204 | } 205 | 206 | EXPORT_API S32 udpClose(udpSocket* socket) { 207 | UDPKIT_CHECK_VALIDSOCKET(socket); 208 | 209 | #ifdef UDPKIT_WIN 210 | S32 result = closesocket(socket->nativeSocket); 211 | #else 212 | S32 result = close(socket->nativeSocket); 213 | #endif 214 | 215 | // delete socket object 216 | delete socket; 217 | 218 | if (result == SOCKET_ERROR) { 219 | S32 error = udpLastError(); 220 | udpShutdown(); 221 | return error; 222 | } 223 | else { 224 | udpShutdown(); 225 | return UDPKIT_SOCKET_OK; 226 | } 227 | } 228 | -------------------------------------------------------------------------------- /src/udpkit.examples.chat/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Text; 5 | using System.Threading; 6 | using UdpKit; 7 | 8 | namespace UdpKit.Examples.Chat { 9 | 10 | class ChatSerializer : UdpSerializer { 11 | public override bool Pack (ref UdpBitStream stream, ref object o) { 12 | // cast to string and get bytes 13 | string msg = (string) o; 14 | byte[] bytes = Encoding.UTF8.GetBytes(msg); 15 | 16 | // write length and bytes into buffer 17 | stream.WriteInt(bytes.Length); 18 | stream.WriteByteArray(bytes); 19 | 20 | return true; 21 | } 22 | 23 | public override bool Unpack (ref UdpBitStream stream, ref object o) { 24 | // read length and create array, then read bytes into array 25 | byte[] bytes = new byte[stream.ReadInt()]; 26 | stream.ReadByteArray(bytes); 27 | 28 | // convert bytes to string 29 | o = Encoding.UTF8.GetString(bytes); 30 | return true; 31 | } 32 | } 33 | 34 | class Server { 35 | UdpSocket socket; 36 | List clients; 37 | 38 | public Server () { 39 | socket = UdpSocket.Create(); 40 | socket.Start(new UdpEndPoint(UdpIPv4Address.Localhost, 14000)); 41 | clients = new List(); 42 | } 43 | 44 | public void Loop () { 45 | UdpEvent ev = default(UdpEvent); 46 | 47 | while (true) { 48 | while (socket.Poll(ref ev)) { 49 | switch (ev.EventType) { 50 | case UdpEventType.Connected: 51 | // log in local console 52 | UdpLog.User("Client connected from {0}, total clients {1}", ev.Connection.RemoteEndPoint, socket.ConnectionCount); 53 | 54 | // send welcome message 55 | ev.Connection.Send("Welcome to the chat server!"); 56 | 57 | // send message to all other clients 58 | SendToAllClients("Client connected from {0}", ev.Connection.RemoteEndPoint); 59 | 60 | // add to client list 61 | clients.Add(ev.Connection); 62 | break; 63 | 64 | case UdpEventType.Disconnected: 65 | // log in local console 66 | UdpLog.User("Client at {0} disconnected, total clients {1}", ev.Connection.RemoteEndPoint, socket.ConnectionCount); 67 | 68 | // remove from client list 69 | clients.Remove(ev.Connection); 70 | 71 | // Send message to all others 72 | SendToAllClients("Client at {0} disconnected", ev.Connection.RemoteEndPoint); 73 | break; 74 | 75 | // When we receive, just forward to all clients 76 | case UdpEventType.ObjectReceived: 77 | SendToAllClients(ev.Object as string); 78 | break; 79 | 80 | // If lost, resend to connection it was lost on 81 | case UdpEventType.ObjectLost: 82 | ev.Connection.Send(ev.Object); 83 | break; 84 | } 85 | } 86 | 87 | // Simulate ~60fps game loop 88 | Thread.Sleep(16); 89 | } 90 | } 91 | 92 | void SendToAllClients (string message, params object[] args) { 93 | message = string.Format(message, args); 94 | 95 | foreach (UdpConnection connection in clients) { 96 | connection.Send(message); 97 | } 98 | } 99 | } 100 | 101 | class Client { 102 | 103 | delegate string ReadLine (); 104 | 105 | UdpSocket socket; 106 | 107 | public Client () { 108 | socket = UdpSocket.Create(); 109 | socket.Start(UdpEndPoint.Any); 110 | socket.Connect(new UdpEndPoint(UdpIPv4Address.Localhost, 14000)); 111 | } 112 | 113 | public void Loop () { 114 | UdpEvent ev = default(UdpEvent); 115 | StreamReader input = new StreamReader(Console.OpenStandardInput()); 116 | Char[] buffer = new Char[1024]; 117 | ReadLine read = Console.ReadLine; 118 | IAsyncResult result = null; 119 | UdpConnection connection = null; 120 | 121 | while (true) { 122 | while (socket.Poll(ref ev)) { 123 | switch (ev.EventType) { 124 | case UdpEventType.Connected: 125 | UdpLog.User("Connected to server at {0}", ev.Connection.RemoteEndPoint); 126 | connection = ev.Connection; 127 | break; 128 | 129 | case UdpEventType.Disconnected: 130 | UdpLog.User("Disconnected from server at {0}", ev.Connection.RemoteEndPoint); 131 | connection = null; 132 | break; 133 | 134 | case UdpEventType.ObjectReceived: 135 | Console.WriteLine(": " + (ev.Object as string)); 136 | break; 137 | } 138 | } 139 | 140 | if (result == null) { 141 | result = read.BeginInvoke(null, null); 142 | } 143 | 144 | if (result.IsCompleted) { 145 | if (connection != null) { 146 | connection.Send(read.EndInvoke(result)); 147 | } 148 | 149 | result = read.BeginInvoke(null, null); 150 | } 151 | 152 | // Simulate ~60fps game loop 153 | Thread.Sleep(16); 154 | } 155 | } 156 | 157 | } 158 | 159 | class Program { 160 | static void Main (string[] args) { 161 | Console.WriteLine("Example: Chat"); 162 | Console.WriteLine("Press [S] to start server"); 163 | Console.WriteLine("Press [C] to start client"); 164 | Console.Write("... "); 165 | 166 | UdpLog.SetWriter(Console.WriteLine); 167 | 168 | switch (Console.ReadKey(true).Key) { 169 | case ConsoleKey.S: 170 | Console.WriteLine("Server"); 171 | new Server().Loop(); 172 | break; 173 | 174 | case ConsoleKey.C: 175 | Console.WriteLine("Client"); 176 | new Client().Loop(); 177 | break; 178 | 179 | default: 180 | Main(args); 181 | break; 182 | } 183 | } 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /src/udpkit.stresstest/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Text; 5 | using System.Threading; 6 | 7 | namespace UdpKit.stresstest { 8 | struct pair { 9 | public uint seq; 10 | public uint val; 11 | 12 | public pair (uint seq, uint val) { 13 | this.seq = seq; 14 | this.val = val; 15 | } 16 | } 17 | 18 | class ConnectionObject { 19 | bool done = false; 20 | public uint recvNext = 0; 21 | public uint fromNumber = 0; 22 | public uint toNumber = 1 << 11; 23 | public UdpConnection connection = null; 24 | public udpSendChannel sendChan = new udpSendChannel(6, 8); 25 | public udpRecvChannel recvChan = new udpRecvChannel(6, 8); 26 | 27 | public bool QueueNext () { 28 | if (fromNumber < toNumber && sendChan.tryInsert(fromNumber)) { 29 | fromNumber += 1u; 30 | return true; 31 | } 32 | 33 | return false; 34 | } 35 | 36 | public void Ack (pair p) { 37 | if (sendChan.tryAck(p.seq)) { 38 | uint seq = 0, val = 0; 39 | 40 | while (sendChan.tryRemoveAcked(ref seq, ref val)) { 41 | UdpLog.User("delivered {0} (seq: {1})", val, seq); 42 | } 43 | } 44 | } 45 | 46 | public void Nack (pair p) { 47 | UdpLog.User("lost {0} (seq: {1})", p.val, p.seq); 48 | sendChan.tryNack(p.seq); 49 | } 50 | 51 | public void Send () { 52 | uint seq = 0, val = 0; 53 | 54 | while (sendChan.tryNextSend(ref seq, ref val)) { 55 | connection.Send(new pair(seq, val)); 56 | } 57 | } 58 | 59 | public void Recv (pair p) { 60 | recvChan.tryAdd(p.seq, p.val); 61 | } 62 | 63 | public void DequeueReceived () { 64 | uint seq = 0, val = 0; 65 | 66 | while (recvChan.tryRemove(ref seq, ref val)) { 67 | if (val != recvNext) { 68 | throw new Exception(); 69 | } 70 | 71 | UdpLog.User("received {0} (seq: {1})", val, seq); 72 | recvNext = val + 1u; 73 | 74 | if (recvNext == toNumber) { 75 | done = true; 76 | } 77 | } 78 | } 79 | } 80 | 81 | class Serializer : UdpSerializer { 82 | public override bool Pack (ref UdpBitStream buffer, ref object o) { 83 | pair p = (pair) o; 84 | buffer.WriteUInt(p.seq, 32); 85 | buffer.WriteUInt(p.val, 32); 86 | 87 | UdpLog.User("sending {0} (seq: {1})", p.val, p.seq); 88 | return true; 89 | } 90 | 91 | public override bool Unpack (ref UdpBitStream buffer, ref object o) { 92 | pair p = new pair(); 93 | p.seq = buffer.ReadUInt(32); 94 | p.val = buffer.ReadUInt(32); 95 | o = p; 96 | return true; 97 | } 98 | } 99 | 100 | abstract class SocketObject { 101 | protected UdpSocket socket; 102 | 103 | public List connections = new List(256); 104 | 105 | public abstract ushort Port { get; } 106 | public abstract void Started (); 107 | 108 | public SocketObject () { 109 | socket = UdpSocket.Create(new UdpConfig { SimulatedLoss = 0.25f, ConnectionTimeout = 100000000, PingTimeout = 10, ConnectionLimit = -1 }); 110 | } 111 | 112 | public void Start () { 113 | socket.Start(new UdpEndPoint(UdpIPv4Address.Localhost, Port)); 114 | Started(); 115 | } 116 | 117 | public bool Process () { 118 | UdpEvent ev = default(UdpEvent); 119 | ConnectionObject co = null; 120 | pair val = default(pair); 121 | 122 | if (socket.Poll(ref ev)) { 123 | switch (ev.EventType) { 124 | case UdpEventType.Connected: 125 | ev.Connection.UserToken = co = new ConnectionObject(); 126 | co.connection = ev.Connection; 127 | connections.Add(ev.Connection); 128 | 129 | for (int i = 0; i < 16; ++i) { 130 | co.QueueNext(); 131 | co.Send(); 132 | } 133 | 134 | break; 135 | 136 | case UdpEventType.ObjectLost: 137 | val = (pair) ev.Object; 138 | co = (ConnectionObject) ev.Connection.UserToken; 139 | co.Nack(val); 140 | co.Send(); 141 | break; 142 | 143 | case UdpEventType.ObjectDelivered: 144 | val = (pair) ev.Object; 145 | co = (ConnectionObject) ev.Connection.UserToken; 146 | co.Ack(val); 147 | co.QueueNext(); 148 | co.Send(); 149 | break; 150 | 151 | case UdpEventType.ObjectReceived: 152 | val = (pair) ev.Object; 153 | co = (ConnectionObject) ev.Connection.UserToken; 154 | co.Recv(val); 155 | co.DequeueReceived(); 156 | break; 157 | 158 | case UdpEventType.ObjectRejected: 159 | Console.WriteLine("REJECTED"); 160 | break; 161 | 162 | case UdpEventType.ObjectSendFailed: 163 | Console.WriteLine("SENDFAILED"); 164 | break; 165 | } 166 | 167 | return true; 168 | } 169 | 170 | return false; 171 | } 172 | } 173 | 174 | class ClientObject : SocketObject { 175 | public override ushort Port { 176 | get { return 0; } 177 | } 178 | 179 | public override void Started () { 180 | socket.Connect(new UdpEndPoint(UdpIPv4Address.Localhost, 14000)); 181 | } 182 | } 183 | 184 | class ServerObject : SocketObject { 185 | public override ushort Port { 186 | get { return 14000; } 187 | } 188 | 189 | public override void Started () { 190 | } 191 | } 192 | 193 | 194 | class Program { 195 | 196 | static void ProcThread () { 197 | while (true) { 198 | bool any = false; 199 | 200 | for (int i = 0; i < sockets.Length; ++i) { 201 | any = any || sockets[i].Process(); 202 | } 203 | 204 | if (!any) { 205 | Thread.Sleep(1); 206 | } 207 | } 208 | } 209 | 210 | const int ClientCount = 32; 211 | 212 | static SocketObject[] sockets; 213 | static DateTime start; 214 | public static int connectionsCreated = 0; 215 | public static int ConnectionCount = ClientCount * 2; 216 | 217 | static void connectionStats (UdpConnection c) { 218 | UdpConnectionStats s = c.Stats; 219 | Console.WriteLine("{0}: {1} / {2} / {3} / {4}", c.RemoteEndPoint, s.PacketsSent, s.PacketsReceived, s.CommandSent, s.CommandsReceived); 220 | } 221 | 222 | static void Main (string[] args) { 223 | if(File.Exists("log.txt")) 224 | File.Delete("log.txt"); 225 | 226 | var fs = File.AppendText("log.txt"); 227 | sockets = new SocketObject[ClientCount + 1]; 228 | Thread th = new Thread(ProcThread); 229 | UdpLog.SetWriter(s => { fs.WriteLine(s); }); 230 | 231 | sockets[0] = new ServerObject(); 232 | 233 | for (int i = 1; i < sockets.Length; ++i) { 234 | sockets[i] = new ClientObject(); 235 | } 236 | 237 | start = DateTime.Now; 238 | th.Start(); 239 | 240 | for (int i = 0; i < sockets.Length; ++i) { 241 | sockets[i].Start(); 242 | } 243 | 244 | while (true) { 245 | Console.Clear(); 246 | 247 | for (int i = 0; i < sockets[0].connections.Count; ++i) { 248 | connectionStats(sockets[0].connections[i]); 249 | } 250 | 251 | 252 | Console.WriteLine("-"); 253 | 254 | for (int i = 1; i < sockets.Length; ++i) { 255 | if (sockets[i].connections.Count > 0) { 256 | connectionStats(sockets[i].connections[0]); 257 | } 258 | } 259 | 260 | Thread.Sleep(100); 261 | } 262 | } 263 | } 264 | } 265 | --------------------------------------------------------------------------------