├── .github └── FUNDING.yml ├── .gitignore ├── CONTRIBUTING.md ├── GenericProtocol.sln ├── GenericProtocol ├── Factory.cs ├── GenericProtocol.csproj ├── IClient.cs ├── INetworkDiscovery.cs ├── IServer.cs └── Implementation │ ├── ArraySegmentExtensions.cs │ ├── BinaryDownlink.cs │ ├── BinaryUplink.cs │ ├── Globals.cs │ ├── LeadingByteProcessor.cs │ ├── NetworkDiscovery.cs │ ├── ProtoClient.cs │ ├── ProtoServer.cs │ └── SocketExtensions.cs ├── GenericProtocolTest ├── GenericProtocolTest.csproj └── Program.cs ├── Images └── Icon.png ├── LICENSE ├── README.md └── appveyor.yml /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: mrousavy 2 | ko_fi: mrousavy 3 | custom: ["https://paypal.me/mrousavy"] 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # .NET Core 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | **/Properties/launchSettings.json 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # Visual Studio code coverage results 117 | *.coverage 118 | *.coveragexml 119 | 120 | # NCrunch 121 | _NCrunch_* 122 | .*crunch*.local.xml 123 | nCrunchTemp_* 124 | 125 | # MightyMoose 126 | *.mm.* 127 | AutoTest.Net/ 128 | 129 | # Web workbench (sass) 130 | .sass-cache/ 131 | 132 | # Installshield output folder 133 | [Ee]xpress/ 134 | 135 | # DocProject is a documentation generator add-in 136 | DocProject/buildhelp/ 137 | DocProject/Help/*.HxT 138 | DocProject/Help/*.HxC 139 | DocProject/Help/*.hhc 140 | DocProject/Help/*.hhk 141 | DocProject/Help/*.hhp 142 | DocProject/Help/Html2 143 | DocProject/Help/html 144 | 145 | # Click-Once directory 146 | publish/ 147 | 148 | # Publish Web Output 149 | *.[Pp]ublish.xml 150 | *.azurePubxml 151 | # TODO: Comment the next line if you want to checkin your web deploy settings 152 | # but database connection strings (with potential passwords) will be unencrypted 153 | *.pubxml 154 | *.publishproj 155 | 156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 157 | # checkin your Azure Web App publish settings, but sensitive information contained 158 | # in these scripts will be unencrypted 159 | PublishScripts/ 160 | 161 | # NuGet Packages 162 | *.nupkg 163 | # The packages folder can be ignored because of Package Restore 164 | **/packages/* 165 | # except build/, which is used as an MSBuild target. 166 | !**/packages/build/ 167 | # Uncomment if necessary however generally it will be regenerated when needed 168 | #!**/packages/repositories.config 169 | # NuGet v3's project.json files produces more ignorable files 170 | *.nuget.props 171 | *.nuget.targets 172 | 173 | # Microsoft Azure Build Output 174 | csx/ 175 | *.build.csdef 176 | 177 | # Microsoft Azure Emulator 178 | ecf/ 179 | rcf/ 180 | 181 | # Windows Store app package directories and files 182 | AppPackages/ 183 | BundleArtifacts/ 184 | Package.StoreAssociation.xml 185 | _pkginfo.txt 186 | 187 | # Visual Studio cache files 188 | # files ending in .cache can be ignored 189 | *.[Cc]ache 190 | # but keep track of directories ending in .cache 191 | !*.[Cc]ache/ 192 | 193 | # Others 194 | ClientBin/ 195 | ~$* 196 | *~ 197 | *.dbmdl 198 | *.dbproj.schemaview 199 | *.jfm 200 | *.pfx 201 | *.publishsettings 202 | orleans.codegen.cs 203 | 204 | # Since there are multiple workflows, uncomment next line to ignore bower_components 205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 206 | #bower_components/ 207 | 208 | # RIA/Silverlight projects 209 | Generated_Code/ 210 | 211 | # Backup & report files from converting an old project file 212 | # to a newer Visual Studio version. Backup files are not needed, 213 | # because we have git ;-) 214 | _UpgradeReport_Files/ 215 | Backup*/ 216 | UpgradeLog*.XML 217 | UpgradeLog*.htm 218 | 219 | # SQL Server files 220 | *.mdf 221 | *.ldf 222 | *.ndf 223 | 224 | # Business Intelligence projects 225 | *.rdl.data 226 | *.bim.layout 227 | *.bim_*.settings 228 | 229 | # Microsoft Fakes 230 | FakesAssemblies/ 231 | 232 | # GhostDoc plugin setting file 233 | *.GhostDoc.xml 234 | 235 | # Node.js Tools for Visual Studio 236 | .ntvs_analysis.dat 237 | node_modules/ 238 | 239 | # Typescript v1 declaration files 240 | typings/ 241 | 242 | # Visual Studio 6 build log 243 | *.plg 244 | 245 | # Visual Studio 6 workspace options file 246 | *.opt 247 | 248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 249 | *.vbw 250 | 251 | # Visual Studio LightSwitch build output 252 | **/*.HTMLClient/GeneratedArtifacts 253 | **/*.DesktopClient/GeneratedArtifacts 254 | **/*.DesktopClient/ModelManifest.xml 255 | **/*.Server/GeneratedArtifacts 256 | **/*.Server/ModelManifest.xml 257 | _Pvt_Extensions 258 | 259 | # Paket dependency manager 260 | .paket/paket.exe 261 | paket-files/ 262 | 263 | # FAKE - F# Make 264 | .fake/ 265 | 266 | # JetBrains Rider 267 | .idea/ 268 | *.sln.iml 269 | 270 | # CodeRush 271 | .cr/ 272 | 273 | # Python Tools for Visual Studio (PTVS) 274 | __pycache__/ 275 | *.pyc 276 | 277 | # Cake - Uncomment if you are using it 278 | # tools/** 279 | # !tools/packages.config 280 | 281 | # Telerik's JustMock configuration file 282 | *.jmconfig 283 | 284 | # BizTalk build output 285 | *.btp.cs 286 | *.btm.cs 287 | *.odx.cs 288 | *.xsd.cs 289 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## Bugs and Feature Requests 4 | 1. Report **bugs/issues** in the [Issues](https://github.com/mrousavy/GenericProtocol/issues) section. Please explain your bugs as best you can. 5 | 2. Ask for **features** in the [Issues](https://github.com/mrousavy/GenericProtocol/issues) section too. 6 | 7 | ## Pull Requests 8 | **Performance**/**code** **enhancements**, **new features** or **bugfixes** will be 9 | happily accepted as long as they follow these rules: 10 | 11 | 1. It fits the current **API design** 12 | 2. It fits my current **code style** 13 | 3. It **works** 14 | -------------------------------------------------------------------------------- /GenericProtocol.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26730.12 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GenericProtocol", "GenericProtocol\GenericProtocol.csproj", "{C6D68B1B-95EC-4216-A23E-3A7F5F5A145D}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GenericProtocolTest", "GenericProtocolTest\GenericProtocolTest.csproj", "{C7CB0EA9-D686-436B-8DCF-27A2A2E523AA}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {C6D68B1B-95EC-4216-A23E-3A7F5F5A145D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {C6D68B1B-95EC-4216-A23E-3A7F5F5A145D}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {C6D68B1B-95EC-4216-A23E-3A7F5F5A145D}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {C6D68B1B-95EC-4216-A23E-3A7F5F5A145D}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {C7CB0EA9-D686-436B-8DCF-27A2A2E523AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {C7CB0EA9-D686-436B-8DCF-27A2A2E523AA}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {C7CB0EA9-D686-436B-8DCF-27A2A2E523AA}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {C7CB0EA9-D686-436B-8DCF-27A2A2E523AA}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {862E9D1A-47AB-4F35-999F-5B10A7ECEB21} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /GenericProtocol/Factory.cs: -------------------------------------------------------------------------------- 1 | //TODO: (Implement BinaryDownlink and remove the #ifs and #defines) 2 | //#define implemented 3 | 4 | using System.Net; 5 | using System.Threading.Tasks; 6 | using GenericProtocol.Implementation; 7 | 8 | namespace GenericProtocol 9 | { 10 | /// 11 | /// The and 12 | /// start factory 13 | /// 14 | public static class Factory 15 | { 16 | #region Client 17 | 18 | /// 19 | /// Start and Connect a new 20 | /// 21 | /// The Type of object to send over the network 22 | /// The 's 23 | /// The 's Port 24 | /// A connected instance 25 | public static async Task> StartNewClient(string address, int port) 26 | { 27 | var client = new ProtoClient(IPAddress.Parse(address), port); 28 | await client.Connect(); 29 | return client; 30 | } 31 | 32 | /// 33 | /// Start and Connect a new 34 | /// 35 | /// The Type of object to send over the network 36 | /// The 's 37 | /// The 's Port 38 | /// 39 | /// Whether to use a seperate 40 | /// for all data transfers 41 | /// 42 | /// A connected instance 43 | public static async Task> StartNewClient(string address, int port, bool newThread) 44 | { 45 | var client = new ProtoClient(IPAddress.Parse(address), port); 46 | await client.Connect(newThread); 47 | return client; 48 | } 49 | 50 | #if implemented 51 | /// 52 | /// Start and Connect a new 53 | /// that sends and receives pure binary data ( array) 54 | /// 55 | /// The Type of object to send over the network 56 | /// The 's 57 | /// The 's Port 58 | /// A connected instance 59 | public static async Task> StartNewBinaryDownlink(string address, int port) { 60 | var client = new BinaryDownlink(IPAddress.Parse(address), port); 61 | await client.Connect(); 62 | return client; 63 | } 64 | 65 | /// 66 | /// Start and Connect a new 67 | /// that sends and receives pure binary data ( array) 68 | /// 69 | /// The 's 70 | /// The 's Port 71 | /// Whether to use a seperate 72 | /// for all data transfers 73 | /// A connected instance 74 | public static async Task> StartNewBinaryDownlink(string address, int port, bool newThread) { 75 | var client = new BinaryDownlink(IPAddress.Parse(address), port); 76 | await client.Connect(newThread); 77 | return client; 78 | } 79 | #endif 80 | 81 | #endregion 82 | 83 | #region Server 84 | 85 | //TODO: Server 86 | 87 | #endregion 88 | } 89 | } -------------------------------------------------------------------------------- /GenericProtocol/GenericProtocol.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.0;netstandard2.0 5 | GenericProtocol 6 | 1.0.35 7 | mrousavy, cbarosch 8 | mrousavy 9 | Generic Protocol 10 | A fast TCP event based buffered server/client protocol for transferring data over the network in .NET Core/Classic 11 | https://github.com/mrousavy/GenericProtocol/blob/master/LICENSE 12 | https://github.com/mrousavy/GenericProtocol 13 | https://github.com/mrousavy/GenericProtocol 14 | GitHub 15 | tcp socket protocol client server 16 | 1.0.3.5 17 | 1.0.3.5 18 | Bugfixes, Binary Down/Up-Links, Network Discovery 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /GenericProtocol/IClient.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using GenericProtocol.Implementation; 4 | 5 | namespace GenericProtocol 6 | { 7 | /// 8 | /// A Client. 9 | /// 10 | /// ( should be marked as ) 11 | /// 12 | /// 13 | /// The Type of the Messages to use 14 | /// (has to be ZeroFormatter marked, see: ) 15 | /// 16 | public interface IClient : IDisposable 17 | { 18 | /// 19 | /// Indicating whether this 20 | /// should automatically reconnect to the 21 | /// once a connection is lost 22 | /// 23 | bool AutoReconnect { get; set; } 24 | 25 | /// 26 | /// Delay between reconnect attempts in milliseconds 27 | /// 28 | int ReconnectInterval { get; set; } 29 | 30 | /// 31 | /// Delay between Server pings in milliseconds 32 | /// 33 | int PingDelay { get; set; } 34 | 35 | /// 36 | /// The size of receive buffers (should be equal or 37 | /// less than bandwidth) 38 | /// 39 | int ReceiveBufferSize { get; set; } 40 | 41 | /// 42 | /// The size of send buffers (should be equal or 43 | /// less than bandwidth) 44 | /// 45 | int SendBufferSize { get; set; } 46 | 47 | /// 48 | /// Represents the current status of the Connection 49 | /// 50 | ConnectionStatus ConnectionStatus { get; } 51 | 52 | /// 53 | /// Event for received messages 54 | /// 55 | event ReceivedHandler ReceivedMessage; 56 | 57 | /// 58 | /// Event on connection to server loss 59 | /// 60 | event ConnectionContextHandler ConnectionLost; 61 | 62 | /// 63 | /// Connect the Socket to the set IP Address 64 | /// and start receiving messages 65 | /// 66 | /// 67 | /// True, if the 68 | /// should be operating on a seperate Thread. 69 | /// 70 | Task Connect(bool seperateThread); 71 | 72 | /// 73 | /// Gracefully disconnect from the Server 74 | /// 75 | void Disconnect(); 76 | 77 | /// 78 | /// Send a new Message to the Server 79 | /// 80 | /// 81 | /// The message object 82 | /// to serialize and send to the server 83 | /// 84 | Task Send(T message); 85 | } 86 | } -------------------------------------------------------------------------------- /GenericProtocol/INetworkDiscovery.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Net; 3 | using System.Threading.Tasks; 4 | using GenericProtocol.Implementation; 5 | 6 | namespace GenericProtocol 7 | { 8 | /// 9 | /// A protocol to discover other GenericProtocol 10 | /// s in your network 11 | /// via a UDP Broadcast 12 | /// 13 | public interface INetworkDiscovery 14 | { 15 | /// 16 | /// Discover all s in the 17 | /// given network by sending a UDP broadcast message 18 | /// 19 | /// 20 | /// The port to use for the discovery service 21 | /// (same as used in ) 22 | /// 23 | /// 24 | /// A containing all 25 | /// discovery results 26 | /// 27 | Task Discover(int port = Constants.DiscoveryPort); 28 | 29 | /// 30 | /// Start a new Listener on the given network which 31 | /// responds to calls 32 | /// 33 | /// 34 | /// The network's IP to start listening in 35 | /// (By default: ) 36 | /// 37 | /// 38 | /// The port to use for the discovery service 39 | /// 40 | void Host(IPAddress networkIp, int port = Constants.DiscoveryPort); 41 | } 42 | 43 | 44 | /// 45 | /// The Result of a call 46 | /// 47 | public interface IDiscoveryResult 48 | { 49 | /// 50 | /// True if the 51 | /// found one or more s in the network 52 | /// 53 | bool Any { get; } 54 | 55 | /// 56 | /// The count of the hosts that responded in the network 57 | /// 58 | int HostsCount { get; } 59 | 60 | /// 61 | /// An of s 62 | /// representing all Hosts that responded to a 63 | /// call 64 | /// 65 | IEnumerable Hosts { get; } 66 | } 67 | } -------------------------------------------------------------------------------- /GenericProtocol/IServer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net; 4 | using System.Threading.Tasks; 5 | using GenericProtocol.Implementation; 6 | 7 | namespace GenericProtocol 8 | { 9 | /// 10 | /// 11 | /// A Server. 12 | /// 13 | /// ( should be marked as ) 14 | /// 15 | /// 16 | /// The Type of the Messages to use 17 | /// (has to be ZeroFormatter marked, see: ) 18 | /// 19 | public interface IServer : IDisposable 20 | { 21 | /// 22 | /// Delay between Client pings in milliseconds 23 | /// 24 | int PingDelay { get; set; } 25 | 26 | /// 27 | /// The size of the receive buffers (should be equal or 28 | /// less than bandwidth) 29 | /// 30 | int ReceiveBufferSize { get; set; } 31 | 32 | /// 33 | /// The size of the send buffers (should be equal or 34 | /// less than bandwidth) 35 | /// 36 | int SendBufferSize { get; set; } 37 | 38 | /// 39 | /// The maximum clients to queue on simultanious connection attempts 40 | /// 41 | int MaxConnectionsBacklog { get; set; } 42 | 43 | /// 44 | /// An list of all the connected clients' s 45 | /// 46 | IEnumerable Clients { get; } 47 | 48 | /// 49 | /// Event for just connected clients 50 | /// 51 | event ConnectionContextHandler ClientConnected; 52 | 53 | /// 54 | /// Event for just disconnected clients 55 | /// 56 | event ConnectionContextHandler ClientDisconnected; 57 | 58 | /// 59 | /// Event for received messages 60 | /// 61 | event ReceivedHandler ReceivedMessage; 62 | 63 | /// 64 | /// Bind the Socket to the set IP Address 65 | /// and start listening for incoming connections 66 | /// 67 | /// 68 | /// True, if the 69 | /// should be operating on a seperate Thread. 70 | /// 71 | void Start(bool seperateThread); 72 | 73 | /// 74 | /// Stop the Server and disconnect all Clients 75 | /// gracefully 76 | /// 77 | void Stop(); 78 | 79 | /// 80 | /// Send a new Message to the Client 81 | /// 82 | /// 83 | /// The message object 84 | /// to serialize and send to the client 85 | /// 86 | /// 87 | /// The client (IP + Port) 88 | /// to send the message to 89 | /// 90 | Task Send(T message, IPEndPoint to); 91 | 92 | /// 93 | /// Broadcast a new Message to all connected Clients 94 | /// 95 | /// 96 | /// The message object 97 | /// to serialize and send to the client 98 | /// 99 | Task Broadcast(T message); 100 | 101 | /// 102 | /// Gracefully disconnect a Client with the given 103 | /// IP Address and Port and returns true if successful 104 | /// 105 | /// 106 | /// The Client to kick by IP Address and Port 107 | /// 108 | /// 109 | /// Thrown when the given 110 | /// could not be found in the connected clients. 111 | /// 112 | /// 113 | /// Indicating whether the disconnect was successful 114 | /// 115 | bool Kick(IPEndPoint endPoint); 116 | } 117 | } -------------------------------------------------------------------------------- /GenericProtocol/Implementation/ArraySegmentExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace GenericProtocol.Implementation 4 | { 5 | public static class ArraySegmentExtensions 6 | { 7 | /// 8 | /// Take a portion of this 9 | /// 10 | /// this 11 | /// The start index of the slice 12 | /// The length of the slice 13 | public static ArraySegment SliceEx(this ArraySegment segment, int start, int count) 14 | { 15 | if (segment == default(ArraySegment)) throw new ArgumentNullException(nameof(segment)); 16 | if (start < 0 || start >= segment.Count) throw new ArgumentOutOfRangeException(nameof(start)); 17 | if (count < 1 || start + count > segment.Count) throw new ArgumentOutOfRangeException(nameof(count)); 18 | 19 | return new ArraySegment(segment.Array, start, count); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /GenericProtocol/Implementation/BinaryDownlink.cs: -------------------------------------------------------------------------------- 1 | namespace GenericProtocol.Implementation 2 | { 3 | /// 4 | /// The client for the protocol for transferring binary large objects (BLOBs) like images or files. 5 | /// 6 | public class BinaryDownlink /*: IClient*/ 7 | { 8 | // TODO: Implement BinaryDownlink once ProtoClient is tested & done 9 | } 10 | } -------------------------------------------------------------------------------- /GenericProtocol/Implementation/BinaryUplink.cs: -------------------------------------------------------------------------------- 1 | namespace GenericProtocol.Implementation 2 | { 3 | /// 4 | /// A protocol for transferring binary large objects (BLOBs) like images or files. 5 | /// 6 | public class BinaryUplink /*: IServer */ 7 | { 8 | // TODO: Implement BinaryUplink once ProtoServer is tested & done 9 | } 10 | } -------------------------------------------------------------------------------- /GenericProtocol/Implementation/Globals.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | 4 | namespace GenericProtocol.Implementation 5 | { 6 | public delegate void ConnectionContextHandler( 7 | IPEndPoint endPoint); 8 | 9 | public delegate void ReceivedHandler( 10 | IPEndPoint senderEndPoint, 11 | T message); 12 | 13 | /// 14 | /// The status of a Connection 15 | /// 16 | public enum ConnectionStatus 17 | { 18 | /// 19 | /// Indicating that the 20 | /// or is currently 21 | /// disconnected 22 | /// 23 | Disconnected = 0, 24 | 25 | /// 26 | /// Indicating that the 27 | /// or is currently 28 | /// trying to (re-)connect 29 | /// 30 | Connecting = 1, 31 | 32 | /// 33 | /// Indicating that the 34 | /// or is currently 35 | /// bound and connected 36 | /// 37 | Connected = 2 38 | } 39 | 40 | internal static class Constants 41 | { 42 | internal const int ReceiveBufferSize = 1024; // Size of the receive buffer 43 | internal const int SendBufferSize = 1024; // Size of the send buffer 44 | internal const int LeadingByteSize = sizeof(int); // Size of the leading byte prefix 45 | internal const int MaxConnectionsBacklog = 10; // Maximum num. of sim. connection requests to queue 46 | internal const int PingDelay = 5000; // Delay between ping messages 47 | internal const int ReconnectInterval = 500; // Interval between reconnect attempts 48 | internal const int DiscoveryPort = 15000; // The port use for other GenericProtocol client-discovery 49 | } 50 | 51 | 52 | public class TransferException : Exception 53 | { 54 | public TransferException(string message) : base(message) 55 | { } 56 | } 57 | 58 | public class NotFoundException : Exception 59 | { 60 | public NotFoundException(string message) : base(message) 61 | { } 62 | } 63 | 64 | public class GenericProtocolException : Exception 65 | { 66 | public GenericProtocolException(string message) : base(message) 67 | { } 68 | } 69 | 70 | public class NetworkInterfaceException : Exception 71 | { 72 | public NetworkInterfaceException(string message) : base(message) 73 | { } 74 | } 75 | } -------------------------------------------------------------------------------- /GenericProtocol/Implementation/LeadingByteProcessor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Sockets; 3 | using System.Threading.Tasks; 4 | 5 | namespace GenericProtocol.Implementation 6 | { 7 | internal static class LeadingByteProcessor 8 | { 9 | /// 10 | /// Number of bytes to reserve for the byte size that's going to get sent/received 11 | /// 12 | internal static int LeadingByteSize { get; set; } = Constants.LeadingByteSize; 13 | 14 | /// 15 | /// Read the prefix from a message (number of following bytes) 16 | /// 17 | /// The socket to read the leading bytes from 18 | /// Returns an awaitable 19 | internal static async Task ReadLeading(Socket socket) 20 | { 21 | var bytes = new byte[LeadingByteSize]; 22 | var segment = new ArraySegment(bytes); 23 | // read leading bytes 24 | int read = await socket.ReceiveAsync(segment, SocketFlags.None); 25 | 26 | if (read < 1) 27 | throw new TransferException($"{read} lead-bytes were read! " + 28 | "Null bytes could mean a connection shutdown."); 29 | 30 | // size of the following byte[] 31 | int size = BitConverter.ToInt32(segment.Array, 0); 32 | return size; 33 | } 34 | 35 | /// 36 | /// Send the prefix from a message (number of following bytes) 37 | /// 38 | /// The socket to read the leading bytes from 39 | /// The size of the following message (= leading byte's value) 40 | /// Returns an awaitable 41 | internal static async Task SendLeading(Socket socket, int size) 42 | { 43 | // build byte[] out of size 44 | var bytes = BitConverter.GetBytes(size); 45 | var segment = new ArraySegment(bytes); 46 | // send leading bytes 47 | int sent = await socket.SendAsync(segment, SocketFlags.None); 48 | 49 | if (sent < 1) 50 | throw new TransferException($"{sent} lead-bytes were sent! " + 51 | "Null bytes could mean a connection shutdown."); 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /GenericProtocol/Implementation/NetworkDiscovery.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Net.NetworkInformation; 6 | using System.Net.Sockets; 7 | using System.Threading.Tasks; 8 | 9 | namespace GenericProtocol.Implementation 10 | { 11 | public class NetworkDiscovery : INetworkDiscovery 12 | { 13 | // Property to write on (this is just a writebuffer dump) 14 | private byte[] PingerBytes { get; } = { 1 }; 15 | 16 | public async Task Discover(int port = Constants.DiscoveryPort) 17 | { 18 | // TODO: Make network discovery work 19 | var ip = new IPEndPoint(IPAddress.Broadcast, port); 20 | var segment = new ArraySegment(PingerBytes); 21 | 22 | // Iterate through all interfaces and send broadcast on each 23 | foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces()) 24 | { 25 | foreach (var address in netInterface.GetIPProperties().UnicastAddresses.Select(a => a.Address)) 26 | { 27 | if (address.IsIPv6LinkLocal) continue; // Skip IPv6 28 | 29 | // Open sender socket and dispose on finish 30 | using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) 31 | { 32 | client.EnableBroadcast = true; // By default this is disabled 33 | client.Bind(new IPEndPoint(address, port)); 34 | int sent = await client.SendToAsync(segment, SocketFlags.Broadcast, ip); 35 | 36 | // Build result 37 | var result = new DiscoveryResult(sent > 0, -1, null); 38 | return result; 39 | } 40 | } 41 | } 42 | 43 | throw new NetworkInterfaceException("No network interfaces were found!"); 44 | } 45 | 46 | public async void Host(IPAddress networkIp, int port = Constants.DiscoveryPort) 47 | { 48 | // TODO: Make network discovery work 49 | var ip = new IPEndPoint(networkIp, port); 50 | var segment = new ArraySegment(PingerBytes); 51 | 52 | // Open listener socket and dispose on error 53 | using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) 54 | { 55 | listener.EnableBroadcast = true; 56 | listener.Bind(ip); // bind to given IP Address 57 | // TODO: listener.Listen(Constants.MaxConnectionsBacklog); // Listen for incoming connections 58 | while (true) 59 | { 60 | // Loop until error 61 | // TODO: var client = await listener.AcceptAsync(); // Wait until client connects 62 | int received = await listener.ReceiveAsync(segment, SocketFlags.None); // receive from new socket 63 | if (received < 1) break; // Received null-byte terminator; exit function 64 | } 65 | } 66 | } 67 | } 68 | 69 | public struct DiscoveryResult : IDiscoveryResult, IEquatable 70 | { 71 | public bool Any { get; } 72 | public int HostsCount { get; } 73 | public IEnumerable Hosts { get; } 74 | 75 | public DiscoveryResult(bool any, int count, IEnumerable hosts) 76 | { 77 | Any = any; 78 | HostsCount = count; 79 | Hosts = hosts; 80 | } 81 | 82 | public bool Equals(DiscoveryResult other) => 83 | Any == other.Any && HostsCount == other.HostsCount && Equals(Hosts, other.Hosts); 84 | 85 | public override bool Equals(object obj) 86 | { 87 | if (ReferenceEquals(null, obj)) return false; 88 | return obj is DiscoveryResult && Equals((DiscoveryResult) obj); 89 | } 90 | 91 | public override int GetHashCode() 92 | { 93 | unchecked 94 | { 95 | int hashCode = Any.GetHashCode(); 96 | hashCode = (hashCode * 397) ^ HostsCount; 97 | hashCode = (hashCode * 397) ^ (Hosts != null ? Hosts.GetHashCode() : 0); 98 | return hashCode; 99 | } 100 | } 101 | } 102 | } -------------------------------------------------------------------------------- /GenericProtocol/Implementation/ProtoClient.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Sockets; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using ZeroFormatter; 7 | 8 | namespace GenericProtocol.Implementation 9 | { 10 | public class ProtoClient : IClient 11 | { 12 | #region Properties 13 | 14 | public int ReceiveBufferSize { get; set; } = Constants.ReceiveBufferSize; 15 | public int SendBufferSize { get; set; } = Constants.SendBufferSize; 16 | public int ReconnectInterval { get; set; } = Constants.ReconnectInterval; 17 | public int PingDelay { get; set; } = Constants.PingDelay; 18 | public ConnectionStatus ConnectionStatus { get; set; } // Status of connection 19 | 20 | public event ReceivedHandler ReceivedMessage; 21 | public event ConnectionContextHandler ConnectionLost; 22 | 23 | public bool AutoReconnect { get; set; } 24 | 25 | private IPEndPoint EndPoint { get; } // Server (remote) EndPoint 26 | private Socket Socket { get; } // Actual underlying socket 27 | 28 | #endregion 29 | 30 | #region ctor 31 | 32 | /// 33 | /// Create a new instance of the 34 | /// with the default and . 35 | /// Use to start and connect the socket. 36 | /// 37 | /// The server's to connect to 38 | /// The server's Port to connect to 39 | public ProtoClient(IPAddress address, int port) : 40 | this(address, port, AddressFamily.InterNetwork, SocketType.Stream) 41 | { } 42 | 43 | /// 44 | /// Create a new instance of the 45 | /// Use to start and connect the socket. 46 | /// 47 | /// 48 | /// The 49 | /// this should use 50 | /// 51 | /// 52 | /// The this 53 | /// should use 54 | /// 55 | /// The server's to connect to 56 | /// The server's Port to connect to 57 | public ProtoClient(IPAddress address, int port, AddressFamily family, SocketType type) 58 | { 59 | EndPoint = new IPEndPoint(address, port); 60 | Socket = new Socket(family, type, ProtocolType.Tcp); 61 | } 62 | 63 | #endregion 64 | 65 | #region Functions 66 | 67 | public async Task Connect(bool seperateThread = false) 68 | { 69 | if (ConnectionStatus == ConnectionStatus.Connected) 70 | throw new GenericProtocolException("Already connected!"); 71 | 72 | await Socket.ConnectAsync(EndPoint).ConfigureAwait(false); 73 | ConnectionStatus = ConnectionStatus.Connected; 74 | 75 | if (seperateThread) 76 | { 77 | // Launch on a new Thread 78 | new Thread(StartReceiving).Start(); 79 | new Thread(KeepAlive).Start(); 80 | } else 81 | { 82 | // Use Tasks 83 | StartReceiving(); 84 | KeepAlive(); 85 | } 86 | } 87 | 88 | public void Disconnect() 89 | { 90 | try 91 | { 92 | Socket?.Disconnect(false); 93 | ConnectionStatus = ConnectionStatus.Disconnected; 94 | Socket?.Close(); 95 | Socket?.Dispose(); 96 | } catch (ObjectDisposedException) 97 | { 98 | // already stopped 99 | } 100 | } 101 | 102 | public async Task Send(T message) 103 | { 104 | if (message.Equals(default(T))) throw new ArgumentNullException(nameof(message)); 105 | 106 | bool alive = Socket.Ping(); 107 | if (!alive) 108 | throw new TransferException($"The Socket to {EndPoint} is not responding!"); 109 | 110 | try 111 | { 112 | // build byte[] out of message (serialize with ZeroFormatter) 113 | var bytes = ZeroFormatterSerializer.Serialize(message); 114 | var segment = new ArraySegment(bytes); 115 | 116 | int size = bytes.Length; 117 | await LeadingByteProcessor.SendLeading(Socket, size) 118 | .ConfigureAwait(false); // Send receiver the byte count 119 | 120 | //TODO: Decide whether to catch errors in buffer-loop and continue once fixed or cancel whole send? 121 | int written = 0; 122 | while (written < size) 123 | { 124 | int send = size - written; // current buffer size 125 | if (send > SendBufferSize) 126 | send = SendBufferSize; // max size 127 | 128 | var slice = segment.SliceEx(written, send); // buffered portion of array 129 | written = await Socket.SendAsync(slice, SocketFlags.None).ConfigureAwait(false); 130 | } 131 | 132 | if (written < 1) 133 | throw new TransferException($"{written} bytes were sent! " + 134 | "Null bytes could mean a connection shutdown."); 135 | } catch (SocketException) 136 | { 137 | ConnectionLost?.Invoke(EndPoint); 138 | // On any error - cancel whole buffered writing 139 | if (AutoReconnect) 140 | await Reconnect().ConfigureAwait(false); // Try reconnecting and re-send everything once reconnected 141 | else 142 | throw; // Throw if we're not trying to reconnect 143 | } 144 | } 145 | 146 | public void Dispose() 147 | { 148 | Disconnect(); 149 | } 150 | 151 | #endregion 152 | 153 | #region Privates 154 | 155 | // Endless Start reading loop 156 | private void StartReceiving() 157 | { 158 | // Loop theoretically infinetly 159 | while (true) 160 | { 161 | try 162 | { 163 | // Read the leading "byte" 164 | long size = LeadingByteProcessor.ReadLeading(Socket).GetAwaiter().GetResult(); 165 | 166 | var bytes = new byte[size]; 167 | var segment = new ArraySegment(bytes); 168 | //TODO: Decide whether to catch errors in buffer-loop and continue once fixed or cancel whole receive? 169 | // read until all data is read 170 | int read = 0; 171 | while (read < size) 172 | { 173 | long receive = size - read; // current buffer size 174 | if (receive > ReceiveBufferSize) receive = ReceiveBufferSize; // max size 175 | 176 | var 177 | slice = segment.SliceEx(read, (int) receive); // get buffered portion of array 178 | read += Socket.ReceiveAsync(slice, SocketFlags.None).GetAwaiter().GetResult(); 179 | } 180 | 181 | var message = ZeroFormatterSerializer.Deserialize(segment.Array); 182 | 183 | ReceivedMessage?.Invoke(EndPoint, message); // call event 184 | } catch (ObjectDisposedException) 185 | { 186 | return; // Socket was closed & disposed -> exit 187 | } catch (SocketException) 188 | { 189 | ConnectionLost?.Invoke(EndPoint); 190 | if (!AutoReconnect) 191 | Reconnect().GetAwaiter().GetResult(); // Try reconnecting on an error, then continue receiving 192 | } 193 | 194 | // Listen again after client connected 195 | } 196 | } 197 | 198 | // Reconnect the Socket connection 199 | private async Task Reconnect() 200 | { 201 | // Don't reconnect if we're already reconnecting somewhere else 202 | if (ConnectionStatus == ConnectionStatus.Connecting) return; 203 | 204 | ConnectionStatus = ConnectionStatus.Connecting; // Connecting... 205 | while (true) 206 | { 207 | try 208 | { 209 | Socket.Disconnect(true); // Disconnect and reserve socket 210 | await Socket.ConnectAsync(EndPoint).ConfigureAwait(false); // Connect to Server 211 | ConnectionStatus = ConnectionStatus.Connected; 212 | return; 213 | } catch (SocketException) 214 | { 215 | // could not connect 216 | } 217 | 218 | await Task.Delay(ReconnectInterval).ConfigureAwait(false); // Try to reconnect all x milliseconds 219 | } 220 | } 221 | 222 | // Keep server connection alive by pinging 223 | private async void KeepAlive() 224 | { 225 | while (true) 226 | { 227 | await Task.Delay(PingDelay).ConfigureAwait(false); 228 | 229 | bool isAlive = Socket.Ping(); // Try to ping the server 230 | if (isAlive) continue; // Client responded, continue pinger 231 | 232 | // ---- Socket is NOT alive: ---- // 233 | ConnectionLost?.Invoke(EndPoint); 234 | // Client does not respond, try reconnecting, or disconnect & exit 235 | if (AutoReconnect) 236 | { 237 | await Reconnect().ConfigureAwait(false); // Wait for reconnect 238 | } else 239 | { 240 | Disconnect(); // Stop and exit 241 | return; 242 | } 243 | } 244 | } 245 | 246 | #endregion 247 | } 248 | } -------------------------------------------------------------------------------- /GenericProtocol/Implementation/ProtoServer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Net.Sockets; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using ZeroFormatter; 9 | 10 | namespace GenericProtocol.Implementation 11 | { 12 | public class ProtoServer : IServer 13 | { 14 | #region Properties 15 | 16 | public int MaxConnectionsBacklog { get; set; } = Constants.MaxConnectionsBacklog; 17 | public int PingDelay { get; set; } = Constants.PingDelay; 18 | public int ReceiveBufferSize { get; set; } = Constants.ReceiveBufferSize; 19 | public int SendBufferSize { get; set; } = Constants.SendBufferSize; 20 | public IEnumerable Clients => Sockets.Keys; 21 | 22 | public event ConnectionContextHandler ClientConnected; 23 | public event ConnectionContextHandler ClientDisconnected; 24 | public event ReceivedHandler ReceivedMessage; 25 | 26 | private IPEndPoint EndPoint { get; } 27 | private Socket Socket { get; } 28 | private IDictionary Sockets { get; } 29 | 30 | #endregion 31 | 32 | #region ctor 33 | 34 | /// 35 | /// Create a new instance of the 36 | /// with the default and . 37 | /// Use to bind and start the socket. 38 | /// 39 | /// The to start this Protocol on 40 | /// The Port to start this Protocol on 41 | public ProtoServer(IPAddress address, int port) : 42 | this(address, port, AddressFamily.InterNetwork, SocketType.Stream) 43 | { } 44 | 45 | /// 46 | /// Create a new instance of the . 47 | /// Use to bind and start the socket. 48 | /// 49 | /// 50 | /// The 51 | /// this should use 52 | /// 53 | /// 54 | /// The this 55 | /// should use 56 | /// 57 | /// The to start this Protocol on 58 | /// The Port to start this Protocol on 59 | public ProtoServer(IPAddress address, int port, AddressFamily family, SocketType type) 60 | { 61 | Sockets = new Dictionary(); 62 | EndPoint = new IPEndPoint(address, port); 63 | Socket = new Socket(family, type, ProtocolType.Tcp); 64 | } 65 | 66 | #endregion 67 | 68 | #region Functions 69 | 70 | /// 71 | /// Bind and Start the Server to the set IP Address. 72 | /// 73 | public void Start(bool seperateThread = false) 74 | { 75 | Socket.Bind(EndPoint); 76 | 77 | if (seperateThread) 78 | new Thread(StartListening).Start(); 79 | else 80 | StartListening(); 81 | } 82 | 83 | /// 84 | /// Shutdown the server and all active clients 85 | /// 86 | public void Stop() 87 | { 88 | foreach (var kvp in Sockets) 89 | { 90 | try 91 | { 92 | DisconnectClient(kvp.Key); 93 | } catch 94 | { 95 | // could not disconnect client 96 | } 97 | } 98 | } 99 | 100 | public async Task Send(T message, IPEndPoint to) 101 | { 102 | if (message.Equals(default(T))) 103 | throw new ArgumentNullException(nameof(message)); 104 | 105 | // Build a byte array of the serialized data 106 | var bytes = ZeroFormatterSerializer.Serialize(message); 107 | var segment = new ArraySegment(bytes); 108 | 109 | // Find socket 110 | var socket = Sockets.FirstOrDefault(c => c.Key.Equals(to)).Value; 111 | if (socket == null) 112 | throw new NetworkInterfaceException($"The IP Address {to} could not be found!"); 113 | 114 | int size = bytes.Length; 115 | await LeadingByteProcessor.SendLeading(socket, size).ConfigureAwait(false); // send leading size 116 | 117 | //TODO: Do something when sending interrupts? Wait for client to come back? 118 | // Write buffered 119 | int written = 0; 120 | while (written < size) 121 | { 122 | int send = size - written; // current buffer size 123 | if (send > SendBufferSize) send = SendBufferSize; // max size 124 | 125 | var slice = segment.SliceEx(written, send); // buffered portion of array 126 | written = await socket.SendAsync(slice, SocketFlags.None).ConfigureAwait(false); 127 | } 128 | 129 | if (written < 1) 130 | throw new TransferException($"{written} bytes were sent! " + 131 | "Null bytes could mean a connection shutdown."); 132 | } 133 | 134 | public async Task Broadcast(T message) 135 | { 136 | // Build list of Send(..) tasks 137 | var tasks = Sockets.Select(client => Send(message, client.Key)).ToList(); 138 | // await all 139 | await Task.WhenAll(tasks).ConfigureAwait(false); 140 | } 141 | 142 | 143 | public bool Kick(IPEndPoint endPoint) => DisconnectClient(endPoint); 144 | 145 | public void Dispose() 146 | { 147 | Stop(); 148 | Socket?.Dispose(); 149 | } 150 | 151 | #endregion 152 | 153 | #region Privates 154 | 155 | // Endless Start listening loop 156 | private async void StartListening() 157 | { 158 | Socket.Listen(10); 159 | // Loop theoretically infinetly 160 | while (true) 161 | { 162 | var client = await Socket.AcceptAsync().ConfigureAwait(false); // Block until accept 163 | var endpoint = client.RemoteEndPoint as IPEndPoint; // Get remote endpoint 164 | Sockets.Add(endpoint, client); // Add client to dictionary 165 | 166 | StartReading(client); // Start listening for data 167 | KeepAlive(client); // Keep client alive and ping 168 | 169 | ClientConnected?.Invoke(endpoint); // call event 170 | } 171 | // Listen again after client connected 172 | 173 | // ReSharper disable once FunctionNeverReturns 174 | } 175 | 176 | // Endless Start reading loop 177 | private async void StartReading(Socket client) 178 | { 179 | var endpoint = client.RemoteEndPoint as IPEndPoint; // Get remote endpoint 180 | 181 | // Loop theoretically infinetly 182 | while (true) 183 | { 184 | try 185 | { 186 | long size = await LeadingByteProcessor.ReadLeading(client).ConfigureAwait(false); // leading 187 | 188 | var bytes = new byte[size]; 189 | var segment = new ArraySegment(bytes); 190 | // TODO: Do something when receiving interrupts? Wait for client to come back? 191 | // read until all data is read 192 | int read = 0; 193 | while (read < size) 194 | { 195 | long receive = size - read; // current buffer size 196 | if (receive > ReceiveBufferSize) 197 | receive = ReceiveBufferSize; // max size 198 | 199 | var slice = segment.SliceEx(read, (int) receive); // get buffered portion of array 200 | read += await client.ReceiveAsync(slice, SocketFlags.None).ConfigureAwait(false); 201 | } 202 | 203 | if (read < 1) 204 | throw new TransferException($"{read} bytes were read! " + 205 | "Null bytes could mean a connection shutdown."); 206 | 207 | var message = ZeroFormatterSerializer.Deserialize(segment.Array); 208 | 209 | ReceivedMessage?.Invoke(endpoint, message); // call event 210 | } catch (SocketException ex) 211 | { 212 | Console.WriteLine(ex.ErrorCode); 213 | bool success = DisconnectClient(endpoint); // try to disconnect 214 | if (success) 215 | return; // Exit Reading loop once successfully disconnected 216 | } catch (ObjectDisposedException) 217 | { 218 | // client object is disposed 219 | bool success = DisconnectClient(endpoint); // try to disconnect 220 | if (success) 221 | return; // Exit Reading loop once successfully disconnected 222 | } catch (TransferException) 223 | { 224 | // 0 read bytes = null byte 225 | bool success = DisconnectClient(endpoint); // try to disconnect 226 | if (success) 227 | return; // Exit Reading loop once successfully disconnected 228 | } 229 | } // Listen again after client connected 230 | } 231 | 232 | // Keep a Client alive by pinging 233 | private async void KeepAlive(Socket client) 234 | { 235 | while (true) 236 | { 237 | try 238 | { 239 | await Task.Delay(PingDelay).ConfigureAwait(false); 240 | 241 | bool isAlive = client.Ping(); 242 | if (isAlive) 243 | continue; // Client responded 244 | } catch (ObjectDisposedException) 245 | { 246 | // client object is disposed 247 | } 248 | 249 | // Client does not respond, disconnect & exit 250 | DisconnectClient(client.RemoteEndPoint as IPEndPoint); 251 | return; 252 | } 253 | } 254 | 255 | // Disconnect a client; returns true if successful 256 | private bool DisconnectClient(IPEndPoint endPoint) 257 | { 258 | // Get all EndPoints/Sockets where the endpoint matches with this argument 259 | var filtered = Sockets.Where(c => c.Key.Equals(endPoint)).ToArray(); 260 | // .count should always be 1, CAN be more -> Loop 261 | foreach (var kvp in filtered) 262 | { 263 | try 264 | { 265 | kvp.Value.Disconnect(false); // Gracefully disconnect socket 266 | kvp.Value.Close(); 267 | kvp.Value.Dispose(); 268 | 269 | Sockets.Remove(kvp.Key); // Remove from collection 270 | ClientDisconnected?.Invoke(kvp.Key); // Event 271 | } catch 272 | { 273 | // Socket is either already disconnected, or failing to disconnect. try ping 274 | return !kvp.Value.Ping(); 275 | } 276 | } 277 | 278 | return true; 279 | } 280 | 281 | #endregion 282 | } 283 | } -------------------------------------------------------------------------------- /GenericProtocol/Implementation/SocketExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Sockets; 3 | 4 | namespace GenericProtocol.Implementation 5 | { 6 | public static class SocketExtensions 7 | { 8 | /// 9 | /// Ping this to check for an active connection 10 | /// 11 | /// The socket to ping 12 | /// True if the responds 13 | public static bool Ping(this Socket socket) 14 | { 15 | try 16 | { 17 | return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0); 18 | } catch (SocketException) 19 | { 20 | return false; 21 | } catch (ObjectDisposedException) 22 | { 23 | return false; 24 | } 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /GenericProtocolTest/GenericProtocolTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /GenericProtocolTest/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using GenericProtocol.Implementation; 4 | 5 | namespace GenericProtocolTest 6 | { 7 | public static class Program 8 | { 9 | private static ProtoServer _server; 10 | private static ProtoClient _client; 11 | private static readonly IPAddress ServerIp = IPAddress.Loopback; 12 | private static bool TestServer { get; } = false; 13 | private static bool TestClient { get; } = false; 14 | 15 | private static void Main(string[] args) 16 | { 17 | //INetworkDiscovery discovery = new NetworkDiscovery(); 18 | //discovery.Host(IPAddress.Any); 19 | //discovery.Discover(); 20 | 21 | if (TestServer) 22 | StartServer(); 23 | if (TestClient) 24 | StartClient(); 25 | 26 | Console.WriteLine("\n"); 27 | 28 | while (true) 29 | { 30 | string text = Console.ReadLine(); 31 | if (string.IsNullOrWhiteSpace(text)) continue; 32 | 33 | if (TestClient) 34 | SendToServer(text); 35 | else 36 | SendToClients(text); 37 | } 38 | } 39 | 40 | 41 | private static void StartClient() 42 | { 43 | _client = new ProtoClient(ServerIp, 1024) { AutoReconnect = true }; 44 | _client.ReceivedMessage += ClientMessageReceived; 45 | _client.ConnectionLost += Client_ConnectionLost; 46 | 47 | Console.WriteLine("Connecting"); 48 | _client.Connect().GetAwaiter().GetResult(); 49 | Console.WriteLine("Connected!"); 50 | _client.Send("Hello Server!").GetAwaiter().GetResult(); 51 | } 52 | 53 | private static void SendToServer(string message) 54 | { 55 | _client?.Send(message); 56 | } 57 | 58 | private static void SendToClients(string message) 59 | { 60 | _server?.Broadcast(message); 61 | } 62 | 63 | private static void Client_ConnectionLost(IPEndPoint endPoint) 64 | { 65 | Console.WriteLine($"Connection lost! {endPoint.Address}"); 66 | } 67 | 68 | private static void StartServer() 69 | { 70 | _server = new ProtoServer(IPAddress.Any, 1024); 71 | Console.WriteLine("Starting Server..."); 72 | _server.Start(); 73 | Console.WriteLine("Server started!"); 74 | _server.ClientConnected += ClientConnected; 75 | _server.ReceivedMessage += ServerMessageReceived; 76 | } 77 | 78 | private static async void ServerMessageReceived(IPEndPoint sender, string message) 79 | { 80 | Console.WriteLine($"{sender}: {message}"); 81 | await _server.Send($"Hello {sender}!", sender); 82 | } 83 | 84 | private static void ClientMessageReceived(IPEndPoint sender, string message) 85 | { 86 | Console.WriteLine($"{sender}: {message}"); 87 | } 88 | 89 | private static async void ClientConnected(IPEndPoint address) 90 | { 91 | await _server.Send($"Hello {address}!", address); 92 | } 93 | } 94 | } -------------------------------------------------------------------------------- /Images/Icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrousavy/GenericProtocol/b94290a4b6fa21968d4cfc443f6c7be328f6ea17/Images/Icon.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Marc Rousavy 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 all 13 | 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 THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | <T> 4 |
5 | Generic Protocol 6 |

7 | 8 |
⚡️ A fast TCP event based buffered server/client protocol for transferring data over the (inter)net in .NET 🌐
9 | 10 |

11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |

27 |

28 | Buy Me a Coffee at ko-fi.com 29 |

30 |

31 | 32 | ## Why? 33 | > Send whole objects over the net easier and faster 34 | 35 | 1. Send nearly **any** .NET `object` 36 | (See: [supported](https://github.com/neuecc/ZeroFormatter#built-in-support-types), [custom](https://github.com/neuecc/ZeroFormatter#quick-start)) :package: 37 | 2. Send/Receive **faster** by **buffered send/receive** and **ZeroFormatter**'s **fast (de-)serializing** :dash: 38 | 3. Automatically **correct errors** with **TCP** and **Auto-reconnect** :white_check_mark: 39 | 4. **Async** and **Event** based :zap: 40 | 5. **Efficient Network Discovery** for other **GenericProtocol Hosts** :mag: 41 | 6. **Fast binary links** for file/images/.. transfer :floppy_disk: 42 | 7. Made with love :heart: 43 | 44 | Sending objects: 45 | ```csharp 46 | await client.Send(someObject); 47 | ``` 48 | 49 | ...on the other end: 50 | ```csharp 51 | private void MyMessageReceivedCallback(SomeObject someObject) { 52 | Console.WriteLine("I've received an object!"); 53 | } 54 | ``` 55 | 56 | ## How? 57 | Add **GenericProtocol** to your existing **.NET**/**.NET Core 2.0+**/**.NET Standard 2.0+** Project via **NuGet**: 58 | ``` 59 | PM> Install-Package GenericProtocol 60 | ``` 61 | 62 | Use the default namespace: 63 | ```csharp 64 | using GenericProtocol; 65 | ``` 66 | 67 | Are you [connecting to a server](#client), or **are you** [the server](#server)? 68 | 69 | 70 | ## Client 71 | ### Connect to a [server](#server): 72 | ```csharp 73 | IClient client = await Factory.StartNewClient("82.205.121.132", 1024, true); 74 | ``` 75 | The Factory will **construct and connect** a new `IClient` object, where `` is the object 76 | you want to **send over the net** (Here: `MessageObject`). This can be ([supported](https://github.com/neuecc/ZeroFormatter#built-in-support-types)) 77 | **built in types** (`string`, `IEnumerable`, ..) or **custom types** marked with `[ZeroFormattable]` (see [here](https://github.com/neuecc/ZeroFormatter#quick-start)) 78 | 79 | ### Send/Receive custom objects: 80 | ```csharp 81 | // MessageObject.cs 82 | [ZeroFormattable] 83 | public struct MessageObject { 84 | [Index(0)] 85 | public string Sender { get; set; } 86 | [Index(1)] 87 | public string Recipient { get; set; } 88 | [Index(2)] 89 | public string Message { get; set; } 90 | [Index(3)] 91 | public DateTime Timestamp { get; set; } 92 | } 93 | 94 | // Main.cs 95 | IClient client = await Factory.StartNewClient("82.205.121.132", 1024); 96 | // MyMessageReceivedCallback will be called whenever this client receives a message 97 | client.ReceivedMessage += MyMessageReceivedCallback; // void MyCallback(IPEndPoint, MessageObject) 98 | 99 | var msgObject = new MessageObject() { 100 | Sender = "mrousavy", 101 | Recipient = "cbarosch", 102 | Message = "Hi server!", 103 | Timestamp = DateTime.Now 104 | } 105 | await client.Send(msgObject); 106 | // (Optionally configure your Server so that it should redirect to the Recipient) 107 | client.Dispose(); 108 | ``` 109 | 110 | ### Send large binary content 111 | ```csharp 112 | IClient client = await Factory.StartNewBinaryDownlink("82.205.121.132", 1024, true); 113 | client.Send(bytes); // bytes can be a large file for example 114 | client.Dispose(); 115 | ``` 116 | Use `BinaryDownlinks`/`BinaryUplinks` when you just want to **send binary content** (Files, Images, ..). The binary links will skip the serialization and **send buffered right away**. 117 | 118 | ### Other 119 | ```csharp 120 | // Automatically try to reconnect on disconnects 121 | client.AutoReconnect = true; 122 | // Set the reading buffer size for incoming data 123 | client.ReceiveBufferSize = 2048; 124 | // Set the writing buffer size for outgoing data 125 | client.SendBufferSize = 2048; 126 | // Get the current Connection status 127 | var status = client.ConnectionStatus; 128 | // Connection to server lost handler 129 | client.ConnectionLost += ...; 130 | ``` 131 | 132 | ## Server 133 | ### Start a new server: 134 | ```csharp 135 | IServer server = await Factory.StartNewServer(IPAddress.Any, 1024, true); 136 | ``` 137 | 138 | ### Send/Receive your objects (`MessageObject` in this example): 139 | ```csharp 140 | // Attach to the Message Received event 141 | server.ReceivedMessage += MyMessageReceivedCallback; // void MyCallback(IPEndPoint, MessageObject) 142 | 143 | var msgObject = new MessageObject() { 144 | Sender = "server", 145 | Recipient = "mrousavy", 146 | Message = "Hello client!", 147 | Timestamp = DateTime.Now 148 | } 149 | var clientEndPoint = server.Clients.First(); // Get first client in connected-clients enumerable 150 | await server.Send(msgObject, clientEndPoint); // Send object to given client 151 | ``` 152 | 153 | ### Other 154 | ```csharp 155 | // Event once a client connects 156 | server.ClientConnected += ...; // void ClientConnectedCallback(IPEndPoint) 157 | // Event once a client disconnects 158 | server.ClientDisconnected += ...; // void ClientDisconnectedCallback(IPEndPoint) 159 | // Set the reading buffer size for incoming data 160 | server.ReceiveBufferSize = 2048; 161 | // Set the writing buffer size for outgoing data 162 | server.SendBufferSize = 2048; 163 | // Set the count of maximum clients to queue on simultanious connection attempts 164 | server.MaxConnectionsBacklog = 8; 165 | ``` 166 | 167 | > License: [MIT](https://github.com/mrousavy/GenericProtocol/blob/master/LICENSE) | [Contributing](https://github.com/mrousavy/GenericProtocol/blob/master/CONTRIBUTING.md) | Thanks! 168 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | version: 1.0.{build} 2 | skip_non_tags: true 3 | image: Visual Studio 2017 4 | configuration: Release 5 | dotnet_csproj: 6 | patch: true 7 | file: 'GenericProtocol\*.csproj' 8 | version: '{version}' 9 | package_version: '{version}' 10 | cache: 11 | - packages -> **\packages.config 12 | 13 | before_build: 14 | - cmd: >- 15 | dotnet restore 16 | 17 | nuget restore 18 | build: 19 | verbosity: minimal 20 | after_build: 21 | - cmd: >- 22 | dotnet pack GenericProtocol\GenericProtocol.csproj 23 | artifacts: 24 | - path: GenericProtocol\bin\$(configuration)\*.nupkg 25 | name: NupkgArtifact 26 | deploy: 27 | provider: NuGet 28 | api_key: 29 | secure: GbnKcTtDdY0RbYxlclr1ad4oL0qmge9VN9bkiA8r8PWx5ElCPfKo5m/6cR79cTgG 30 | skip_symbols: true 31 | artifact: /.*\.nupkg/ 32 | --------------------------------------------------------------------------------