├── .gitignore ├── Extensions └── Netcode.cs ├── License ├── Program.cs ├── Readme.md ├── Realtime Networking Server.csproj ├── Realtime Networking Server.sln ├── Scripts ├── Client.cs ├── Data.cs ├── Database.cs ├── Email.cs ├── Manager.cs ├── Packet.cs ├── Receiver.cs ├── Retry.cs ├── Sender.cs ├── Server.cs ├── Sqlite.cs ├── Threading.cs └── Tools.cs ├── Terminal.cs └── app.manifest /.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/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | -------------------------------------------------------------------------------- /Extensions/Netcode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.IO; 5 | using System.Threading.Tasks; 6 | 7 | namespace DevelopersHub.RealtimeNetworking.Server 8 | { 9 | class Netcode 10 | { 11 | 12 | #region Internal 13 | 14 | private static int process_check_period = 60; 15 | private static DateTime laast_process_check; 16 | 17 | public static void Start() 18 | { 19 | string tempPath = Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar) + string.Format("{0}RealtimeNetworking{0}Extentions{0}Netcode", Path.DirectorySeparatorChar); 20 | string resultPath = string.Format("{0}Result{1}", tempPath, Path.DirectorySeparatorChar); 21 | string loadPath = string.Format("{0}Load{1}", tempPath, Path.DirectorySeparatorChar); 22 | string readyPath = string.Format("{0}Ready{1}", tempPath, Path.DirectorySeparatorChar); 23 | if (Directory.Exists(resultPath)) 24 | { 25 | Directory.Delete(resultPath, true); 26 | } 27 | if (Directory.Exists(loadPath)) 28 | { 29 | Directory.Delete(loadPath, true); 30 | } 31 | if (Directory.Exists(readyPath)) 32 | { 33 | Directory.Delete(readyPath, true); 34 | } 35 | laast_process_check = DateTime.Now; 36 | } 37 | 38 | public static void OnExit() 39 | { 40 | for (int i = 0; i < games.Count; i++) 41 | { 42 | KillGameProcess(i); 43 | } 44 | } 45 | 46 | public static void Update() 47 | { 48 | if (!updating) 49 | { 50 | updating = true; 51 | _Update(); 52 | } 53 | } 54 | 55 | private static bool updating = false; 56 | private static List games = new List(); 57 | 58 | private class Game 59 | { 60 | public string id = string.Empty; 61 | public Data.Game game = null; 62 | public Process process = null; 63 | public DateTime start; 64 | public Data.RuntimeGame runtime = null; 65 | public int port = 7777; 66 | } 67 | 68 | private static string tempPath 69 | { 70 | get 71 | { 72 | return Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar) + string.Format("{0}RealtimeNetworking{0}Extentions{0}Netcode", Path.DirectorySeparatorChar); 73 | } 74 | } 75 | 76 | private static void _Update() 77 | { 78 | Task task = Task.Run(() => 79 | { 80 | string path = string.Format("{0}Ready{1}", tempPath, Path.DirectorySeparatorChar); 81 | if(Directory.Exists(path)) 82 | { 83 | string[] files = Directory.GetFiles(path); 84 | if (files != null && files.Length > 0) 85 | { 86 | foreach (string file in files) 87 | { 88 | if (Path.GetExtension(file).ToLower() == ".txt") 89 | { 90 | try 91 | { 92 | string id = Path.GetFileNameWithoutExtension(file); 93 | int port = 7777; 94 | using (var reader = new StreamReader(file)) 95 | { 96 | port = int.Parse(reader.ReadLine().Trim()); 97 | } 98 | File.Delete(file); 99 | ServerIsReady(id, port); 100 | } 101 | catch (Exception) 102 | { 103 | 104 | } 105 | } 106 | } 107 | } 108 | } 109 | path = string.Format("{0}Result{1}", tempPath, Path.DirectorySeparatorChar); 110 | if (Directory.Exists(path)) 111 | { 112 | string[] files = Directory.GetFiles(path); 113 | if (files != null && files.Length > 0) 114 | { 115 | foreach (string file in files) 116 | { 117 | if (Path.GetExtension(file).ToLower() == ".txt") 118 | { 119 | try 120 | { 121 | string serializedData = File.ReadAllText(file); 122 | File.Delete(file); 123 | Data.RuntimeResult result = Tools.Desrialize(Tools.DecompressString(serializedData)); 124 | Terminal.OnNetcodeGameResultReceived(result); 125 | } 126 | catch (Exception) 127 | { 128 | 129 | } 130 | } 131 | } 132 | } 133 | } 134 | path = string.Format("{0}Close{1}", tempPath, Path.DirectorySeparatorChar); 135 | if (Directory.Exists(path)) 136 | { 137 | string[] files = Directory.GetFiles(path); 138 | if (files != null && files.Length > 0) 139 | { 140 | foreach (string file in files) 141 | { 142 | if (Path.GetExtension(file).ToLower() == ".txt") 143 | { 144 | try 145 | { 146 | string id = File.ReadAllText(file).Trim(); 147 | File.Delete(file); 148 | for (int i = 0; i < games.Count; i++) 149 | { 150 | if (games[i] != null && games[i].id == id) 151 | { 152 | KillGameProcess(i); 153 | } 154 | } 155 | } 156 | catch (Exception) 157 | { 158 | 159 | } 160 | } 161 | } 162 | } 163 | } 164 | if(Terminal.netcode_max_server_life_seconds > 0) 165 | { 166 | double process_check_seconds = (DateTime.Now - laast_process_check).TotalSeconds; 167 | if (process_check_seconds >= process_check_period) 168 | { 169 | laast_process_check = DateTime.Now; 170 | for (int i = 0; i < games.Count; i++) 171 | { 172 | if (games[i] != null && (DateTime.Now - games[i].start).TotalSeconds >= Terminal.netcode_max_server_life_seconds) 173 | { 174 | KillGameProcess(i); 175 | } 176 | } 177 | } 178 | } 179 | updating = false; 180 | }); 181 | } 182 | 183 | private static void KillGameProcess(int index) 184 | { 185 | if (games[index] != null && games[index].process != null) 186 | { 187 | var process = games[index].process; 188 | process.Kill(); 189 | process.WaitForExit(); 190 | process.Dispose(); 191 | } 192 | } 193 | 194 | private static void ServerIsReady(string id, int port) 195 | { 196 | Console.WriteLine("Netcode server is ready." + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); 197 | for (int g = 0; g < games.Count; g++) 198 | { 199 | if (games[g].id == id) 200 | { 201 | games[g].port = port; 202 | for (int i = games[g].game.room.players.Count - 1; i >= 0; i--) 203 | { 204 | if (Server.clients.ContainsKey(games[g].game.room.players[i].client) && Server.clients[games[g].game.room.players[i].client].accountID == games[g].game.room.players[i].id) 205 | { 206 | byte[] serializedData = Tools.Compress(Tools.Serialize(games[g].runtime)); 207 | Packet packet = new Packet(); 208 | packet.Write((int)Manager.InternalID.NETCODE_STARTED); 209 | packet.Write(port); 210 | packet.Write(serializedData.Length); 211 | packet.Write(serializedData); 212 | Manager.SendTCPData(games[g].game.room.players[i].client, packet); 213 | } 214 | else 215 | { 216 | games[g].game.room.players.RemoveAt(i); 217 | } 218 | } 219 | break; 220 | } 221 | } 222 | } 223 | 224 | private static void ServerExited(Game game) 225 | { 226 | Console.WriteLine("Netcode server closed." + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); 227 | } 228 | 229 | public static void StartGame(Data.Game game) 230 | { 231 | Task task = Task.Run(() => 232 | { 233 | for (int i = game.room.players.Count - 1; i >= 0; i--) 234 | { 235 | if (Server.clients.ContainsKey(game.room.players[i].client) && Server.clients[game.room.players[i].client].accountID == game.room.players[i].id) 236 | { 237 | Packet packet = new Packet(); 238 | packet.Write((int)Manager.InternalID.NETCODE_INIT); 239 | Manager.SendTCPData(game.room.players[i].client, packet); 240 | } 241 | else 242 | { 243 | game.room.players.RemoveAt(i); 244 | } 245 | } 246 | if (game.room.players.Count > 0) 247 | { 248 | if (File.Exists(Terminal.netcode_server_executable_path)) 249 | { 250 | try 251 | { 252 | Game netcodeGame = new Game(); 253 | netcodeGame.id = Guid.NewGuid().ToString().Trim(); 254 | netcodeGame.game = game; 255 | string path = string.Format("{0}Load{1}", tempPath, Path.DirectorySeparatorChar); 256 | if (!Directory.Exists(path)) 257 | { 258 | Directory.CreateDirectory(path); 259 | } 260 | string filePath = path + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss-fff") + ".txt"; 261 | if (File.Exists(filePath)) 262 | { 263 | File.Delete(filePath); 264 | } 265 | Data.RuntimeGame data = _GetRuntimeGame(netcodeGame.game); 266 | data.id = netcodeGame.id; 267 | string serializedData = Tools.CompressString(Tools.Serialize(data)); 268 | File.WriteAllText(filePath, serializedData); 269 | netcodeGame.process = new Process(); 270 | netcodeGame.process.StartInfo.FileName = Terminal.netcode_server_executable_path; 271 | netcodeGame.process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized; 272 | netcodeGame.process.StartInfo.CreateNoWindow = true; 273 | netcodeGame.process.StartInfo.UseShellExecute = false; 274 | netcodeGame.process.EnableRaisingEvents = true; 275 | netcodeGame.process.StartInfo.ArgumentList.Add(netcodeGame.id); 276 | netcodeGame.process.Exited += new EventHandler(ProcessExited); 277 | netcodeGame.start = DateTime.Now; 278 | netcodeGame.runtime = data; 279 | games.Add(netcodeGame); 280 | netcodeGame.process.Start(); 281 | Console.WriteLine("Netcode server started. " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); 282 | } 283 | catch (Exception ex) 284 | { 285 | Console.WriteLine(ex.Message); 286 | } 287 | } 288 | else 289 | { 290 | Console.WriteLine("Server executable is missing."); 291 | } 292 | } 293 | }); 294 | } 295 | 296 | private static Data.RuntimeGame _GetRuntimeGame(Data.Game game) 297 | { 298 | Data.RuntimeGame data = new Data.RuntimeGame(); 299 | data.mapID = game.room.mapID; 300 | data.gameID = game.room.gameID; 301 | using (var connection = Sqlite.connection) 302 | { 303 | connection.Open(); 304 | for (int i = 0; i < game.room.players.Count; i++) 305 | { 306 | Data.RuntimePlayer player = new Data.RuntimePlayer(); 307 | player.id = game.room.players[i].id; 308 | player.username = game.room.players[i].username; 309 | player.team = game.room.players[i].team; 310 | player.characters = Manager.GetRuntimeCharacters(player.id, true, true, connection); 311 | data.players.Add(player); 312 | } 313 | Terminal.OverrideGameInitialData(ref data, connection); 314 | connection.Close(); 315 | } 316 | return data; 317 | } 318 | 319 | private static void ProcessExited(object sender, EventArgs e) 320 | { 321 | Process process = (Process)sender; 322 | if(process.StartInfo.ArgumentList.Count > 0) 323 | { 324 | string id = process.StartInfo.ArgumentList[0]; 325 | for (int i = 0; i < games.Count; i++) 326 | { 327 | if (games[i].id == id) 328 | { 329 | ServerExited(games[i]); 330 | games.RemoveAt(i); 331 | break; 332 | } 333 | } 334 | } 335 | } 336 | 337 | #endregion 338 | 339 | } 340 | } -------------------------------------------------------------------------------- /License: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Developers Hub 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 | -------------------------------------------------------------------------------- /Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | 4 | namespace DevelopersHub.RealtimeNetworking.Server 5 | { 6 | class Program 7 | { 8 | 9 | private static bool isRunning = false; 10 | private const float updatePeriod = 1000f / Terminal.updates_per_second; 11 | 12 | static void Main(string[] args) 13 | { 14 | AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnExit); 15 | if (Manager.enabled) 16 | { 17 | Manager.Initialize(); 18 | } 19 | AppDomain.CurrentDomain.UnhandledException += GlobalUnhandledExceptionHandler; 20 | try 21 | { 22 | Console.Title = "Server Console"; 23 | isRunning = true; 24 | Thread mainThread = new Thread(new ThreadStart(MainThread)); 25 | mainThread.Start(); 26 | Server.Start(Terminal.max_players, Terminal.port); 27 | } 28 | catch (Exception ex) 29 | { 30 | Tools.LogError(ex.Message, ex.StackTrace); 31 | } 32 | } 33 | 34 | private static void MainThread() 35 | { 36 | DateTime nextLoop = DateTime.Now; 37 | while (isRunning) 38 | { 39 | while (nextLoop < DateTime.Now) 40 | { 41 | Terminal.Update(); 42 | if (Manager.enabled) 43 | { 44 | Manager.Update(); 45 | } 46 | Threading.UpdateMain(); 47 | nextLoop = nextLoop.AddMilliseconds(updatePeriod); 48 | if (nextLoop > DateTime.Now) 49 | { 50 | Thread.Sleep((int)Math.Clamp((nextLoop - DateTime.Now).TotalMilliseconds, 0, Int32.MaxValue)); 51 | } 52 | } 53 | } 54 | } 55 | 56 | private static void GlobalUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e) 57 | { 58 | Exception ex = default(Exception); 59 | ex = (Exception)e.ExceptionObject; 60 | Tools.LogError(ex.Message, ex.StackTrace, "Unhandled"); 61 | } 62 | 63 | private static void OnExit(object sender, EventArgs e) 64 | { 65 | if (Manager.enabled) 66 | { 67 | Manager.OnExit(); 68 | } 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Unity Realtime Networking Server 2 | This is a console application that can be used as server for Unity clients. 3 | -------------------------------------------------------------------------------- /Realtime Networking Server.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net7.0 6 | DevelopersHub.RealtimeNetworking.Server 7 | app.manifest 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Realtime Networking Server.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31727.386 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Realtime Networking Server", "Realtime Networking Server.csproj", "{DE59CF5B-8A0B-4C7E-9BF9-AB1266BC9D6A}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {DE59CF5B-8A0B-4C7E-9BF9-AB1266BC9D6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {DE59CF5B-8A0B-4C7E-9BF9-AB1266BC9D6A}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {DE59CF5B-8A0B-4C7E-9BF9-AB1266BC9D6A}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {DE59CF5B-8A0B-4C7E-9BF9-AB1266BC9D6A}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {888766DA-9FC0-4109-83B9-B535CDB51FDC} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Scripts/Client.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Sockets; 4 | 5 | namespace DevelopersHub.RealtimeNetworking.Server 6 | { 7 | class Client 8 | { 9 | 10 | public static int dataBufferSize = 4096; 11 | public int id; 12 | public TCP tcp; 13 | public UDP udp; 14 | public string sendToken = "xxxxx"; 15 | public string receiveToken = "xxxxx"; 16 | public long accountID = -1; 17 | public bool disconnecting = false; 18 | public string ipAddress = "000.0.0.000"; 19 | public Data.Room room = null; 20 | public Data.Player player = null; 21 | public Data.Party party = null; 22 | public Data.Game game = null; 23 | public DateTime lastTick = DateTime.Now; 24 | 25 | public Client(int _clientId) 26 | { 27 | id = _clientId; 28 | tcp = new TCP(id); 29 | udp = new UDP(id); 30 | } 31 | 32 | public class TCP 33 | { 34 | public TcpClient socket; 35 | private readonly int id; 36 | private NetworkStream stream; 37 | private Packet receivedData; 38 | private byte[] receiveBuffer; 39 | 40 | public TCP(int _id) 41 | { 42 | id = _id; 43 | } 44 | 45 | public void Initialize(TcpClient _socket) 46 | { 47 | socket = _socket; 48 | socket.ReceiveBufferSize = dataBufferSize; 49 | socket.SendBufferSize = dataBufferSize; 50 | stream = socket.GetStream(); 51 | receivedData = new Packet(); 52 | receiveBuffer = new byte[dataBufferSize]; 53 | stream.BeginRead(receiveBuffer, 0, dataBufferSize, IncomingData, null); 54 | using (Packet packet = new Packet((int)Packet.ID.INITIALIZATION)) 55 | { 56 | Server.clients[id].sendToken = Tools.GenerateToken(); 57 | packet.Write(id); 58 | packet.Write(Server.clients[id].sendToken); 59 | packet.WriteLength(); 60 | Server.clients[id].tcp.SendData(packet); 61 | } 62 | } 63 | 64 | public void SendData(Packet _packet) 65 | { 66 | try 67 | { 68 | if (socket != null) 69 | { 70 | stream.BeginWrite(_packet.ToArray(), 0, _packet.Length(), null, null); 71 | } 72 | } 73 | catch (Exception ex) 74 | { 75 | Tools.LogError(ex.Message, ex.StackTrace); 76 | } 77 | } 78 | 79 | private void IncomingData(IAsyncResult result) 80 | { 81 | try 82 | { 83 | int length = stream.EndRead(result); 84 | if (length <= 0) 85 | { 86 | Server.clients[id].Disconnect(); 87 | return; 88 | } 89 | byte[] data = new byte[length]; 90 | Array.Copy(receiveBuffer, data, length); 91 | receivedData.Reset(CheckData(data)); 92 | stream.BeginRead(receiveBuffer, 0, dataBufferSize, IncomingData, null); 93 | } 94 | catch (Exception ex) 95 | { 96 | Tools.LogError(ex.Message, ex.StackTrace); 97 | Server.clients[id].Disconnect(); 98 | } 99 | } 100 | 101 | private bool CheckData(byte[] _data) 102 | { 103 | int length = 0; 104 | receivedData.SetBytes(_data); 105 | if (receivedData.UnreadLength() >= 4) 106 | { 107 | length = receivedData.ReadInt(); 108 | if (length <= 0) 109 | { 110 | return true; 111 | } 112 | } 113 | while (length > 0 && length <= receivedData.UnreadLength()) 114 | { 115 | byte[] _packetBytes = receivedData.ReadBytes(length); 116 | Threading.ExecuteOnMainThread(() => 117 | { 118 | try 119 | { 120 | using (Packet _packet = new Packet(_packetBytes)) 121 | { 122 | int _packetId = _packet.ReadInt(); 123 | Server.packetHandlers[_packetId](id, _packet); 124 | } 125 | } 126 | catch (Exception ex) 127 | { 128 | Tools.LogError(ex.Message, ex.StackTrace); 129 | } 130 | }); 131 | length = 0; 132 | if (receivedData.UnreadLength() >= 4) 133 | { 134 | length = receivedData.ReadInt(); 135 | if (length <= 0) 136 | { 137 | return true; 138 | } 139 | } 140 | } 141 | if (length <= 1) 142 | { 143 | return true; 144 | } 145 | return false; 146 | } 147 | 148 | public void Disconnect() 149 | { 150 | socket.Close(); 151 | stream = null; 152 | receivedData = null; 153 | receiveBuffer = null; 154 | socket = null; 155 | } 156 | } 157 | 158 | public class UDP 159 | { 160 | public IPEndPoint endPoint; 161 | private int id; 162 | 163 | public UDP(int _id) 164 | { 165 | id = _id; 166 | } 167 | 168 | public void Connect(IPEndPoint _endPoint) 169 | { 170 | endPoint = _endPoint; 171 | } 172 | 173 | public void SendData(Packet _packet) 174 | { 175 | Server.SendDataUDP(endPoint, _packet); 176 | } 177 | 178 | public void CheckData(Packet _packetData) 179 | { 180 | int _packetLength = _packetData.ReadInt(); 181 | byte[] _packetBytes = _packetData.ReadBytes(_packetLength); 182 | Threading.ExecuteOnMainThread(() => 183 | { 184 | try 185 | { 186 | using (Packet _packet = new Packet(_packetBytes)) 187 | { 188 | int _packetId = _packet.ReadInt(); 189 | Server.packetHandlers[_packetId](id, _packet); 190 | } 191 | } 192 | catch (Exception ex) 193 | { 194 | Tools.LogError(ex.Message, ex.StackTrace); 195 | } 196 | }); 197 | } 198 | 199 | public void Disconnect() 200 | { 201 | endPoint = null; 202 | } 203 | } 204 | 205 | private void Disconnect() 206 | { 207 | if (tcp.socket != null) 208 | { 209 | Console.WriteLine("Client with IP {0} has been disconnected.", tcp.socket.Client.RemoteEndPoint); 210 | IPEndPoint ip = tcp.socket.Client.RemoteEndPoint as IPEndPoint; 211 | Terminal.ClientDisconnected(id, ip.Address.ToString()); 212 | if (Manager.enabled) 213 | { 214 | Manager.OnClientDisconnected(id, ip.Address.ToString()); 215 | } 216 | tcp.Disconnect(); 217 | } 218 | else 219 | { 220 | Console.WriteLine("Client with unkown IP has been disconnected."); 221 | Terminal.ClientDisconnected(id, "unknown"); 222 | if (Manager.enabled) 223 | { 224 | Manager.OnClientDisconnected(id, "unknown"); 225 | } 226 | } 227 | if (udp.endPoint != null) 228 | { 229 | udp.Disconnect(); 230 | } 231 | } 232 | 233 | } 234 | } -------------------------------------------------------------------------------- /Scripts/Data.cs: -------------------------------------------------------------------------------- 1 | namespace DevelopersHub.RealtimeNetworking.Server 2 | { 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | public class Data 7 | { 8 | 9 | public class Player 10 | { 11 | public long id = 0; 12 | public string username = string.Empty; 13 | public bool online = false; 14 | public int client = 0; 15 | public bool ready = false; 16 | public int team = 0; 17 | public int scene = -1; 18 | } 19 | 20 | public class PlayerProfile 21 | { 22 | public long id = 0; 23 | public string username = string.Empty; 24 | public int coins = 0; 25 | public int score = 0; 26 | public int level = 1; 27 | public int xp = 0; 28 | public bool online = false; 29 | public DateTime login; 30 | } 31 | 32 | public class Party 33 | { 34 | public string id = string.Empty; 35 | public bool auto = false; 36 | public int gameID = 0; 37 | public int mapID = 0; 38 | public long leaderID = 0; 39 | public int maxPlayers = 100; 40 | public Extension extension = Extension.NONE; 41 | public bool matchmaking = false; 42 | public int teamsPerMatch = 2; 43 | public int playersPerTeam = 6; 44 | public List players = new List(); 45 | public HashSet invites = new HashSet(); 46 | } 47 | 48 | public class FriendRequest 49 | { 50 | public long id = 0; 51 | public long playerID = 0; 52 | public string username = string.Empty; 53 | public bool online = false; 54 | public DateTime time; 55 | } 56 | 57 | public class Room 58 | { 59 | public string id = string.Empty; 60 | public int gameID = 0; 61 | public int mapID = 0; 62 | public long hostID = 0; 63 | public string hostUsername = string.Empty; 64 | public string password = string.Empty; 65 | public int maxPlayers = 0; 66 | public List players = new List(); 67 | } 68 | 69 | public class Friend 70 | { 71 | public long id = 0; 72 | public string username = string.Empty; 73 | public bool online = false; 74 | } 75 | 76 | public enum GameType 77 | { 78 | HOSTED = 1, MATCHED = 2 79 | } 80 | 81 | public class Game 82 | { 83 | public Room room = null; 84 | public DateTime start; 85 | public GameType type = GameType.HOSTED; 86 | public Extension extension = Extension.NONE; 87 | public GameCustomData customData = new GameCustomData(); 88 | public List sceneHostsKeys = new List(); 89 | public List sceneHostsValues = new List(); 90 | } 91 | 92 | public class GameCustomData 93 | { 94 | 95 | } 96 | 97 | public enum Extension 98 | { 99 | NONE = 0, NETCODE_SERVER = 1 100 | } 101 | 102 | public class RuntimeEquipment 103 | { 104 | public long id = 0; 105 | public long characterID = 0; 106 | public int prefabID = 0; 107 | public int type = 0; 108 | public string name = string.Empty; 109 | public string customName = string.Empty; 110 | public string tag = string.Empty; 111 | public int level = 1; 112 | public double armor = 0; 113 | public double damage = 0; 114 | public double accuracy = 0; 115 | public double range = 0; 116 | public double speed = 0; 117 | public double weight = 0; 118 | public int capacity = 0; 119 | } 120 | 121 | public class RuntimeCharacter 122 | { 123 | public long id = 0; 124 | public int prefabID = 0; 125 | public string name = string.Empty; 126 | public string customName = string.Empty; 127 | public string tag = string.Empty; 128 | public bool selected = false; 129 | public int xp = 0; 130 | public int level = 1; 131 | public double health = 100; 132 | public double damage = 0; 133 | public double speed = 0; 134 | public int strength = 0; 135 | public int agility = 0; 136 | public int constitution = 0; 137 | public int dexterity = 0; 138 | public int vitality = 0; 139 | public int endurance = 0; 140 | public int intelligence = 0; 141 | public int wisdom = 0; 142 | public int charisma = 0; 143 | public int perception = 0; 144 | public int luck = 0; 145 | public int willpower = 0; 146 | public List equipments = new List(); 147 | } 148 | 149 | public class RuntimePlayer 150 | { 151 | public long id = 0; 152 | public string username = string.Empty; 153 | public int team = 0; 154 | public List characters = new List(); 155 | } 156 | 157 | public class RuntimeGame 158 | { 159 | public string id = string.Empty; 160 | public int gameID = 0; 161 | public int mapID = 0; 162 | public List players = new List(); 163 | } 164 | 165 | public class RuntimeResult 166 | { 167 | public double duration = 0; 168 | public RuntimeGame game = null; 169 | } 170 | 171 | public class Color 172 | { 173 | public float r; 174 | public float g; 175 | public float b; 176 | public float a; 177 | } 178 | 179 | public enum PurchaseResult 180 | { 181 | Unknown = 0, Successful = 1, InsufficientFunds = 2, NotAvailable = 3 182 | } 183 | 184 | } 185 | } -------------------------------------------------------------------------------- /Scripts/Database.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DevelopersHub.RealtimeNetworking.Server 4 | { 5 | class Database 6 | { 7 | 8 | #region MySQL 9 | /* 10 | private static MySqlConnection _mysqlConnection; 11 | private const string _mysqlServer = "127.0.0.1"; 12 | private const string _mysqlUsername = "root"; 13 | private const string _mysqlPassword = ""; 14 | private const string _mysqlDatabase = "database"; 15 | 16 | public static MySqlConnection mysqlConnection 17 | { 18 | get 19 | { 20 | if (_mysqlConnection == null || _mysqlConnection.State == ConnectionState.Closed) 21 | { 22 | try 23 | { 24 | _mysqlConnection = new MySqlConnection("SERVER=" + _mysqlServer + "; DATABASE=" + _mysqlDatabase + "; UID=" + _mysqlUsername + "; PASSWORD=" + _mysqlPassword + ";"); 25 | _mysqlConnection.Open(); 26 | Console.WriteLine("Connection established with MySQL database."); 27 | } 28 | catch (Exception) 29 | { 30 | Console.WriteLine("Failed to connect the MySQL database."); 31 | } 32 | } 33 | else if (_mysqlConnection.State == ConnectionState.Broken) 34 | { 35 | try 36 | { 37 | _mysqlConnection.Close(); 38 | _mysqlConnection = new MySqlConnection("SERVER=" + _mysqlServer + "; DATABASE=" + _mysqlDatabase + "; UID=" + _mysqlUsername + "; PASSWORD=" + _mysqlPassword + ";"); 39 | _mysqlConnection.Open(); 40 | Console.WriteLine("Connection re-established with MySQL database."); 41 | } 42 | catch (Exception) 43 | { 44 | Console.WriteLine("Failed to connect the MySQL database."); 45 | } 46 | } 47 | return _mysqlConnection; 48 | } 49 | } 50 | 51 | public static void Demo_MySQL_1() 52 | { 53 | string query = String.Format("UPDATE table SET int_column = {0}, string_column = '{1}', datetime_column = NOW();", 123, "Hello World"); 54 | using (MySqlCommand command = new MySqlCommand(query, mysqlConnection)) 55 | { 56 | command.ExecuteNonQuery(); 57 | } 58 | } 59 | 60 | public static void Demo_MySQL_2() 61 | { 62 | string query = String.Format("SELECT column1, column2 FROM table WHERE column3 = {0} ORDER BY column1 DESC;", 123); 63 | using (MySqlCommand command = new MySqlCommand(query, mysqlConnection)) 64 | { 65 | using (MySqlDataReader reader = command.ExecuteReader()) 66 | { 67 | if (reader.HasRows) 68 | { 69 | while (reader.Read()) 70 | { 71 | int column1 = int.Parse(reader["column1"].ToString()); 72 | string column2 = reader["column2"].ToString(); 73 | } 74 | } 75 | } 76 | } 77 | } 78 | */ 79 | #endregion 80 | 81 | #region SQL 82 | /* 83 | private static SqlConnection _sqlConnection; 84 | private const string _sqlServer = "server"; 85 | private const string _sqlDatabase = "database"; 86 | 87 | public static SqlConnection sqlConnection 88 | { 89 | get 90 | { 91 | if (_sqlConnection == null || _sqlConnection.State == ConnectionState.Closed) 92 | { 93 | try 94 | { 95 | var connectionString = @"Server=localhost\" + _sqlServer + ";Database=" + _sqlDatabase + ";Initial Catalog=" + _sqlDatabase + ";Trusted_Connection=True;MultipleActiveResultSets=true"; 96 | _sqlConnection = new SqlConnection(connectionString); 97 | _sqlConnection.Open(); 98 | Console.WriteLine("Connection established with SQL database."); 99 | } 100 | catch (Exception) 101 | { 102 | Console.WriteLine("Failed to connect the SQL database."); 103 | } 104 | } 105 | else if (_sqlConnection.State == ConnectionState.Broken) 106 | { 107 | try 108 | { 109 | _sqlConnection.Close(); 110 | var connectionString = @"Server=localhost\" + _sqlServer + ";Database=" + _sqlDatabase + ";Initial Catalog=" + _sqlDatabase + ";Trusted_Connection=True;MultipleActiveResultSets=true"; 111 | _sqlConnection = new SqlConnection(connectionString); 112 | _sqlConnection.Open(); 113 | Console.WriteLine("Connection re-established with SQL database."); 114 | } 115 | catch (Exception) 116 | { 117 | Console.WriteLine("Failed to connect the SQL database."); 118 | } 119 | } 120 | return _sqlConnection; 121 | } 122 | } 123 | 124 | public static void Demo_SQL_1() 125 | { 126 | string query = String.Format("UPDATE database.table SET int_column = {0}, string_column = '{1}', datetime_column = GETUTCDATE();", 123, "Hello World"); 127 | using (SqlCommand command = new SqlCommand(query, sqlConnection)) 128 | { 129 | command.ExecuteNonQuery(); 130 | } 131 | } 132 | 133 | public static void Demo_SQL_2() 134 | { 135 | string query = String.Format("SELECT column1, column2 FROM database.table WHERE column3 = {0} ORDER BY column1 DESC;", 123); 136 | using (SqlCommand command = new SqlCommand(query, sqlConnection)) 137 | { 138 | using (SqlDataReader reader = command.ExecuteReader()) 139 | { 140 | if (reader.HasRows) 141 | { 142 | while (reader.Read()) 143 | { 144 | int column1 = int.Parse(reader["column1"].ToString()); 145 | string column2 = reader["column2"].ToString(); 146 | } 147 | } 148 | } 149 | } 150 | } 151 | */ 152 | #endregion 153 | 154 | #region Sqlite 155 | /* 156 | public static void Demo_Sqlite_1() 157 | { 158 | try 159 | { 160 | using (var connection = Sqlite.connection) 161 | { 162 | connection.Open(); 163 | var command = connection.CreateCommand(); 164 | command.CommandText = @" 165 | Update accounts 166 | SET age = 30 167 | WHERE id = $id 168 | "; 169 | command.Parameters.AddWithValue("$id", 123); 170 | command.ExecuteNonQuery(); 171 | connection.Close(); 172 | } 173 | } 174 | catch (Exception) 175 | { 176 | 177 | } 178 | } 179 | 180 | public static void Demo_Sqlite_2() 181 | { 182 | try 183 | { 184 | using (var connection = Sqlite.connection) 185 | { 186 | connection.Open(); 187 | var command = connection.CreateCommand(); 188 | command.CommandText = @" 189 | SELECT name 190 | FROM accounts 191 | WHERE id = $id 192 | "; 193 | command.Parameters.AddWithValue("$id", 123); 194 | using (var reader = command.ExecuteReader()) 195 | { 196 | while (reader.Read()) 197 | { 198 | var name = reader.GetString(0); 199 | Console.WriteLine($"Hello, {name}!"); 200 | } 201 | } 202 | connection.Close(); 203 | } 204 | } 205 | catch (Exception) 206 | { 207 | 208 | } 209 | } 210 | */ 211 | #endregion 212 | 213 | } 214 | } -------------------------------------------------------------------------------- /Scripts/Email.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Mail; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace DevelopersHub.RealtimeNetworking.Server.Scripts 8 | { 9 | public class Email 10 | { 11 | 12 | protected static readonly string host = "smtp.gmail.com"; 13 | protected static readonly int port = 587; 14 | protected static readonly string address = "demo@gmail.com"; 15 | protected static readonly string password = "password"; 16 | protected static readonly string name = "Developers Hub"; 17 | 18 | public static bool Send(string to, string subject, string mail) 19 | { 20 | MailMessage message = new MailMessage(new MailAddress(address, name), new MailAddress(to)); 21 | message.Subject = subject; 22 | message.IsBodyHtml = true; 23 | message.Body = mail; 24 | message.SubjectEncoding = Encoding.UTF8; 25 | message.BodyEncoding = Encoding.UTF8; 26 | try 27 | { 28 | using (var smtp = new SmtpClient(host, port)) 29 | { 30 | smtp.EnableSsl = true; 31 | smtp.DeliveryMethod = SmtpDeliveryMethod.Network; 32 | smtp.UseDefaultCredentials = false; 33 | smtp.Credentials = new NetworkCredential(address, password); 34 | smtp.Send(message); 35 | } 36 | return true; 37 | } 38 | catch (Exception ex) 39 | { 40 | Console.WriteLine(ex.Message); 41 | return false; 42 | } 43 | } 44 | 45 | public async static Task SendAsync(string to, string subject, string mail) 46 | { 47 | Task task = Task.Run(() => 48 | { 49 | return Send(to, subject, mail); 50 | }); 51 | return await task; 52 | } 53 | 54 | public static bool DemoSendEmailVerificationCode(string code, string email, int expiration) 55 | { 56 | string mail = email_verification_code_template; 57 | mail = mail.Replace("[company_logo_url]", "https://developershub.org/wp-content/uploads/2023/04/developershub_logo_black_512x512.png"); 58 | mail = mail.Replace("[company_name]", name); 59 | mail = mail.Replace("[user_name]", email); 60 | mail = mail.Replace("[email_description]", "You can use this code to recover your account. Enter this code in the game to load your progress."); 61 | mail = mail.Replace("[verification_code]", code); 62 | mail = mail.Replace("[remained_time]", expiration + " minutes"); 63 | mail = mail.Replace("[copyright_footer]", "© " + DateTime.UtcNow.Year.ToString() + " " + name + " , Torento, Canada"); 64 | return Send(email, "Verification Code", mail); 65 | } 66 | 67 | protected static readonly string email_verification_code_template = @" 68 | 69 | 70 | 71 | 72 | 73 |
74 |
75 |
76 | 77 | 78 | 79 | 82 | 83 | 84 | 150 | 151 | 152 | 155 | 156 | 157 |
80 | 81 |
85 | 86 | 87 | 88 | 90 | 144 | 146 | 147 | 148 |
89 | 91 |
92 | 93 |
94 |
95 | [company_name] 96 |
97 | 98 | 99 | 100 | 105 | 106 | 107 |
101 | 102 | [user_name] 103 | 104 |
108 |
109 |
110 |
111 | [email_description] 112 |
113 |
114 | [verification_code] 115 |
116 |
117 |
118 | 119 |
120 | This code will expire after [remained_time]. 121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 | 129 |
130 |
131 |
132 |
133 |
134 |
135 |
This email has been sent at your request, Please do not reply to it.
136 |
137 | [copyright_footer] 138 |
139 |
140 |
141 |
142 |
143 |
145 |
149 |
153 | 154 |
158 |
159 |
160 |
161 | 162 | "; 163 | 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /Scripts/Packet.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Numerics; 4 | using System.Text; 5 | 6 | namespace DevelopersHub.RealtimeNetworking.Server 7 | { 8 | public class Packet : IDisposable 9 | { 10 | public enum ID 11 | { 12 | INITIALIZATION = 1, CUSTOM = 2, INTERNAL = 3 13 | } 14 | 15 | private List buffer; 16 | private byte[] readableBuffer; 17 | private int readPos; 18 | 19 | public void SetID(int id) 20 | { 21 | buffer.InsertRange(0, BitConverter.GetBytes(id)); 22 | } 23 | 24 | /// Creates a new empty packet (without an ID). 25 | public Packet() 26 | { 27 | buffer = new List(); // Initialize buffer 28 | readPos = 0; // Set readPos to 0 29 | } 30 | 31 | /// Creates a new packet with a given ID. Used for sending. 32 | /// The packet ID. 33 | public Packet(int _id) 34 | { 35 | buffer = new List(); // Initialize buffer 36 | readPos = 0; // Set readPos to 0 37 | Write(_id); // Write packet id to the buffer 38 | } 39 | 40 | /// Creates a packet from which data can be read. Used for receiving. 41 | /// The bytes to add to the packet. 42 | public Packet(byte[] _data) 43 | { 44 | buffer = new List(); // Initialize buffer 45 | readPos = 0; // Set readPos to 0 46 | SetBytes(_data); 47 | } 48 | 49 | #region Functions 50 | /// Sets the packet's content and prepares it to be read. 51 | /// The bytes to add to the packet. 52 | public void SetBytes(byte[] _data) 53 | { 54 | Write(_data); 55 | readableBuffer = buffer.ToArray(); 56 | } 57 | 58 | /// Inserts the length of the packet's content at the start of the buffer. 59 | public void WriteLength() 60 | { 61 | buffer.InsertRange(0, BitConverter.GetBytes(buffer.Count)); // Insert the byte length of the packet at the very beginning 62 | } 63 | 64 | /// Inserts the given int at the start of the buffer. 65 | /// The int to insert. 66 | public void InsertInt(int _value) 67 | { 68 | buffer.InsertRange(0, BitConverter.GetBytes(_value)); // Insert the int at the start of the buffer 69 | } 70 | 71 | /// Gets the packet's content in array form. 72 | public byte[] ToArray() 73 | { 74 | readableBuffer = buffer.ToArray(); 75 | return readableBuffer; 76 | } 77 | 78 | /// Gets the length of the packet's content. 79 | public int Length() 80 | { 81 | return buffer.Count; // Return the length of buffer 82 | } 83 | 84 | /// Gets the length of the unread data contained in the packet. 85 | public int UnreadLength() 86 | { 87 | return Length() - readPos; // Return the remaining length (unread) 88 | } 89 | 90 | /// Resets the packet instance to allow it to be reused. 91 | /// Whether or not to reset the packet. 92 | public void Reset(bool _shouldReset = true) 93 | { 94 | if (_shouldReset) 95 | { 96 | buffer.Clear(); // Clear buffer 97 | readableBuffer = null; 98 | readPos = 0; // Reset readPos 99 | } 100 | else 101 | { 102 | readPos -= 4; // "Unread" the last read int 103 | } 104 | } 105 | #endregion 106 | 107 | #region Write Data 108 | /// Adds a byte to the packet. 109 | /// The byte to add. 110 | public void Write(byte _value) 111 | { 112 | buffer.Add(_value); 113 | } 114 | 115 | /// Adds an array of bytes to the packet. 116 | /// The byte array to add. 117 | public void Write(byte[] _value) 118 | { 119 | buffer.AddRange(_value); 120 | } 121 | 122 | /// Adds a short to the packet. 123 | /// The short to add. 124 | public void Write(short _value) 125 | { 126 | buffer.AddRange(BitConverter.GetBytes(_value)); 127 | } 128 | 129 | /// Adds an int to the packet. 130 | /// The int to add. 131 | public void Write(int _value) 132 | { 133 | buffer.AddRange(BitConverter.GetBytes(_value)); 134 | } 135 | 136 | /// Adds a long to the packet. 137 | /// The long to add. 138 | public void Write(long _value) 139 | { 140 | buffer.AddRange(BitConverter.GetBytes(_value)); 141 | } 142 | 143 | /// Adds a float to the packet. 144 | /// The float to add. 145 | public void Write(float _value) 146 | { 147 | buffer.AddRange(BitConverter.GetBytes(_value)); 148 | } 149 | 150 | /// Adds a double to the packet. 151 | /// The double to add. 152 | public void Write(double _value) 153 | { 154 | buffer.AddRange(BitConverter.GetBytes(_value)); 155 | } 156 | 157 | /// Adds a bool to the packet. 158 | /// The bool to add. 159 | public void Write(bool _value) 160 | { 161 | buffer.AddRange(BitConverter.GetBytes(_value)); 162 | } 163 | 164 | /// Adds a string to the packet. 165 | /// The string to add. 166 | public void Write(string _value) 167 | { 168 | Write(_value.Length); // Add the length of the string to the packet 169 | buffer.AddRange(Encoding.ASCII.GetBytes(_value)); // Add the string itself 170 | } 171 | 172 | /// Adds a Vector3 to the packet. 173 | /// The Vector3 to add. 174 | public void Write(Vector3 _value) 175 | { 176 | Write(_value.X); 177 | Write(_value.Y); 178 | Write(_value.Z); 179 | } 180 | 181 | /// Adds a Quaternion to the packet. 182 | /// The Quaternion to add. 183 | public void Write(Quaternion _value) 184 | { 185 | Write(_value.X); 186 | Write(_value.Y); 187 | Write(_value.Z); 188 | Write(_value.W); 189 | } 190 | #endregion 191 | 192 | #region Read Data 193 | /// Reads a byte from the packet. 194 | /// Whether or not to move the buffer's read position. 195 | public byte ReadByte(bool _moveReadPos = true) 196 | { 197 | if (buffer.Count > readPos) 198 | { 199 | // If there are unread bytes 200 | byte _value = readableBuffer[readPos]; // Get the byte at readPos' position 201 | if (_moveReadPos) 202 | { 203 | // If _moveReadPos is true 204 | readPos += 1; // Increase readPos by 1 205 | } 206 | return _value; // Return the byte 207 | } 208 | else 209 | { 210 | throw new Exception("Could not read value of type 'byte'!"); 211 | } 212 | } 213 | 214 | /// Reads an array of bytes from the packet. 215 | /// The length of the byte array. 216 | /// Whether or not to move the buffer's read position. 217 | public byte[] ReadBytes(int _length, bool _moveReadPos = true) 218 | { 219 | if (buffer.Count > readPos) 220 | { 221 | // If there are unread bytes 222 | byte[] _value = buffer.GetRange(readPos, _length).ToArray(); // Get the bytes at readPos' position with a range of _length 223 | if (_moveReadPos) 224 | { 225 | // If _moveReadPos is true 226 | readPos += _length; // Increase readPos by _length 227 | } 228 | return _value; // Return the bytes 229 | } 230 | else 231 | { 232 | throw new Exception("Could not read value of type 'byte[]'!"); 233 | } 234 | } 235 | 236 | /// Reads a short from the packet. 237 | /// Whether or not to move the buffer's read position. 238 | public short ReadShort(bool _moveReadPos = true) 239 | { 240 | if (buffer.Count > readPos) 241 | { 242 | // If there are unread bytes 243 | short _value = BitConverter.ToInt16(readableBuffer, readPos); // Convert the bytes to a short 244 | if (_moveReadPos) 245 | { 246 | // If _moveReadPos is true and there are unread bytes 247 | readPos += 2; // Increase readPos by 2 248 | } 249 | return _value; // Return the short 250 | } 251 | else 252 | { 253 | throw new Exception("Could not read value of type 'short'!"); 254 | } 255 | } 256 | 257 | /// Reads an int from the packet. 258 | /// Whether or not to move the buffer's read position. 259 | public int ReadInt(bool _moveReadPos = true) 260 | { 261 | if (buffer.Count > readPos) 262 | { 263 | // If there are unread bytes 264 | int _value = BitConverter.ToInt32(readableBuffer, readPos); // Convert the bytes to an int 265 | if (_moveReadPos) 266 | { 267 | // If _moveReadPos is true 268 | readPos += 4; // Increase readPos by 4 269 | } 270 | return _value; // Return the int 271 | } 272 | else 273 | { 274 | throw new Exception("Could not read value of type 'int'!"); 275 | } 276 | } 277 | 278 | /// Reads a long from the packet. 279 | /// Whether or not to move the buffer's read position. 280 | public long ReadLong(bool _moveReadPos = true) 281 | { 282 | if (buffer.Count > readPos) 283 | { 284 | // If there are unread bytes 285 | long _value = BitConverter.ToInt64(readableBuffer, readPos); // Convert the bytes to a long 286 | if (_moveReadPos) 287 | { 288 | // If _moveReadPos is true 289 | readPos += 8; // Increase readPos by 8 290 | } 291 | return _value; // Return the long 292 | } 293 | else 294 | { 295 | throw new Exception("Could not read value of type 'long'!"); 296 | } 297 | } 298 | 299 | /// Reads a float from the packet. 300 | /// Whether or not to move the buffer's read position. 301 | public float ReadFloat(bool _moveReadPos = true) 302 | { 303 | if (buffer.Count > readPos) 304 | { 305 | // If there are unread bytes 306 | float _value = BitConverter.ToSingle(readableBuffer, readPos); // Convert the bytes to a float 307 | if (_moveReadPos) 308 | { 309 | // If _moveReadPos is true 310 | readPos += 4; // Increase readPos by 4 311 | } 312 | return _value; // Return the float 313 | } 314 | else 315 | { 316 | throw new Exception("Could not read value of type 'float'!"); 317 | } 318 | } 319 | 320 | /// Reads a double from the packet. 321 | /// Whether or not to move the buffer's read position. 322 | public double ReadDouble(bool _moveReadPos = true) 323 | { 324 | if (buffer.Count > readPos) 325 | { 326 | // If there are unread bytes 327 | double _value = BitConverter.ToSingle(readableBuffer, readPos); // Convert the bytes to a double 328 | if (_moveReadPos) 329 | { 330 | // If _moveReadPos is true 331 | readPos += 8; // Increase readPos by 8 332 | } 333 | return _value; // Return the double 334 | } 335 | else 336 | { 337 | throw new Exception("Could not read value of type 'float'!"); 338 | } 339 | } 340 | 341 | /// Reads a bool from the packet. 342 | /// Whether or not to move the buffer's read position. 343 | public bool ReadBool(bool _moveReadPos = true) 344 | { 345 | if (buffer.Count > readPos) 346 | { 347 | // If there are unread bytes 348 | bool _value = BitConverter.ToBoolean(readableBuffer, readPos); // Convert the bytes to a bool 349 | if (_moveReadPos) 350 | { 351 | // If _moveReadPos is true 352 | readPos += 1; // Increase readPos by 1 353 | } 354 | return _value; // Return the bool 355 | } 356 | else 357 | { 358 | throw new Exception("Could not read value of type 'bool'!"); 359 | } 360 | } 361 | 362 | /// Reads a string from the packet. 363 | /// Whether or not to move the buffer's read position. 364 | public string ReadString(bool _moveReadPos = true) 365 | { 366 | try 367 | { 368 | int _length = ReadInt(); // Get the length of the string 369 | string _value = Encoding.ASCII.GetString(readableBuffer, readPos, _length); // Convert the bytes to a string 370 | if (_moveReadPos && _value.Length > 0) 371 | { 372 | // If _moveReadPos is true string is not empty 373 | readPos += _length; // Increase readPos by the length of the string 374 | } 375 | return _value; // Return the string 376 | } 377 | catch 378 | { 379 | throw new Exception("Could not read value of type 'string'!"); 380 | } 381 | } 382 | 383 | /// Reads a Vector3 from the packet. 384 | /// Whether or not to move the buffer's read position. 385 | public Vector3 ReadVector3(bool _moveReadPos = true) 386 | { 387 | return new Vector3(ReadFloat(_moveReadPos), ReadFloat(_moveReadPos), ReadFloat(_moveReadPos)); 388 | } 389 | 390 | /// Reads a Quaternion from the packet. 391 | /// Whether or not to move the buffer's read position. 392 | public Quaternion ReadQuaternion(bool _moveReadPos = true) 393 | { 394 | return new Quaternion(ReadFloat(_moveReadPos), ReadFloat(_moveReadPos), ReadFloat(_moveReadPos), ReadFloat(_moveReadPos)); 395 | } 396 | #endregion 397 | 398 | private bool disposed = false; 399 | 400 | protected virtual void Dispose(bool _disposing) 401 | { 402 | if (!disposed) 403 | { 404 | if (_disposing) 405 | { 406 | buffer = null; 407 | readableBuffer = null; 408 | readPos = 0; 409 | } 410 | disposed = true; 411 | } 412 | } 413 | 414 | public void Dispose() 415 | { 416 | Dispose(true); 417 | GC.SuppressFinalize(this); 418 | } 419 | 420 | } 421 | } -------------------------------------------------------------------------------- /Scripts/Receiver.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Numerics; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace DevelopersHub.RealtimeNetworking.Server 9 | { 10 | class Receiver 11 | { 12 | 13 | public static void Initialization(int clientID, Packet packet) 14 | { 15 | string token = packet.ReadString(); 16 | Server.clients[clientID].receiveToken = token; 17 | } 18 | 19 | public static void ReceiveCustom(int clientID, Packet packet) 20 | { 21 | if (packet != null) 22 | { 23 | Terminal.PacketReceived(clientID, packet); 24 | } 25 | } 26 | 27 | public static void ReceiveInternal(int clientID, Packet packet) 28 | { 29 | if (packet != null && Manager.enabled) 30 | { 31 | Manager.ReceivedPacket(clientID, packet); 32 | } 33 | } 34 | 35 | } 36 | } -------------------------------------------------------------------------------- /Scripts/Retry.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading; 4 | 5 | namespace DevelopersHub.RealtimeNetworking.Server 6 | { 7 | public static class Retry 8 | { 9 | 10 | public static T Do(Func action, TimeSpan retryInterval, int maxAttemptCount, bool throwExceptionOnAttemptsFailed = true) 11 | { 12 | var exceptions = new List(); 13 | for (int attempted = 0; attempted < maxAttemptCount; attempted++) 14 | { 15 | try 16 | { 17 | if (attempted > 0) { Thread.Sleep(retryInterval); } 18 | return action(); 19 | } 20 | catch (Exception ex) 21 | { 22 | exceptions.Add(ex); 23 | } 24 | } 25 | if (throwExceptionOnAttemptsFailed) 26 | { 27 | throw new AggregateException(exceptions); 28 | } 29 | else 30 | { 31 | return default; 32 | } 33 | } 34 | 35 | } 36 | } -------------------------------------------------------------------------------- /Scripts/Sender.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Numerics; 3 | 4 | namespace DevelopersHub.RealtimeNetworking.Server 5 | { 6 | class Sender 7 | { 8 | 9 | #region Core 10 | /// Sends a packet to a client via TCP. 11 | /// The client to send the packet the packet to. 12 | /// The packet to send to the client. 13 | private static void SendTCPData(int clientID, Packet packet) 14 | { 15 | packet.WriteLength(); 16 | Server.clients[clientID].tcp.SendData(packet); 17 | } 18 | 19 | /// Sends a packet to a client via UDP. 20 | /// The client to send the packet the packet to. 21 | /// The packet to send to the client. 22 | private static void SendUDPData(int clientID, Packet packet) 23 | { 24 | packet.WriteLength(); 25 | Server.clients[clientID].udp.SendData(packet); 26 | } 27 | 28 | /// Sends a packet to all clients via TCP. 29 | /// The packet to send. 30 | private static void SendTCPDataToAll(Packet packet) 31 | { 32 | packet.WriteLength(); 33 | for (int i = 1; i <= Server.MaxPlayers; i++) 34 | { 35 | Server.clients[i].tcp.SendData(packet); 36 | } 37 | } 38 | 39 | /// Sends a packet to all clients except one via TCP. 40 | /// The client to NOT send the data to. 41 | /// The packet to send. 42 | private static void SendTCPDataToAll(int exceptClientID, Packet packet) 43 | { 44 | packet.WriteLength(); 45 | for (int i = 1; i <= Server.MaxPlayers; i++) 46 | { 47 | if (i != exceptClientID) 48 | { 49 | Server.clients[i].tcp.SendData(packet); 50 | } 51 | } 52 | } 53 | 54 | /// Sends a packet to all clients via UDP. 55 | /// The packet to send. 56 | private static void SendUDPDataToAll(Packet packet) 57 | { 58 | packet.WriteLength(); 59 | for (int i = 1; i <= Server.MaxPlayers; i++) 60 | { 61 | Server.clients[i].udp.SendData(packet); 62 | } 63 | } 64 | 65 | /// Sends a packet to all clients except one via UDP. 66 | /// The client to NOT send the data to. 67 | /// The packet to send. 68 | private static void SendUDPDataToAll(int exceptClientID, Packet packet) 69 | { 70 | packet.WriteLength(); 71 | for (int i = 1; i <= Server.MaxPlayers; i++) 72 | { 73 | if (i != exceptClientID) 74 | { 75 | Server.clients[i].udp.SendData(packet); 76 | } 77 | } 78 | } 79 | #endregion 80 | 81 | #region TCP 82 | public static void TCP_Send(int clientID, Packet packet) 83 | { 84 | if (packet != null) 85 | { 86 | packet.SetID((int)Packet.ID.CUSTOM); 87 | SendTCPData(clientID, packet); 88 | } 89 | } 90 | 91 | public static void TCP_SentToAll(Packet packet) 92 | { 93 | if (packet != null) 94 | { 95 | packet.SetID((int)Packet.ID.CUSTOM); 96 | SendTCPDataToAll(packet); 97 | } 98 | } 99 | 100 | public static void TCP_SentToAllExeptOne(int excludedClientID, Packet packet) 101 | { 102 | if (packet != null) 103 | { 104 | packet.SetID((int)Packet.ID.CUSTOM); 105 | SendTCPDataToAll(excludedClientID, packet); 106 | } 107 | } 108 | #endregion 109 | 110 | #region UDP 111 | public static void UDP_Send(int clientID, Packet packet) 112 | { 113 | if (packet != null) 114 | { 115 | packet.SetID((int)Packet.ID.CUSTOM); 116 | SendUDPData(clientID, packet); 117 | } 118 | } 119 | 120 | public static void UDP_SentToAll(Packet packet) 121 | { 122 | if (packet != null) 123 | { 124 | packet.SetID((int)Packet.ID.CUSTOM); 125 | SendUDPDataToAll(packet); 126 | } 127 | } 128 | 129 | public static void UDP_SentToAllExeptOne(int excludedClientID, Packet packet) 130 | { 131 | if (packet != null) 132 | { 133 | packet.SetID((int)Packet.ID.CUSTOM); 134 | SendUDPDataToAll(excludedClientID, packet); 135 | } 136 | } 137 | #endregion 138 | 139 | } 140 | } -------------------------------------------------------------------------------- /Scripts/Server.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net; 4 | using System.Net.Sockets; 5 | 6 | namespace DevelopersHub.RealtimeNetworking.Server 7 | { 8 | class Server 9 | { 10 | 11 | public static int MaxPlayers { get; private set; } 12 | public static int Port { get; private set; } 13 | public static Dictionary clients = new Dictionary(); 14 | public delegate void PacketHandler(int clientID, Packet packet); 15 | public static Dictionary packetHandlers; 16 | 17 | private static TcpListener tcpListener; 18 | private static UdpClient udpListener; 19 | 20 | public static void Start(int maxPlayers, int port) 21 | { 22 | MaxPlayers = maxPlayers; 23 | Port = port; 24 | for (int i = 1; i <= MaxPlayers; i++) 25 | { 26 | clients.Add(i, new Client(i)); 27 | } 28 | packetHandlers = new Dictionary() 29 | { 30 | { (int)Packet.ID.INITIALIZATION, Receiver.Initialization }, 31 | { (int)Packet.ID.CUSTOM, Receiver.ReceiveCustom }, 32 | { (int)Packet.ID.INTERNAL, Receiver.ReceiveInternal }, 33 | }; 34 | tcpListener = new TcpListener(IPAddress.Any, Port); 35 | tcpListener.Start(); 36 | tcpListener.BeginAcceptTcpClient(OnConnectedTCP, null); 37 | if (Terminal.udp_active) 38 | { 39 | udpListener = new UdpClient(Port); 40 | udpListener.BeginReceive(OnConnectedUDP, null); 41 | } 42 | Terminal.Start(); 43 | } 44 | 45 | private static void OnConnectedTCP(IAsyncResult result) 46 | { 47 | TcpClient client = tcpListener.EndAcceptTcpClient(result); 48 | tcpListener.BeginAcceptTcpClient(OnConnectedTCP, null); 49 | Console.WriteLine("Incoming connection from {0}.", client.Client.RemoteEndPoint); 50 | for (int i = 1; i <= MaxPlayers; i++) 51 | { 52 | if (clients[i].tcp.socket == null && clients[i].accountID < 0 && clients[i].disconnecting == false) 53 | { 54 | clients[i].tcp.Initialize(client); 55 | IPEndPoint ip = client.Client.RemoteEndPoint as IPEndPoint; 56 | Terminal.ClientConnected(i, ip.Address.ToString()); 57 | if (Manager.enabled) 58 | { 59 | Manager.OnClientConnected(i, ip.Address.ToString()); 60 | } 61 | return; 62 | } 63 | } 64 | Console.WriteLine("{0} failed to connect. Server is at full capacity.", client.Client.RemoteEndPoint); 65 | } 66 | 67 | private static void OnConnectedUDP(IAsyncResult result) 68 | { 69 | try 70 | { 71 | IPEndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, 0); 72 | byte[] data = udpListener.EndReceive(result, ref clientEndPoint); 73 | udpListener.BeginReceive(OnConnectedUDP, null); 74 | if (data.Length < 4) 75 | { 76 | return; 77 | } 78 | using (Packet packet = new Packet(data)) 79 | { 80 | int id = packet.ReadInt(); 81 | if (id == 0) 82 | { 83 | return; 84 | } 85 | if (clients[id].udp.endPoint == null) 86 | { 87 | clients[id].udp.Connect(clientEndPoint); 88 | return; 89 | } 90 | if (clients[id].udp.endPoint.ToString() == clientEndPoint.ToString()) 91 | { 92 | clients[id].udp.CheckData(packet); 93 | } 94 | } 95 | } 96 | catch (Exception ex) 97 | { 98 | Tools.LogError(ex.Message, ex.StackTrace); 99 | } 100 | } 101 | 102 | public static void SendDataUDP(IPEndPoint clientEndPoint, Packet packet) 103 | { 104 | try 105 | { 106 | if (clientEndPoint != null) 107 | { 108 | udpListener.BeginSend(packet.ToArray(), packet.Length(), clientEndPoint, null, null); 109 | } 110 | } 111 | catch (Exception ex) 112 | { 113 | Tools.LogError(ex.Message, ex.StackTrace); 114 | } 115 | } 116 | 117 | } 118 | } -------------------------------------------------------------------------------- /Scripts/Sqlite.cs: -------------------------------------------------------------------------------- 1 | using Google.Protobuf.WellKnownTypes; 2 | using Microsoft.Data.Sqlite; 3 | using System; 4 | using System.IO; 5 | using System.Threading.Tasks; 6 | 7 | namespace DevelopersHub.RealtimeNetworking.Server 8 | { 9 | class Sqlite 10 | { 11 | 12 | public static SqliteConnection connection 13 | { 14 | get 15 | { 16 | return new SqliteConnection("Data Source = " + Terminal.sqlite_database_file_path + "; Pooling = True;"); 17 | } 18 | } 19 | 20 | public static async void Initialize() 21 | { 22 | bool created = await CreateDatabase(); 23 | if(created) 24 | { 25 | CreateTables(); 26 | } 27 | ResetAccountsIndex(); 28 | // Test("A"); 29 | // Test("B"); 30 | // Test("C"); 31 | // Test("D"); 32 | // Test("E"); 33 | // Test("F"); 34 | // Test("G"); 35 | // Test("H"); 36 | // Test("I"); 37 | // Test("J"); 38 | } 39 | 40 | /* 41 | private static void Test(string id) 42 | { 43 | Task task = Task.Run(() => 44 | { 45 | int count = 0; 46 | while (true) 47 | { 48 | using (var _connection = connection) 49 | { 50 | long id = 1; 51 | _connection.Open(); 52 | using (var command = _connection.CreateCommand()) 53 | { 54 | command.CommandText = string.Format(@"INSERT INTO accounts (username, password) VALUES('{0}', '{1}'); SELECT LAST_INSERT_ROWID();", "whatever", "whatever"); 55 | id = Convert.ToInt64(command.ExecuteScalar()); 56 | } 57 | using (var command = _connection.CreateCommand()) 58 | { 59 | command.CommandText = string.Format(@"SELECT username, client_index, coins, score, level, xp, login_time FROM accounts WHERE id = {0};", id); 60 | using (var reader = command.ExecuteReader()) 61 | { 62 | if (reader.HasRows) 63 | { 64 | while (reader.Read()) 65 | { 66 | Data.PlayerProfile profile = new Data.PlayerProfile(); 67 | profile.id = id; 68 | profile.username = reader.GetString("username"); 69 | profile.online = reader.GetInt32("client_index") >= 0; 70 | profile.coins = reader.GetInt32("coins"); 71 | profile.score = reader.GetInt32("score"); 72 | profile.level = reader.GetInt32("level"); 73 | profile.xp = reader.GetInt32("xp"); 74 | profile.login = reader.GetDateTime("login_time"); 75 | break; 76 | } 77 | } 78 | } 79 | } 80 | _connection.Close(); 81 | } 82 | count++; 83 | Console.WriteLine(id + " " + count.ToString()); 84 | if (count >= 100) 85 | { 86 | break; 87 | } 88 | } 89 | }); 90 | } 91 | */ 92 | 93 | private static void ResetAccountsIndex() 94 | { 95 | try 96 | { 97 | using (var _connection = connection) 98 | { 99 | _connection.Open(); 100 | var command = _connection.CreateCommand(); 101 | command.CommandText = @"UPDATE accounts SET client_index = -1"; 102 | command.ExecuteNonQuery(); 103 | _connection.Close(); 104 | } 105 | } 106 | catch (Exception ex) 107 | { 108 | Console.WriteLine(ex.Message + "\n" + ex.StackTrace); 109 | } 110 | } 111 | 112 | private async static Task CreateDatabase() 113 | { 114 | Task task = Task.Run(() => 115 | { 116 | try 117 | { 118 | if (!File.Exists(Terminal.sqlite_database_file_path)) 119 | { 120 | string directory = Path.GetDirectoryName(Terminal.sqlite_database_file_path); 121 | if (!Directory.Exists(directory)) 122 | { 123 | Directory.CreateDirectory(directory); 124 | } 125 | FileStream fileStream = File.Create(Terminal.sqlite_database_file_path); 126 | return true; 127 | } 128 | else 129 | { 130 | // TODO: Validate the file 131 | } 132 | } 133 | catch (Exception ex) 134 | { 135 | Console.WriteLine(ex.Message + "\n" + ex.StackTrace); 136 | } 137 | return false; 138 | }); 139 | return await task; 140 | } 141 | 142 | private static void CreateTables() 143 | { 144 | using (var _connection = connection) 145 | { 146 | _connection.Open(); 147 | var command = _connection.CreateCommand(); 148 | 149 | command.CommandText = @" 150 | Create Table accounts ( 151 | id INTEGER PRIMARY KEY AUTOINCREMENT, 152 | username VARCHAR(50) DEFAULT 'Player', 153 | password VARCHAR(500) DEFAULT '', 154 | device_id VARCHAR(500) DEFAULT '', 155 | ip_address VARCHAR(50) DEFAULT '0.0.0.0', 156 | client_index INTEGER DEFAULT -1, 157 | coins INTEGER DEFAULT 0, 158 | score INTEGER DEFAULT 0, 159 | level INTEGER DEFAULT 1, 160 | xp INTEGER DEFAULT 0, 161 | login_time DATETIME DEFAULT CURRENT_TIMESTAMP, 162 | banned INTEGER DEFAULT 0, 163 | ban_reason INTEGER DEFAULT 0 164 | )"; 165 | command.ExecuteNonQuery(); 166 | 167 | command.CommandText = @" 168 | Create Table characters ( 169 | id INTEGER PRIMARY KEY AUTOINCREMENT, 170 | account_id INTEGER DEFAULT 0, 171 | selected INTEGER DEFAULT 0, 172 | prefab_id INTEGER DEFAULT 0, 173 | xp INTEGER DEFAULT 0, 174 | level INTEGER DEFAULT 1, 175 | health REAL DEFAULT 100, 176 | speed REAL DEFAULT 0, 177 | damage REAL DEFAULT 0, 178 | strength INTEGER DEFAULT 0, 179 | agility INTEGER DEFAULT 0, 180 | constitution INTEGER DEFAULT 0, 181 | dexterity INTEGER DEFAULT 0, 182 | vitality INTEGER DEFAULT 0, 183 | endurance INTEGER DEFAULT 0, 184 | intelligence INTEGER DEFAULT 0, 185 | wisdom INTEGER DEFAULT 0, 186 | charisma INTEGER DEFAULT 0, 187 | perception INTEGER DEFAULT 0, 188 | luck INTEGER DEFAULT 0, 189 | willpower INTEGER DEFAULT 0, 190 | default_name VARCHAR(50) DEFAULT 'No Name', 191 | tag VARCHAR(50) DEFAULT '', 192 | custom_name VARCHAR(50) DEFAULT '' 193 | )"; 194 | command.ExecuteNonQuery(); 195 | 196 | command.CommandText = @" 197 | Create Table equipments ( 198 | id INTEGER PRIMARY KEY AUTOINCREMENT, 199 | account_id INTEGER DEFAULT 0, 200 | character_id INTEGER DEFAULT 0, 201 | prefab_id INTEGER DEFAULT 0, 202 | type INTEGER DEFAULT 0, 203 | level INTEGER DEFAULT 1, 204 | armor REAL DEFAULT 0, 205 | speed REAL DEFAULT 0, 206 | damage REAL DEFAULT 0, 207 | range REAL DEFAULT 0, 208 | weight REAL DEFAULT 0, 209 | accuracy REAL DEFAULT 0, 210 | capacity INTEGER DEFAULT 0, 211 | default_name VARCHAR(50) DEFAULT 'No Name', 212 | tag VARCHAR(50) DEFAULT '', 213 | custom_name VARCHAR(50) DEFAULT '' 214 | )"; 215 | command.ExecuteNonQuery(); 216 | 217 | command.CommandText = @" 218 | Create Table friends ( 219 | id INTEGER PRIMARY KEY AUTOINCREMENT, 220 | account_id_1 INTEGER DEFAULT 0, 221 | account_id_2 INTEGER DEFAULT 0, 222 | status INTEGER DEFAULT 0, 223 | action_time DATETIME DEFAULT CURRENT_TIMESTAMP 224 | )"; 225 | command.ExecuteNonQuery(); 226 | 227 | command.CommandText = @" 228 | Create Table user_blocking ( 229 | id INTEGER PRIMARY KEY AUTOINCREMENT, 230 | blocker_id INTEGER DEFAULT 0, 231 | blocked_id INTEGER DEFAULT 0, 232 | reason INTEGER DEFAULT 0, 233 | action_time DATETIME DEFAULT CURRENT_TIMESTAMP 234 | )"; 235 | command.ExecuteNonQuery(); 236 | 237 | command.CommandText = @" 238 | Create Table ip_banning ( 239 | id INTEGER PRIMARY KEY AUTOINCREMENT, 240 | ip_address VARCHAR(50) DEFAULT '0.0.0.0', 241 | reason INTEGER DEFAULT 0, 242 | action_time DATETIME DEFAULT CURRENT_TIMESTAMP 243 | )"; 244 | command.ExecuteNonQuery(); 245 | 246 | _connection.Close(); 247 | } 248 | } 249 | 250 | } 251 | } 252 | -------------------------------------------------------------------------------- /Scripts/Threading.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace DevelopersHub.RealtimeNetworking.Server 8 | { 9 | class Threading 10 | { 11 | private static readonly List executeOnMainThread = new List(); 12 | private static readonly List executeCopiedOnMainThread = new List(); 13 | private static bool actionToExecuteOnMainThread = false; 14 | 15 | /// Sets an action to be executed on the main thread. 16 | /// The action to be executed on the main thread. 17 | public static void ExecuteOnMainThread(Action _action) 18 | { 19 | if (_action == null) 20 | { 21 | Console.WriteLine("No action to execute on main thread!"); 22 | return; 23 | } 24 | lock (executeOnMainThread) 25 | { 26 | executeOnMainThread.Add(_action); 27 | actionToExecuteOnMainThread = true; 28 | } 29 | } 30 | 31 | /// Executes all code meant to run on the main thread. 32 | public static void UpdateMain() 33 | { 34 | if (actionToExecuteOnMainThread) 35 | { 36 | executeCopiedOnMainThread.Clear(); 37 | lock (executeOnMainThread) 38 | { 39 | executeCopiedOnMainThread.AddRange(executeOnMainThread); 40 | executeOnMainThread.Clear(); 41 | actionToExecuteOnMainThread = false; 42 | } 43 | for (int i = 0; i < executeCopiedOnMainThread.Count; i++) 44 | { 45 | executeCopiedOnMainThread[i](); 46 | } 47 | } 48 | } 49 | 50 | } 51 | } -------------------------------------------------------------------------------- /Scripts/Tools.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Threading.Tasks; 4 | using System.Net; 5 | using System.Net.Sockets; 6 | using System.Text; 7 | using System.Security.Cryptography; 8 | using System.IO.Compression; 9 | using System.Xml.Serialization; 10 | 11 | namespace DevelopersHub.RealtimeNetworking.Server 12 | { 13 | static class Tools 14 | { 15 | 16 | public static void LogError(string message, string trace, string folder = "") 17 | { 18 | Console.WriteLine("Error:" + "\n" + message + "\n" + trace); 19 | Task task = Task.Run(() => 20 | { 21 | try 22 | { 23 | string folderPath = Terminal.log_directory_path; 24 | if (!string.IsNullOrEmpty(folder)) 25 | { 26 | folderPath = folderPath + folder + "\\"; 27 | } 28 | string path = folderPath + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss-ffff") + ".txt"; 29 | if (!Directory.Exists(folderPath)) 30 | { 31 | Directory.CreateDirectory(folderPath); 32 | } 33 | File.WriteAllText(path, message + "\n" + trace); 34 | } 35 | catch (Exception ex) 36 | { 37 | Console.WriteLine("Error:" + "\n" + ex.Message + "\n" + ex.StackTrace); 38 | } 39 | }); 40 | } 41 | 42 | public static string GenerateToken() 43 | { 44 | return Path.GetRandomFileName().Remove(8, 1); 45 | } 46 | 47 | public static string GetIP(AddressFamily type) 48 | { 49 | var host = Dns.GetHostEntry(Dns.GetHostName()); 50 | foreach (var ip in host.AddressList) 51 | { 52 | if (ip.AddressFamily == type) 53 | { 54 | return ip.ToString(); 55 | } 56 | } 57 | return "0.0.0.0"; 58 | } 59 | 60 | /* 61 | public static string GetExternalIP() 62 | { 63 | try 64 | { 65 | var ip = IPAddress.Parse(new WebClient().DownloadString("https://icanhazip.com").Replace("\\r\\n", "").Replace("\\n", "").Trim()); 66 | return ip.ToString(); 67 | } 68 | catch (Exception) 69 | { 70 | try 71 | { 72 | StreamReader sr = new StreamReader(WebRequest.Create("https://checkip.dyndns.org").GetResponse().GetResponseStream()); 73 | string[] ipAddress = sr.ReadToEnd().Trim().Split(':')[1].Substring(1).Split('<'); 74 | return ipAddress[0]; 75 | } 76 | catch (Exception) 77 | { 78 | return "0.0.0.0"; 79 | } 80 | } 81 | } 82 | */ 83 | 84 | public static int FindFreeTcpPort() 85 | { 86 | TcpListener listener = new TcpListener(IPAddress.Loopback, 0); 87 | listener.Start(); 88 | int port = ((IPEndPoint)listener.LocalEndpoint).Port; 89 | listener.Stop(); 90 | return port; 91 | } 92 | 93 | public static T CloneClass(this T target) 94 | { 95 | return Desrialize(Serialize(target)); 96 | } 97 | 98 | public static void CopyTo(Stream source, Stream target) 99 | { 100 | byte[] bytes = new byte[4096]; int count; 101 | while ((count = source.Read(bytes, 0, bytes.Length)) != 0) 102 | { 103 | target.Write(bytes, 0, count); 104 | } 105 | } 106 | 107 | #region Encryption 108 | /* 109 | public static string EncrypteToMD5(string data) 110 | { 111 | UTF8Encoding ue = new UTF8Encoding(); 112 | byte[] bytes = ue.GetBytes(data); 113 | MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); 114 | byte[] hashBytes = md5.ComputeHash(bytes); 115 | string hashString = ""; 116 | for (int i = 0; i < hashBytes.Length; i++) 117 | { 118 | hashString = hashString + Convert.ToString(hashBytes[i], 16).PadLeft(2, '0'); 119 | } 120 | return hashString.PadLeft(32, '0'); 121 | } 122 | */ 123 | 124 | public static string EncrypteToMD5(string data) 125 | { 126 | MD5 md5 = MD5.Create(); 127 | byte[] bytes = Encoding.Default.GetBytes(data); 128 | byte[] encoded = md5.ComputeHash(bytes); 129 | StringBuilder builder = new StringBuilder(); 130 | for (int i = 0; i < encoded.Length; i++) 131 | { 132 | builder.Append(encoded[i].ToString("x2")); 133 | } 134 | return builder.ToString(); 135 | } 136 | #endregion 137 | 138 | #region Serialization 139 | public static string Serialize(this T target) 140 | { 141 | XmlSerializer xml = new XmlSerializer(typeof(T)); 142 | StringWriter writer = new StringWriter(); 143 | xml.Serialize(writer, target); 144 | return writer.ToString(); 145 | } 146 | 147 | public static T Desrialize(this string target) 148 | { 149 | XmlSerializer xml = new XmlSerializer(typeof(T)); 150 | StringReader reader = new StringReader(target); 151 | return (T)xml.Deserialize(reader); 152 | } 153 | 154 | public async static Task SerializeAsync(this T target) 155 | { 156 | Task task = Task.Run(() => 157 | { 158 | XmlSerializer xml = new XmlSerializer(typeof(T)); 159 | StringWriter writer = new StringWriter(); 160 | xml.Serialize(writer, target); 161 | return writer.ToString(); 162 | }); 163 | return await task; 164 | } 165 | 166 | public async static Task DesrializeAsync(this string target) 167 | { 168 | Task task = Task.Run(() => 169 | { 170 | XmlSerializer xml = new XmlSerializer(typeof(T)); 171 | StringReader reader = new StringReader(target); 172 | return (T)xml.Deserialize(reader); 173 | }); 174 | return await task; 175 | } 176 | #endregion 177 | 178 | #region Compression 179 | public async static Task CompressAsync(string target) 180 | { 181 | Task task = Task.Run(() => 182 | { 183 | return Compress(target); 184 | }); 185 | return await task; 186 | } 187 | 188 | public static byte[] Compress(string target) 189 | { 190 | var bytes = Encoding.UTF8.GetBytes(target); 191 | using (var msi = new MemoryStream(bytes)) 192 | { 193 | using (var mso = new MemoryStream()) 194 | { 195 | using (var gs = new GZipStream(mso, CompressionMode.Compress)) 196 | { 197 | CopyTo(msi, gs); 198 | } 199 | return mso.ToArray(); 200 | } 201 | } 202 | } 203 | 204 | public async static Task CompressStringAsync(string target) 205 | { 206 | Task task = Task.Run(() => 207 | { 208 | return CompressString(target); 209 | }); 210 | return await task; 211 | } 212 | 213 | public static string CompressString(string target) 214 | { 215 | return Convert.ToBase64String(Compress(target)); 216 | } 217 | 218 | public async static Task DecompressAsync(byte[] bytes) 219 | { 220 | Task task = Task.Run(() => 221 | { 222 | return Decompress(bytes); 223 | }); 224 | return await task; 225 | } 226 | 227 | public static string Decompress(byte[] bytes) 228 | { 229 | using (var msi = new MemoryStream(bytes)) 230 | { 231 | using (var mso = new MemoryStream()) 232 | { 233 | using (var gs = new GZipStream(msi, CompressionMode.Decompress)) 234 | { 235 | CopyTo(gs, mso); 236 | } 237 | return Encoding.UTF8.GetString(mso.ToArray()); 238 | } 239 | } 240 | } 241 | 242 | public async static Task DecompressStringAsync(string target) 243 | { 244 | Task task = Task.Run(() => 245 | { 246 | return DecompressString(target); 247 | }); 248 | return await task; 249 | } 250 | 251 | public static string DecompressString(string target) 252 | { 253 | return Decompress(Convert.FromBase64String(target)); 254 | } 255 | #endregion 256 | 257 | } 258 | } -------------------------------------------------------------------------------- /Terminal.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DevelopersHub.RealtimeNetworking.Server 4 | { 5 | class Terminal 6 | { 7 | 8 | public const int port = 5555; 9 | public const int updates_per_second = 30; 10 | public const int max_players = 100000; 11 | public const bool udp_active = true; 12 | public const string sqlite_database_file_path = @"C:\Database\realtime_networking.db"; 13 | public const string log_directory_path = @"C:\Log\realtime_networking\"; 14 | 15 | #region Extensions 16 | public const string netcode_server_executable_path = @"C:\Users\Test\Desktop\Server\Netcode.exe"; 17 | public const int netcode_max_server_life_seconds = 21600; 18 | #endregion 19 | 20 | public static void Start() 21 | { 22 | Console.WriteLine("Server Started."); 23 | } 24 | 25 | public static void Update() 26 | { 27 | 28 | } 29 | 30 | public static void ClientConnected(int id, string ip) 31 | { 32 | 33 | } 34 | 35 | public static void ClientDisconnected(int id, string ip) 36 | { 37 | 38 | } 39 | 40 | public static void PacketReceived(int clientID, Packet packet) 41 | { 42 | 43 | } 44 | 45 | public static void OnAuthenticated(long accountID, bool wasSignedUp, Microsoft.Data.Sqlite.SqliteConnection connection) 46 | { 47 | 48 | } 49 | 50 | public static (Data.PurchaseResult, int) OverridePurchase(long accountID, int itemCategory, int itemID, int itemLevel, int currencyID, Microsoft.Data.Sqlite.SqliteConnection connection) 51 | { 52 | uint price = 99999; 53 | Data.PurchaseResult result = Data.PurchaseResult.Unknown; 54 | 55 | /* 56 | bool purchased = false; 57 | if (itemCategory == weapon && itemID == excalibur && itemLevel == 1) 58 | { 59 | if(currencyID == coins) 60 | { 61 | price = 12345; 62 | purchased = Manager.SpendCoins(accountID, price); 63 | } 64 | } 65 | if(purchased) 66 | { 67 | // Add item here. For example: 68 | Data.RuntimeEquipment sword = new Data.RuntimeEquipment(); 69 | sword.name = "Excalibur"; 70 | sword.tag = "excalibur"; 71 | sword.prefabID = 0; 72 | sword.weight = 4.8; 73 | sword.damage = 25; 74 | sword.level = itemLevel; 75 | Manager.CreateEquipment(accountID, 0, sword); 76 | } 77 | else 78 | { 79 | result = Data.PurchaseResult.InsufficientFunds; 80 | } 81 | */ 82 | 83 | return (result, (int)price); 84 | } 85 | 86 | public static (int, int) OverrideMatchmaking(int gameID, int mapID) 87 | { 88 | int teamsPerMatch = 2; 89 | int playersPerTeam = 6; 90 | // ---> 91 | // Add your custom game conditions here, for example: 92 | if (gameID == 1) 93 | { 94 | teamsPerMatch = 10; 95 | playersPerTeam = 10; 96 | } 97 | else if (gameID == 2) 98 | { 99 | teamsPerMatch = 2; 100 | playersPerTeam = 100; 101 | } 102 | // <--- 103 | return (teamsPerMatch, playersPerTeam); 104 | } 105 | 106 | public static void OverrideGameInitialData(ref Data.RuntimeGame data, Microsoft.Data.Sqlite.SqliteConnection connection) 107 | { 108 | 109 | } 110 | 111 | public static void OnGameFinished(Data.Game game) 112 | { 113 | 114 | } 115 | 116 | public static void OnNetcodeGameResultReceived(Data.RuntimeResult result) 117 | { 118 | 119 | } 120 | 121 | } 122 | } -------------------------------------------------------------------------------- /app.manifest: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | --------------------------------------------------------------------------------