├── .gitignore ├── LICENSE ├── README.md ├── imgs ├── client.gif └── server.gif └── src ├── ObjectBinarySerializationTest └── SerializationTest │ ├── GlobalUsing.cs │ ├── Models │ ├── Department.cs │ ├── Employee.cs │ ├── Organization.cs │ ├── ProcessData.cs │ ├── RequestOrganizations.cs │ └── ResponseOrganizations.cs │ ├── Program.cs │ ├── SerializationTest.csproj │ ├── SerializeUtils │ ├── Helpers │ │ ├── CustomSerializeHelper.cs │ │ ├── JsonSerializeHelper.cs │ │ ├── MessagePackSerializeHelper.cs │ │ └── ProtobufSerializeHelper.cs │ └── ISerializeHelper.cs │ └── Test │ └── BenchmarkTest.cs ├── SocketTest.sln └── SocketTesting ├── SocketDto.Test ├── GlobalUsings.cs ├── NumberFormatUnitTest.cs ├── ResponseProcessListUnitTest.cs ├── SocketDto.Test.csproj ├── SocketDtoUnitTest.cs ├── SystemProcessUnitTest.cs └── UpdateGeneralProcessListUnitTest.cs ├── SocketDto ├── AutoCommand │ ├── ChangeProcessList.cs │ └── UpdateProcessList.cs ├── Enums │ ├── AlarmStatus.cs │ ├── GpuEngine.cs │ ├── PowerUsage.cs │ ├── ProcessStatus.cs │ ├── ProcessType.cs │ └── TerminalType.cs ├── EventBus │ ├── ChangeTCPStatusCommand.cs │ ├── ChangeUDPStatusCommand.cs │ └── SocketCommand.cs ├── GlobalUsing.cs ├── Heartbeat.cs ├── ISocketBase.cs ├── Requests │ ├── RequestProcessIDList.cs │ ├── RequestProcessList.cs │ ├── RequestServiceInfo.cs │ ├── RequestTargetType.cs │ └── RequestUdpAddress.cs ├── Response │ ├── ResponseProcessIDList.cs │ ├── ResponseProcessList.cs │ ├── ResponseServiceInfo.cs │ ├── ResponseTargetType.cs │ └── ResponseUdpAddress.cs ├── SocketDto.csproj └── Udp │ ├── UpdateGeneralProcessList.cs │ └── UpdateRealtimeProcessList.cs ├── SocketTest.Client ├── App.axaml ├── App.axaml.cs ├── Assets │ └── avalonia-logo.ico ├── Converters │ ├── AlarmStatusToForegroundConverter.cs │ ├── EnumToDescriptionConverter.cs │ ├── ProcessPowerUsageToForegroundConverter.cs │ ├── ProcessStatusToForegroundConverter.cs │ ├── UsageToForegroundConverter.cs │ └── UsageToFormatConverter.cs ├── Extensions │ └── RangObservableCollection.cs ├── Helpers │ ├── TcpHelper.cs │ └── UdpHelper.cs ├── Models │ └── ProcessItemModel.cs ├── Program.cs ├── Roots.xml ├── SocketTest.Client.csproj ├── ViewModels │ └── MainWindowViewModel.cs ├── Views │ ├── MainWindow.axaml │ └── MainWindow.axaml.cs └── app.manifest └── SocketTest.Server ├── App.axaml ├── App.axaml.cs ├── Assets └── avalonia-logo.ico ├── Helpers ├── TcpHelper.cs └── UdpHelper.cs ├── Mock ├── MockConst.cs └── MockUtil.cs ├── Program.cs ├── Roots.xml ├── SocketTest.Server.csproj ├── ViewModels └── MainWindowViewModel.cs ├── Views ├── MainWindow.axaml └── MainWindow.axaml.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 | src/.idea/ 400 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Dotnet9(dotnet9.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 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 | # C#百万对象序列化与网络传输实践 2 | 3 | | 日期 | 更新内容 | 版本 | 作者 | 4 | | ---------- | ------------------------------------------------------------ | ----- | ------------ | 5 | | 2023-12-16 | 初建,添加网络对象定义 | 0.0.1 | 沙漠尽头的狼 | 6 | | 2023-12-24 | 修改数据类型,节约网络传输大小和减少数据包个数 | 0.0.2 | 沙漠尽头的狼 | 7 | | 2024-02-07 | 1)添加界面截图,2)添加AvaloniaUI分支,1个UDP包拆分2个 | 0.0.3 | 沙漠尽头的狼 | 8 | | 2024-02-08 | 完善进程状态 | 0.0.4 | 沙漠尽头的狼 | 9 | | 2024-02-09 | 修改通信对象,优化发包效率:常更新字段直接读取byte[],优化数据包组装效率 | 0.0.5 | 沙漠尽头的狼 | 10 | | 2024-02-25 | 添加终端类型查询命令 | 0.0.6 | 沙漠尽头的狼 | 11 | | 2024-02-26 | 添加Udp组播地址请求命令,客户端不需要手工配置 | 0.0.7 | 沙漠尽头的狼 | 12 | | 2024-07-09 | 数据包Header添加8个字节长度的Unix毫秒时间戳 | 0.0.8 | 沙漠尽头的狼 | 13 | 14 | [TOC] 15 | 16 | ## 1. 背景 17 | 18 | 完善文章《[C#百万对象序列化深度剖析:如何在网络传输中实现速度与体积的完美平衡 (dotnet9.com)](https://dotnet9.com/2023/12/deep-analysis-of-csharp-million-object-serialization-how-to-achieve-a-perfect-balance-between-speed-and-volume-in-network-transm)》,以客户端实时获取服务端进程信息为测试案例: 19 | 20 | 1. 以操作系统进程信息作为传输数据扩展数个网络数据包,操作系统进程有:进程ID、进程名称、CPU利用率、内存使用率等。 21 | 2. C/S两端使用Avalonia UI作为界面展示; 22 | 3. 添加TCP通信,客户端通过命令方式向服务端请求数据,服务端可被动响应,也可主动推送,主动推送场景包括修改进程、进程结构变化(增加进程、删除进程)等; 23 | 4. 添加UDP通信,服务端可组播数据,主要是常变数据,比如CPU利用率、内存使用率、电源使用情况等; 24 | 5. Avalonia UI百万数据DataGrid加载、实时更新。 25 | 26 | ## 2. 数据包【0.0.5】 27 | 28 | **数据包=头部+数据** 29 | 30 | ### 2.1. 头部【0.0.7】 31 | 32 | | 字段名 | 数据类型 | 说明 | 33 | | --------------- | -------- | ---------------------------------- | 34 | | PacketSize | int | 数据包总大小=头部大小+数据部分大小 | 35 | | SystemId | long | 系统Id | 36 | | `ObjectId` | byte | 对象Id | 37 | | `ObjectVersion` | byte | 对象版本 | 38 | | `UnixTimeMilliseconds` | long | Unix毫秒时间戳 | 39 | 40 | ### 2.2. 数据部分【0.0.5】 41 | 42 | 1. 统一编码为UTF-8。 43 | 44 | 1. TCP数据包基本使用`MessagePack`对对象进行二进制压缩,理论上数据包会比常规二进制序列化小2/3左右。 45 | 2. UDP包不使用任何压缩框架,对于大数字类型(int\double)压缩反而让数据包体积更大,所以使用`BinnaryReader`、`BinnaryWriter`做序列化和反序列化。 46 | 3. `string`|`List`|`Dictionary`等集合类型:前4字节用int表示数量,后面部分为实际数据byte[]。 47 | 48 | ## 3. 网络对象定义 49 | 50 | TCP、UDP传输数据包定义。 51 | 52 | ### 3.1. TCP数据包【0.0.7】 53 | 54 | | 对象Id | 对象版本 | 对象名 | 说明 | 55 | | ------ | -------- | --------------------- | ---------------------------------------- | 56 | | 1 | 1 | RequestTargetType | 请求目标终端类型 | 57 | | 2 | 1 | ResponseTargetType | 响应目标终端类型 | 58 | | 3 | 1 | RequestUdpAddress | 请求Udp组播地址 | 59 | | 4 | 1 | ResponseUdpAddress | 响应Udp组播地址 | 60 | | 5 | 1 | RequestServiceInfo | 请求服务基本信息 | 61 | | 6 | 1 | ResponseServiceInfo | 响应请求服务基本信息 | 62 | | 7 | 1 | RequestProcessIDList | 请求进程ID列表 | 63 | | 8 | 1 | ResponseProcessIDList | 响应请求进程ID列表,更新实时数据需要使用 | 64 | | 9 | 1 | RequestProcessList | 请求进程详细信息列表 | 65 | | 10 | 1 | ResponseProcessList | 响应请求进程详细信息列表 | 66 | | 11 | 1 | UpdateProcessList | 更新进程详细信息列表 | 67 | | 12 | 1 | ChangeProcessList | 进程结构变化:增加、减少进程 | 68 | | 199 | 1 | Heartbeat | TCP心跳包 | 69 | 70 | #### RequestTargetType【0.0.6】 71 | 72 | | 字段名 | 数据类型 | 说明 | 73 | | ------ | -------- | ------ | 74 | | TaskId | int | 任务Id | 75 | 76 | #### ResponseTargetType【0.0.6】 77 | 78 | | 字段名 | 数据类型 | 说明 | 79 | | ------ | -------- | ------------------------------ | 80 | | TaskId | int | 任务Id | 81 | | Type | byte | 终端类型,0:Server,1:Client | 82 | 83 | #### RequestUdpAddress【0.0.7】 84 | 85 | | 字段名 | 数据类型 | 说明 | 86 | | ------ | -------- | ------ | 87 | | TaskId | int | 任务Id | 88 | 89 | #### ResponseUdpAddress【0.0.7】 90 | 91 | | 字段名 | 数据类型 | 说明 | 92 | | ------ | -------- | -------- | 93 | | TaskId | int | 任务Id | 94 | | Ip | string | 组播地址 | 95 | | Port | int | 组播端口 | 96 | 97 | #### RequestServiceInfo【0.0.7】 98 | 99 | | 字段名 | 数据类型 | 说明 | 100 | | ------ | -------- | ------ | 101 | | TaskId | int | 任务Id | 102 | 103 | #### ResponseServiceInfo【0.0.7】 104 | 105 | | 字段名 | 数据类型 | 说明 | 106 | | ------------------ | -------- | ------------------------------------------------------------ | 107 | | TaskId | int | 任务Id | 108 | | OS | string? | 操作系统名称 | 109 | | MemorySize | byte | 系统内存大小(单位GB) | 110 | | ProcessorCount | byte | 处理器个数 | 111 | | DiskSize | short | 硬盘总容量(单位GB) | 112 | | NetworkBandwidth | short | 网络带宽(单位Mbps) | 113 | | Ips | string? | 服务器IP地址,多个IP地址以,分隔 | 114 | | TimestampStartYear | byte | 通信对象时间戳起始年份,比如:23,表示2023年1月1号开始计算时间戳,后面的时间戳都以这个字段计算为准,精确到0.1s,即100ms,主要用于节约网络对象传输大小 | 115 | | LastUpdateTime | uint | 最后更新时间 | 116 | 117 | #### RequestProcessIDList【0.0.5】 118 | 119 | | 字段名 | 数据类型 | 说明 | 120 | | ------ | -------- | ------ | 121 | | TaskId | int | 任务Id | 122 | 123 | #### ResponseProcessIDList【0.0.5】 124 | 125 | | 字段名 | 数据类型 | 说明 | 126 | | ------ | -------- | ------------------------------------------------------------ | 127 | | TaskId | int | 任务Id | 128 | | IDList | int[] | 进程ID数组,有顺序,更新进程实时数据包需要根据该数组查找进程、更新数据 | 129 | 130 | #### RequestProcessList【0.0.1】 131 | 132 | | 字段名 | 数据类型 | 说明 | 133 | | ------ | -------- | ------ | 134 | | TaskId | int | 任务Id | 135 | 136 | #### ResponseProcessList【0.0.5】 137 | 138 | | 字段名 | 数据类型 | 说明 | 139 | | --------- | -------------------- | ---------- | 140 | | TaskId | int | 任务Id | 141 | | TotalSize | int | 总数据大小 | 142 | | PageSize | int | 分页大小 | 143 | | PageCount | int | 总页数 | 144 | | PageIndex | int | 页索引 | 145 | | Processes | `List?` | 进程列表 | 146 | 147 | #### ProcessItem【0.0.5】 148 | 149 | | 字段名 | 数据类型 | 说明 | 150 | | --------------- | -------- | ------------------------------------------------------------ | 151 | | Pid | int | 进程ID | 152 | | Name | string? | 进程名称 | 153 | | Type | byte | 进程类型,0:应用,1:后台进程 | 154 | | ProcessStatus | byte | 进程状态,0:新建状态,1:就绪状态,2:运行状态,3:阻塞状态,4:终止状态 | 155 | | AlarmStatus | byte | 告警状态,没有特别意义,可组合位域状态,0:正常,1:超时,2:超限,切换用户 | 156 | | Publisher | string? | 发布者 | 157 | | CommandLine | string? | 命令行 | 158 | | Cpu | short | Cpu(所有内核的总处理利用率),最后一位表示小数位,比如253表示25.3% | 159 | | Memory | short | 内存(进程占用的物理内存),最后一位表示小数位,比如253表示25.3%,值可根据基本信息计算 | 160 | | Disk | short | 磁盘(所有物理驱动器的总利用率),最后一位表示小数位,比如253表示25.3%,值可根据基本信息计算 | 161 | | Network | short | 网络(当前主要网络上的网络利用率),最后一位表示小数位,比如253表示25.3%,值可根据基本信息计算 | 162 | | Gpu | short | Gpu(所有Gpu引擎的最高利用率),最后一位表示小数位,比如253表示25.3 | 163 | | GpuEngine | byte | Gpu引擎,0:无,1:GPU 0 - 3D | 164 | | PowerUsage | byte | 电源使用情况(CPU、磁盘和GPU对功耗的影响),0:非常低,1:低,2:中,3:高,4:非常高 | 165 | | PowerUsageTrend | byte | 电源使用情况趋势(一段时间内CPU、磁盘和GPU对功耗的影响),0:非常低,1:低,2:中,3:高,4:非常高 | 166 | | LastUpdateTime | uint | 上次更新时间 | 167 | | UpdateTime | uint | 更新时间 | 168 | 169 | #### UpdateProcessList【0.0.1】 170 | 171 | | 字段名 | 数据类型 | 说明 | 172 | | --------- | -------------------- | -------- | 173 | | Processes | `List?` | 进程列表 | 174 | 175 | #### ChangeProcessList【0.0.1】 176 | 177 | | 字段名 | 数据类型 | 说明 | 178 | | ------ | -------- | ---- | 179 | | | | | 180 | 181 | #### Heartbeat【0.0.1】 182 | 183 | | 字段名 | 数据类型 | 说明 | 184 | | ------ | -------- | ---- | 185 | | | | | 186 | 187 | ### 3.2. UDP数据包【0.0.5】 188 | 189 | | 对象Id | 对象版本 | 对象名 | 说明 | 190 | | ------ | -------- | ------------------------- | -------------------- | 191 | | 200 | 1 | UpdateRealtimeProcessList | 更新进程实时数据列表 | 192 | | 201 | 1 | UpdateGeneralProcessList | 更新进程一般数据列表 | 193 | 194 | #### UpdateRealtimeProcessList【0.0.5】 195 | 196 | | 字段名 | 数据类型 | 说明 | 197 | | --------- | -------- | ------------------------------------------------------------ | 198 | | TotalSize | int | 总数据大小 | 199 | | PageSize | int | 分页大小 | 200 | | PageCount | int | 总页数 | 201 | | PageIndex | int | 页索引,客户端根据收到的进程ID列表、详细信息列表为基础,取当前数据包开始进程索引到结束进程索引进行数据更新 | 202 | | Cpus | byte[] | 一个进程占2字节(short) | 203 | | Memories | byte[] | 一个进程占2字节(short) | 204 | | Disks | byte[] | 一个进程占2字节(short) | 205 | | Networks | byte[] | 一个进程占2字节(short) | 206 | 207 | #### UpdateGeneralProcessList【0.0.5】 208 | 209 | | 字段名 | 数据类型 | 说明 | 210 | | --------------- | -------- | ------------------------------------------------------------ | 211 | | TotalSize | int | 总数据大小 | 212 | | PageSize | int | 分页大小 | 213 | | PageCount | int | 总页数 | 214 | | PageIndex | int | 页索引,客户端根据收到的进程ID列表、详细信息列表为基础,取当前数据包开始进程索引到结束进程索引进行数据更新 | 215 | | ProcessStatuses | byte[] | 进程状态,一个进程占1字节(byte) | 216 | | AlarmStatuses | byte[] | 告警状态,一个进程占1字节(byte) | 217 | | Gpus | byte[] | 一个进程占2字节(short) | 218 | | GpuEngines | byte[] | 一个进程占1字节(byte) | 219 | | PowerUsages | byte[] | 一个进程占1字节(byte) | 220 | | PowerUsageTrend | byte[] | 一个进程占1字节(byte) | 221 | | UpdateTimes | byte[] | 一个进程占4字节(byte) | 222 | 223 | ### 3.3. 部分枚举定义 224 | 225 | ```csharp 226 | /// 227 | /// 进程类型 228 | /// 229 | public enum ProcessType 230 | { 231 | [Description("应用")] Application, 232 | [Description("后台进程")] BackgroundProcess 233 | } 234 | 235 | /// 236 | /// 进程运行状态 237 | /// 238 | public enum ProcessStatus 239 | { 240 | [Description("新建状态")] New, 241 | [Description("就绪状态")] Ready, 242 | [Description("运行状态")] Running, 243 | [Description("阻塞状态")] Blocked, 244 | [Description("终止状态")] Terminated 245 | } 246 | 247 | /// 248 | /// GPU引擎 249 | /// 250 | public enum GpuEngine 251 | { 252 | [Description("无")] None, 253 | [Description("GPU 0 - 3D")] Gpu03D 254 | } 255 | 256 | /// 257 | /// 电源使用情况 258 | /// 259 | public enum ProcessPowerUsage 260 | { 261 | [Description("非常低")] VeryLow, 262 | [Description("低")] Low, 263 | [Description("中")] Moderate, 264 | [Description("高")] High, 265 | [Description("非常高")] VeryHigh 266 | } 267 | 268 | /// 269 | /// 进程告警状态(没有意义,只用于测试枚举位域使用) 270 | /// 271 | [Flags] 272 | public enum ProcessAlarmStatus 273 | { 274 | [Description("正常")] Normal = 0, 275 | [Description("超时")] Overtime = 1, 276 | [Description("超限")] OverLimit = 2, 277 | [Description("切换用户")] UserChanged = 4 278 | } 279 | ``` 280 | 281 | ## 4. 效果 282 | 283 | 服务端使用Avalonia UI开发: 284 | 285 | ![](imgs/server.gif) 286 | 287 | 客户端使用Avalonia UI开发: 288 | 289 | ![](imgs/client.gif) 290 | 291 | ## 5. 技术交流 292 | 293 | ### 5.1. 技术网站: 294 | 295 | - Https://dotnet9.com 296 | - Https://codewf.com 297 | - https://dotnetchat.com 298 | 299 | ### 5.2. 微信公众号 300 | 301 | | Dotnet9 | 快乐玩转技术 | 302 | | ---------------------------------------------------------- | ------------------------------------------------------------ | 303 | | ![Dotnet9](https://img1.dotnet9.com/site/wechatpublic.jpg) | ![快乐玩转技术](https://img1.dotnet9.com/site/wechatpublic1.jpg) | 304 | 305 | ### 5.3. 赞助 306 | 307 | | 微信支付 | 支付宝 | QQ支付 | 308 | | ------------------------------------------------ | --------------------------------------------- | -------------------------------------------- | 309 | | ![](https://img1.dotnet9.com/pays/WeChatPay.jpg) | ![](https://img1.dotnet9.com/pays/AliPay.jpg) | ![](https://img1.dotnet9.com/pays/QQPay.jpg) | 310 | 311 | -------------------------------------------------------------------------------- /imgs/client.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnet9/CsharpSocketTest/056932a9c4c1dd084bdcc9fd36167c11e4bf6895/imgs/client.gif -------------------------------------------------------------------------------- /imgs/server.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnet9/CsharpSocketTest/056932a9c4c1dd084bdcc9fd36167c11e4bf6895/imgs/server.gif -------------------------------------------------------------------------------- /src/ObjectBinarySerializationTest/SerializationTest/GlobalUsing.cs: -------------------------------------------------------------------------------- 1 | global using BenchmarkDotNet.Attributes; 2 | global using LoremNET; 3 | global using MessagePack; 4 | global using ProtoBuf; 5 | global using SerializationTest.Models; 6 | global using SerializationTest.SerializeUtils; 7 | global using SerializationTest.SerializeUtils.Helpers; 8 | global using SerializationTest.Test; 9 | global using System.Diagnostics; 10 | global using System.Reflection; 11 | global using System.Text; 12 | global using System.Text.Json; 13 | -------------------------------------------------------------------------------- /src/ObjectBinarySerializationTest/SerializationTest/Models/Department.cs: -------------------------------------------------------------------------------- 1 | namespace SerializationTest.Models; 2 | 3 | /// 4 | /// 部门 5 | /// 6 | [ProtoContract] 7 | [MessagePackObject] 8 | public class Department 9 | { 10 | /// 11 | /// Id 12 | /// 13 | [ProtoMember(1)] 14 | [Key(0)] 15 | public int Id { get; set; } 16 | 17 | /// 18 | /// 部门编码 19 | /// 20 | [ProtoMember(2)] 21 | [Key(1)] 22 | public string? Code { get; set; } 23 | 24 | /// 25 | /// 名称 26 | /// 27 | [ProtoMember(3)] 28 | [Key(2)] 29 | public string? Name { get; set; } 30 | 31 | /// 32 | /// 描述 33 | /// 34 | [ProtoMember(4)] 35 | [Key(3)] 36 | public string? Description { get; set; } 37 | 38 | /// 39 | /// 位置 40 | /// 41 | [ProtoMember(5)] 42 | [Key(4)] 43 | public string? Location { get; set; } 44 | 45 | /// 46 | /// 员工数量 47 | /// 48 | [ProtoMember(6)] 49 | [Key(5)] 50 | public int EmployeeCount { get; set; } 51 | 52 | /// 53 | /// 员工列表 54 | /// 55 | [ProtoMember(7)] 56 | [Key(6)] 57 | public List? Employees { get; set; } 58 | 59 | /// 60 | /// 预算 61 | /// 62 | [ProtoMember(8)] 63 | [Key(7)] 64 | public decimal Budget { get; set; } 65 | 66 | /// 67 | /// 未知 68 | /// 69 | [ProtoMember(9)] 70 | [Key(8)] 71 | public double Value { get; set; } 72 | 73 | /// 74 | /// 创建时间 75 | /// 76 | [ProtoMember(10)] 77 | [Key(9)] 78 | public long CreateTime { get; set; } 79 | } -------------------------------------------------------------------------------- /src/ObjectBinarySerializationTest/SerializationTest/Models/Employee.cs: -------------------------------------------------------------------------------- 1 | namespace SerializationTest.Models; 2 | 3 | /// 4 | /// 员工 5 | /// 6 | [ProtoContract] 7 | [MessagePackObject] 8 | public class Employee 9 | { 10 | /// 11 | /// Id 12 | /// 13 | [ProtoMember(1)] 14 | [Key(0)] 15 | public int Id { get; set; } 16 | 17 | 18 | /// 19 | /// 编码 20 | /// 21 | [ProtoMember(2)] 22 | [Key(1)] 23 | public string? Code { get; set; } 24 | 25 | /// 26 | /// 名 27 | /// 28 | [ProtoMember(3)] 29 | [Key(2)] 30 | public string? FirstName { get; set; } 31 | 32 | /// 33 | /// 姓 34 | /// 35 | [ProtoMember(4)] 36 | [Key(3)] 37 | public string? LastName { get; set; } 38 | 39 | /// 40 | /// 昵称 41 | /// 42 | [ProtoMember(5)] 43 | [Key(4)] 44 | public string? NickName { get; set; } 45 | 46 | /// 47 | /// 出生日期 48 | /// 49 | [ProtoMember(6)] 50 | [Key(5)] 51 | public long BirthDate { get; set; } 52 | 53 | /// 54 | /// 备注 55 | /// 56 | [ProtoMember(7)] 57 | [Key(6)] 58 | public string? Description { get; set; } 59 | 60 | /// 61 | /// 地址 62 | /// 63 | [ProtoMember(8)] 64 | [Key(7)] 65 | public string? Address { get; set; } 66 | 67 | /// 68 | /// 邮件 69 | /// 70 | [ProtoMember(9)] 71 | [Key(8)] 72 | public string? Email { get; set; } 73 | 74 | /// 75 | /// 电话号码 76 | /// 77 | [ProtoMember(10)] 78 | [Key(9)] 79 | public string? PhoneNumber { get; set; } 80 | 81 | /// 82 | /// 工资 83 | /// 84 | [ProtoMember(11)] 85 | [Key(10)] 86 | public decimal Salary { get; set; } 87 | 88 | /// 89 | /// 部门Id 90 | /// 91 | [ProtoMember(12)] 92 | [Key(11)] 93 | public decimal DepartmentId { get; set; } 94 | 95 | /// 96 | /// 入职时间 97 | /// 98 | [ProtoMember(13)] 99 | [Key(12)] 100 | public long EntryTime { get; set; } 101 | } -------------------------------------------------------------------------------- /src/ObjectBinarySerializationTest/SerializationTest/Models/Organization.cs: -------------------------------------------------------------------------------- 1 | namespace SerializationTest.Models; 2 | 3 | /// 4 | /// 组织 5 | /// 6 | [ProtoContract] 7 | [MessagePackObject] 8 | public class Organization 9 | { 10 | /// 11 | /// Id 12 | /// 13 | [ProtoMember(1)] 14 | [Key(0)] 15 | public int Id { get; set; } 16 | 17 | /// 18 | /// 名称 19 | /// 20 | [ProtoMember(2)] 21 | [Key(1)] 22 | public string? Name { get; set; } 23 | 24 | /// 25 | /// 标签 26 | /// 27 | [ProtoMember(3)] 28 | [Key(2)] 29 | public List? Tags { get; set; } 30 | 31 | /// 32 | /// 地址 33 | /// 34 | [ProtoMember(4)] 35 | [Key(3)] 36 | public string? Address { get; set; } 37 | 38 | /// 39 | /// 员工总数 40 | /// 41 | [ProtoMember(5)] 42 | [Key(4)] 43 | public int EmployeeCount { get; set; } 44 | 45 | /// 46 | /// 部门列表 47 | /// 48 | [ProtoMember(6)] 49 | [Key(5)] 50 | public List? Departments { get; set; } 51 | 52 | /// 53 | /// 年度预算 54 | /// 55 | [ProtoMember(7)] 56 | [Key(6)] 57 | public decimal AnnualBudget { get; set; } 58 | 59 | /// 60 | /// 成立日期,时间戳,单位ms 61 | /// 62 | [ProtoMember(8)] 63 | [Key(7)] 64 | public long FoundationDate { get; set; } 65 | } -------------------------------------------------------------------------------- /src/ObjectBinarySerializationTest/SerializationTest/Models/ProcessData.cs: -------------------------------------------------------------------------------- 1 | namespace SerializationTest.Models; 2 | 3 | public record ProcessData 4 | { 5 | /// 6 | /// 占10bit, CPU(所有内核的总处理利用率),最后一位表示小数位,比如253表示25.3% 7 | /// 8 | public short Cpu { get; set; } 9 | 10 | /// 11 | /// 占10bit, 内存(进程占用的物理内存),最后一位表示小数位,比如253表示25.3%,值可根据基本信息计算 12 | /// 13 | public short Memory { get; set; } 14 | 15 | /// 16 | /// 占10bit, 磁盘(所有物理驱动器的总利用率),最后一位表示小数位,比如253表示25.3%,值可根据基本信息计算 17 | /// 18 | public short Disk { get; set; } 19 | 20 | /// 21 | /// 占10bit, 网络(当前主要网络上的网络利用率),最后一位表示小数位,比如253表示25.3%,值可根据基本信息计算 22 | /// 23 | public short Network { get; set; } 24 | 25 | /// 26 | /// 占10bit, GPU(所有GPU引擎的最高利用率),最后一位表示小数位,比如253表示25.3 27 | /// 28 | public short Gpu { get; set; } 29 | 30 | /// 31 | /// 占1bit,GPU引擎,0:无,1:GPU 0 - 3D 32 | /// 33 | public byte GpuEngine { get; set; } 34 | 35 | /// 36 | /// 占3bit,电源使用情况(CPU、磁盘和GPU对功耗的影响),0:非常低,1:低,2:中,3:高,4:非常高 37 | /// 38 | public byte PowerUsage { get; set; } 39 | 40 | /// 41 | /// 占3bit,电源使用情况趋势(一段时间内CPU、磁盘和GPU对功耗的影响),0:非常低,1:低,2:中,3:高,4:非常高 42 | /// 43 | public byte PowerUsageTrend { get; set; } 44 | 45 | /// 46 | /// 占1bit,进程类型,0:应用,1:后台进程 47 | /// 48 | public byte Type { get; set; } 49 | 50 | /// 51 | /// 占1bit,进程状态,0:正常运行,1:效率模式,2:挂起 52 | /// 53 | public byte Status { get; set; } 54 | 55 | public byte[] Serialize() 56 | { 57 | var bytes = new byte[8]; 58 | 59 | // Cpu 60 | bytes[0] = (byte)(Cpu >> 2); 61 | bytes[1] = (byte)(((Cpu & 0x03) << 6) | (Cpu >> 4)); 62 | 63 | // Memory 64 | bytes[2] = (byte)(((Memory & 0x0F) << 4) | (Memory >> 6)); 65 | 66 | // Disk 67 | bytes[3] = (byte)(((Disk & 0x3F) << 2) | (Disk >> 8)); 68 | 69 | // Network 70 | bytes[4] = (byte)(Network & 0xFF); 71 | 72 | // Gpu 73 | bytes[5] = (byte)(Gpu >> 2); 74 | bytes[6] = (byte)((Gpu & 0x03) << 6); 75 | 76 | return bytes; 77 | } 78 | 79 | public static ProcessData Deserialize(byte[] buffer) 80 | { 81 | return new ProcessData 82 | { 83 | Cpu = (short)((buffer[0] << 2) | (buffer[1] >> 6)), 84 | Memory = (short)(((buffer[1] & 0x3F) << 4) | (buffer[2] >> 4)), 85 | Disk = (short)(((buffer[2] & 0x0F) << 6) | (buffer[3] >> 2)), 86 | Network = (short)(((buffer[3] & 0x03) << 8) | buffer[4]), 87 | Gpu = (short)((buffer[5] << 2) | (buffer[6] >> 6)) 88 | }; 89 | } 90 | } -------------------------------------------------------------------------------- /src/ObjectBinarySerializationTest/SerializationTest/Models/RequestOrganizations.cs: -------------------------------------------------------------------------------- 1 | namespace SerializationTest.Models; 2 | 3 | [ProtoContract] 4 | [MessagePackObject] 5 | public class RequestOrganizations 6 | { 7 | } -------------------------------------------------------------------------------- /src/ObjectBinarySerializationTest/SerializationTest/Models/ResponseOrganizations.cs: -------------------------------------------------------------------------------- 1 | namespace SerializationTest.Models; 2 | 3 | [ProtoContract] 4 | [MessagePackObject] 5 | public class ResponseOrganizations 6 | { 7 | /// 8 | /// Id 9 | /// 10 | [ProtoMember(1)] 11 | [Key(0)] 12 | public List? Organizations { get; set; } 13 | } -------------------------------------------------------------------------------- /src/ObjectBinarySerializationTest/SerializationTest/Program.cs: -------------------------------------------------------------------------------- 1 | // 运行基准测试 2 | //BenchmarkRunner.Run(); 3 | 4 | // 普通测试 5 | //BenchmarkTest.Test(); 6 | 7 | BenchmarkTest.TestBit(); 8 | Console.ReadKey(); -------------------------------------------------------------------------------- /src/ObjectBinarySerializationTest/SerializationTest/SerializationTest.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net10.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/ObjectBinarySerializationTest/SerializationTest/SerializeUtils/Helpers/CustomSerializeHelper.cs: -------------------------------------------------------------------------------- 1 | namespace SerializationTest.SerializeUtils.Helpers; 2 | 3 | public class CustomSerializeHelper : ISerializeHelper 4 | { 5 | private static readonly Dictionary> ObjectPropertyInfos = new(); 6 | private static readonly List ComplexTypeNames; 7 | 8 | static CustomSerializeHelper() 9 | { 10 | ComplexTypeNames = new List 11 | { 12 | typeof(List<>).Name, 13 | typeof(Dictionary<,>).Name 14 | }; 15 | } 16 | 17 | private static Encoding DefaultEncoding { get; } = Encoding.UTF8; 18 | 19 | public byte[] Serialize(T data) 20 | { 21 | using var stream = new MemoryStream(); 22 | using var writer = new BinaryWriter(stream, DefaultEncoding); 23 | 24 | var type = typeof(T); 25 | writer.Write(type.Name); 26 | Serialize(writer, data); 27 | 28 | return stream.ToArray(); 29 | } 30 | 31 | public T? Deserialize(byte[] buffer) 32 | { 33 | using var stream = new MemoryStream(buffer); 34 | using var reader = new BinaryReader(stream); 35 | 36 | var data = Activator.CreateInstance(); 37 | var name = reader.ReadString(); 38 | Deserialize(reader, data); 39 | 40 | return data; 41 | } 42 | 43 | 44 | private static List GetProperties(Type type) 45 | { 46 | var objectName = type.Name; 47 | if (ObjectPropertyInfos.TryGetValue(objectName, out var propertyInfos)) return propertyInfos; 48 | 49 | propertyInfos = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList(); 50 | ObjectPropertyInfos[objectName] = propertyInfos; 51 | return propertyInfos; 52 | } 53 | 54 | #region 序列化操作 55 | 56 | private static void Serialize(BinaryWriter writer, T data) 57 | { 58 | var properties = GetProperties(data!.GetType()); 59 | foreach (var property in properties) Serialize(writer, data, property); 60 | } 61 | 62 | private static void Serialize(BinaryWriter writer, T data, PropertyInfo property) 63 | { 64 | var propertyType = property.PropertyType; 65 | var propertyValue = property.GetValue(data, null); 66 | Serialize(writer, propertyValue, propertyType); 67 | } 68 | 69 | private static void Serialize(BinaryWriter writer, object? value, Type valueType) 70 | { 71 | var propertyName = valueType.Name; 72 | if (valueType.IsPrimitive 73 | || valueType.BaseType == typeof(ValueType) 74 | || valueType == typeof(string) 75 | || valueType == typeof(byte[])) 76 | SerializeBase(writer, value, valueType); 77 | else if (ComplexTypeNames.Contains(propertyName)) 78 | SerializeComplex(writer, value, valueType); 79 | else 80 | Serialize(writer, value); 81 | } 82 | 83 | 84 | private static void SerializeBase(BinaryWriter writer, object? value, Type valueType) 85 | { 86 | if (valueType == typeof(byte)) 87 | writer.Write(value == null ? default : byte.Parse(value.ToString()!)); 88 | else if (valueType == typeof(short)) 89 | writer.Write(value == null ? default : short.Parse(value.ToString()!)); 90 | else if (valueType == typeof(int)) 91 | writer.Write(value == null ? default : int.Parse(value.ToString()!)); 92 | else if (valueType == typeof(long)) 93 | writer.Write(value == null ? default : long.Parse(value.ToString()!)); 94 | else if (valueType == typeof(double)) 95 | writer.Write(value == null ? default : double.Parse(value.ToString()!)); 96 | else if (valueType == typeof(decimal)) 97 | writer.Write(value == null ? default : decimal.Parse(value.ToString()!)); 98 | else if (valueType == typeof(string)) writer.Write(value == null ? string.Empty : value.ToString()!); 99 | } 100 | 101 | private static void SerializeComplex(BinaryWriter writer, object? value, Type valueType) 102 | { 103 | var propertyName = valueType.Name; 104 | var count = 0; 105 | if (value == null) 106 | { 107 | writer.Write(count); 108 | return; 109 | } 110 | 111 | var genericArguments = valueType.GetGenericArguments(); 112 | dynamic dynamicValue = value; 113 | count = dynamicValue.Count; 114 | writer.Write(count); 115 | if (propertyName.Equals(typeof(List<>).Name)) 116 | foreach (var item in dynamicValue) 117 | Serialize(writer, item, genericArguments[0]); 118 | else 119 | foreach (var item in dynamicValue) 120 | { 121 | Serialize(writer, item.Key, genericArguments[0]); 122 | Serialize(writer, item.Value, genericArguments[1]); 123 | } 124 | } 125 | 126 | #endregion 127 | 128 | #region 反序列化操作 129 | 130 | private static void Deserialize(BinaryReader reader, T data) 131 | { 132 | var properties = GetProperties(data!.GetType()); 133 | foreach (var property in properties) 134 | { 135 | var value = DeserializeByType(reader, property.PropertyType); 136 | property.SetValue(data, value); 137 | } 138 | } 139 | 140 | private static object? DeserializeByType(BinaryReader reader, Type propertyType) 141 | { 142 | var propertyName = propertyType.Name; 143 | object? value; 144 | if (propertyType.IsPrimitive 145 | || propertyType.BaseType == typeof(ValueType) 146 | || propertyType == typeof(string) 147 | || propertyType == typeof(byte[])) 148 | value = DeserializeBase(reader, propertyType); 149 | else if (ComplexTypeNames.Contains(propertyName)) 150 | value = DeserializeComplex(reader, propertyType); 151 | else 152 | value = DeserializeClass(reader, propertyType); 153 | 154 | return value; 155 | } 156 | 157 | private static object DeserializeBase(BinaryReader reader, Type propertyType) 158 | { 159 | object value; 160 | if (propertyType == typeof(byte)) 161 | value = reader.ReadByte(); 162 | else if (propertyType == typeof(short)) 163 | value = reader.ReadInt16(); 164 | else if (propertyType == typeof(int)) 165 | value = reader.ReadInt32(); 166 | else if (propertyType == typeof(long)) 167 | value = reader.ReadInt64(); 168 | else if (propertyType == typeof(double)) 169 | value = reader.ReadDouble(); 170 | else if (propertyType == typeof(decimal)) 171 | value = reader.ReadDecimal(); 172 | else if (propertyType == typeof(string)) 173 | value = reader.ReadString(); 174 | else 175 | throw new Exception($"暂时未支持数据类型:{propertyType.Name}"); 176 | 177 | return value; 178 | } 179 | 180 | private static object? DeserializeComplex(BinaryReader reader, Type propertyType) 181 | { 182 | var complexObj = Activator.CreateInstance(propertyType); 183 | var count = reader.ReadInt32(); 184 | var addMethod = propertyType.GetMethod("Add")!; 185 | var genericArguments = propertyType.GetGenericArguments(); 186 | for (var i = 0; i < count; i++) 187 | { 188 | var key = DeserializeByType(reader, genericArguments[0]); 189 | if (genericArguments.Length == 1) 190 | { 191 | addMethod.Invoke(complexObj, [key]); 192 | } 193 | else if (genericArguments.Length == 2) 194 | { 195 | var value = DeserializeByType(reader, genericArguments[1]); 196 | addMethod.Invoke(complexObj, [key, value]); 197 | } 198 | } 199 | 200 | return complexObj; 201 | } 202 | 203 | private static object? DeserializeClass(BinaryReader reader, Type type) 204 | { 205 | var data = Activator.CreateInstance(type); 206 | Deserialize(reader, data); 207 | return data; 208 | } 209 | 210 | #endregion 211 | } -------------------------------------------------------------------------------- /src/ObjectBinarySerializationTest/SerializationTest/SerializeUtils/Helpers/JsonSerializeHelper.cs: -------------------------------------------------------------------------------- 1 | namespace SerializationTest.SerializeUtils.Helpers; 2 | 3 | public class JsonSerializeHelper : ISerializeHelper 4 | { 5 | public byte[] Serialize(T data) 6 | { 7 | return JsonSerializer.SerializeToUtf8Bytes(data); 8 | } 9 | 10 | public T? Deserialize(byte[] buffer) 11 | { 12 | return JsonSerializer.Deserialize(buffer); 13 | } 14 | } -------------------------------------------------------------------------------- /src/ObjectBinarySerializationTest/SerializationTest/SerializeUtils/Helpers/MessagePackSerializeHelper.cs: -------------------------------------------------------------------------------- 1 | using MessagePack.Resolvers; 2 | 3 | namespace SerializationTest.SerializeUtils.Helpers; 4 | 5 | /// 6 | /// 标准带压缩:这种方式需要在类和字段上添加特性 7 | /// 8 | public class MessagePackStandardWithCompressionSerializeHelper : ISerializeHelper 9 | { 10 | private readonly MessagePackSerializerOptions _options = 11 | MessagePackSerializerOptions.Standard.WithCompression(MessagePackCompression.Lz4BlockArray); 12 | 13 | public byte[] Serialize(T data) 14 | { 15 | return MessagePackSerializer.Serialize(data, _options); 16 | } 17 | 18 | public T Deserialize(byte[] buffer) 19 | { 20 | return MessagePackSerializer.Deserialize(buffer, _options); 21 | } 22 | } 23 | 24 | /// 25 | /// 标准不带压缩:这种方式需要在类和字段上添加特性 26 | /// 27 | public class MessagePackStandardWithOutCompressionSerializeHelper : ISerializeHelper 28 | { 29 | private readonly MessagePackSerializerOptions _options = MessagePackSerializerOptions.Standard; 30 | 31 | public byte[] Serialize(T data) 32 | { 33 | return MessagePackSerializer.Serialize(data, _options); 34 | } 35 | 36 | public T Deserialize(byte[] buffer) 37 | { 38 | return MessagePackSerializer.Deserialize(buffer, _options); 39 | } 40 | } 41 | 42 | /// 43 | /// 新推功能带压缩:这种方式不需要给传输对象添加特性 44 | /// 45 | public class MessagePackContractlessStandardResolverWithCompressionSerializeHelper : ISerializeHelper 46 | { 47 | private readonly MessagePackSerializerOptions _options = 48 | ContractlessStandardResolver.Options.WithCompression(MessagePackCompression 49 | .Lz4BlockArray); 50 | 51 | public byte[] Serialize(T data) 52 | { 53 | return MessagePackSerializer.Serialize(data, _options); 54 | } 55 | 56 | public T Deserialize(byte[] buffer) 57 | { 58 | return MessagePackSerializer.Deserialize(buffer, _options); 59 | } 60 | } 61 | 62 | /// 63 | /// 新推功能不带压缩:这种方式不需要给传输对象添加特性 64 | /// 65 | public class MessagePackContractlessStandardResolverWithOutCompressionSerializeHelper : ISerializeHelper 66 | { 67 | private readonly MessagePackSerializerOptions _options = 68 | ContractlessStandardResolver.Options; 69 | 70 | public byte[] Serialize(T data) 71 | { 72 | return MessagePackSerializer.Serialize(data, _options); 73 | } 74 | 75 | public T Deserialize(byte[] buffer) 76 | { 77 | return MessagePackSerializer.Deserialize(buffer, _options); 78 | } 79 | } -------------------------------------------------------------------------------- /src/ObjectBinarySerializationTest/SerializationTest/SerializeUtils/Helpers/ProtobufSerializeHelper.cs: -------------------------------------------------------------------------------- 1 | namespace SerializationTest.SerializeUtils.Helpers; 2 | 3 | public class ProtoBufSerializeHelper : ISerializeHelper 4 | { 5 | public byte[] Serialize(T data) 6 | { 7 | using var stream = new MemoryStream(); 8 | Serializer.Serialize(stream, data); 9 | return stream.ToArray(); 10 | } 11 | 12 | public T Deserialize(byte[] buffer) 13 | { 14 | using var stream = new MemoryStream(buffer); 15 | return Serializer.Deserialize(stream); 16 | } 17 | } -------------------------------------------------------------------------------- /src/ObjectBinarySerializationTest/SerializationTest/SerializeUtils/ISerializeHelper.cs: -------------------------------------------------------------------------------- 1 | namespace SerializationTest.SerializeUtils; 2 | 3 | public interface ISerializeHelper 4 | { 5 | byte[] Serialize(T data); 6 | 7 | T? Deserialize(byte[] buffer); 8 | } -------------------------------------------------------------------------------- /src/ObjectBinarySerializationTest/SerializationTest/Test/BenchmarkTest.cs: -------------------------------------------------------------------------------- 1 | using CodeWF.Tools.Extensions; 2 | using MessagePack.Resolvers; 3 | 4 | namespace SerializationTest.Test; 5 | 6 | [MemoryDiagnoser] 7 | [RankColumn] 8 | public class BenchmarkTest 9 | { 10 | /// 11 | /// 测试数据量 12 | /// 13 | private const int MockCount = 100; 14 | 15 | private static readonly Random RandomShared = new(DateTime.Now.Millisecond); 16 | 17 | static BenchmarkTest() 18 | { 19 | MockData = new ResponseOrganizations 20 | { 21 | Organizations = Enumerable.Range(0, MockCount).Select(orgIndex => new Organization 22 | { 23 | Id = orgIndex, 24 | Name = $"Name{orgIndex}", 25 | Tags = Enumerable.Range(RandomShared.Next(0, 5), RandomShared.Next(10, 15)) 26 | .Select(tagIndex => $"标签{tagIndex}") 27 | .ToList(), 28 | Address = $"地址{orgIndex}", 29 | EmployeeCount = RandomShared.Next(10, 1000), 30 | Departments = Enumerable.Range(2, 10).Select(i => new Department 31 | { 32 | Id = i, 33 | Code = $"D{Lorem.Words(1, 3)}", 34 | Name = $"部门{Lorem.Words(1, 3)}", 35 | Description = $"描述{Lorem.Words(1, 3)}", 36 | Location = $"位置{Lorem.Words(1, 3)}", 37 | EmployeeCount = RandomShared.Next(5, 100), 38 | Employees = Enumerable.Range(10, 100).Select(empIndex => new Employee 39 | { 40 | Id = empIndex, 41 | Code = $"E{Lorem.Words(1, 3)}", 42 | FirstName = $"名{Lorem.Words(1, 3)}", 43 | LastName = $"姓{Lorem.Words(1, 3)}", 44 | NickName = $"昵称{Lorem.Words(1, 3)}", 45 | BirthDate = DateTime.Now.AddMilliseconds(-1 * RandomShared.Next(500000, 500000000)) 46 | .GetUnixTimeMilliseconds(), 47 | Description = $"描述{Lorem.Words(1, 3)}", 48 | Address = $"地址{Lorem.Words(1, 3)}", 49 | Email = $"邮件{Lorem.Words(1, 3)}@dotnet9.com", 50 | PhoneNumber = RandomShared.Next(1000000, 999999999).ToString(), 51 | Salary = RandomShared.Next(2000, 100000), 52 | DepartmentId = i, 53 | EntryTime = DateTime.Now.AddMilliseconds(-1 * RandomShared.Next(500000, 500000000)) 54 | .GetUnixTimeMilliseconds() 55 | }).ToList(), 56 | Budget = RandomShared.Next(2000, 100000) + (decimal)RandomShared.NextDouble(), 57 | Value = RandomShared.NextDouble(), 58 | CreateTime = DateTime.Now.AddMilliseconds(-1 * RandomShared.Next(500000, 500000000)) 59 | .GetUnixTimeMilliseconds() 60 | }).ToList(), 61 | AnnualBudget = RandomShared.Next(20000, 1000000) + (decimal)RandomShared.NextDouble(), 62 | FoundationDate = DateTime.Now.AddMilliseconds(-1 * RandomShared.Next(500000, 500000000)) 63 | .GetUnixTimeMilliseconds() 64 | }).ToList() 65 | }; 66 | 67 | MockDpartment = new Department 68 | { 69 | Id = DateTime.Now.Millisecond, 70 | Code = $"D{Lorem.Words(1, 3)}", 71 | Name = $"部门{Lorem.Words(1, 3)}", 72 | Description = $"描述{Lorem.Words(1, 3)}", 73 | Location = $"位置{Lorem.Words(1, 3)}", 74 | EmployeeCount = RandomShared.Next(5, 100), 75 | Employees = Enumerable.Range(0, 10000).Select(empIndex => new Employee 76 | { 77 | Id = empIndex, 78 | Code = $"E{Lorem.Words(1, 3)}", 79 | FirstName = $"名{Lorem.Words(1, 3)}", 80 | LastName = $"姓{Lorem.Words(1, 3)}", 81 | NickName = $"昵称{Lorem.Words(1, 3)}", 82 | BirthDate = DateTime.Now.AddMilliseconds(-1 * RandomShared.Next(500000, 500000000)).GetUnixTimeMilliseconds(), 83 | Description = $"描述{Lorem.Words(1, 3)}", 84 | Address = $"地址{Lorem.Words(1, 3)}", 85 | Email = $"邮件{Lorem.Words(1, 3)}@dotnet9.com", 86 | PhoneNumber = RandomShared.Next(1000000, 999999999).ToString(), 87 | Salary = RandomShared.Next(2000, 100000), 88 | DepartmentId = 3, 89 | EntryTime = DateTime.Now.AddMilliseconds(-1 * RandomShared.Next(500000, 500000000)).GetUnixTimeMilliseconds() 90 | }).ToList(), 91 | Budget = RandomShared.Next(2000, 100000) + (decimal)RandomShared.NextDouble(), 92 | Value = RandomShared.NextDouble(), 93 | CreateTime = DateTime.Now.AddMilliseconds(-1 * RandomShared.Next(500000, 500000000)).GetUnixTimeMilliseconds() 94 | }; 95 | } 96 | 97 | /// 98 | /// 测试数据 99 | /// 100 | private static ResponseOrganizations MockData { get; } 101 | 102 | /// 103 | /// 测试数据 104 | /// 105 | private static Department MockDpartment { get; } 106 | 107 | 108 | //[Benchmark] 109 | //public void JsonByteSerialize() 110 | //{ 111 | // RunSerialize(new JsonSerializeHelper()); 112 | //} 113 | 114 | [Benchmark] 115 | public void CustomSerialize() 116 | { 117 | RunSerialize(new CustomSerializeHelper()); 118 | } 119 | 120 | [Benchmark] 121 | public void ProtoBufSerialize() 122 | { 123 | RunSerialize(new ProtoBufSerializeHelper()); 124 | } 125 | 126 | [Benchmark] 127 | public void MessagePackStandardWithCompressionSerializeHelper() 128 | { 129 | RunSerialize(new MessagePackStandardWithCompressionSerializeHelper()); 130 | } 131 | 132 | [Benchmark] 133 | public void MessagePackStandardWithOutCompressionSerializeHelper() 134 | { 135 | RunSerialize(new MessagePackStandardWithOutCompressionSerializeHelper()); 136 | } 137 | 138 | [Benchmark] 139 | public void MessagePackContractlessStandardResolverWithCompressionSerializeHelper() 140 | { 141 | RunSerialize(new MessagePackContractlessStandardResolverWithCompressionSerializeHelper()); 142 | } 143 | 144 | [Benchmark] 145 | public void MessagePackContractlessStandardResolverWithOutCompressionSerializeHelper() 146 | { 147 | RunSerialize(new MessagePackContractlessStandardResolverWithOutCompressionSerializeHelper()); 148 | } 149 | 150 | 151 | /// 152 | /// 简单测试 153 | /// 154 | public static void Test(List? moreHelpers = null) 155 | { 156 | MessagePackSerializer.DefaultOptions = ContractlessStandardResolver.Options; 157 | var serializeHelpers = new List 158 | { 159 | new CustomSerializeHelper(), 160 | new ProtoBufSerializeHelper(), 161 | new MessagePackStandardWithCompressionSerializeHelper(), 162 | new MessagePackStandardWithOutCompressionSerializeHelper(), 163 | new MessagePackContractlessStandardResolverWithCompressionSerializeHelper(), 164 | new MessagePackContractlessStandardResolverWithOutCompressionSerializeHelper() 165 | }; 166 | if (moreHelpers?.Count() > 0) serializeHelpers.AddRange(moreHelpers); 167 | 168 | serializeHelpers.ForEach(RunSerialize); 169 | } 170 | 171 | 172 | private static void RunSerialize(ISerializeHelper helper) 173 | { 174 | var sw = Stopwatch.StartNew(); 175 | 176 | var buffer = helper.Serialize(MockDpartment); 177 | 178 | sw.Stop(); 179 | Log($"{helper.GetType().Name} Serialize {sw.ElapsedMilliseconds}ms {buffer.Length}byte"); 180 | 181 | sw.Restart(); 182 | 183 | var data = helper.Deserialize(buffer); 184 | 185 | sw.Stop(); 186 | 187 | Log($"{helper.GetType().Name} Deserialize {sw.ElapsedMilliseconds}ms {data?.Employees?.Count}项"); 188 | } 189 | 190 | private static void Log(string log) 191 | { 192 | Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss fff}: {log}"); 193 | } 194 | 195 | public static void TestBit() 196 | { 197 | var processData = new ProcessData 198 | { 199 | Cpu = 253, Memory = 510, Disk = 32, Network = 323, Gpu = 32, GpuEngine = 1, PowerUsage = 3, 200 | PowerUsageTrend = 2, Type = 1, Status = 1 201 | }; 202 | var serializedData = processData.Serialize(); // Serialize to byte array 203 | var deserializedData = ProcessData.Deserialize(serializedData); 204 | if (deserializedData.Cpu == processData.Cpu && deserializedData.Memory == processData.Memory) 205 | Console.WriteLine("success"); 206 | } 207 | } -------------------------------------------------------------------------------- /src/SocketTest.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.8.34330.188 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ObjectBinarySerializationTest", "ObjectBinarySerializationTest", "{49C052ED-5F1C-4834-8310-F0D425A354F7}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SerializationTest", "ObjectBinarySerializationTest\SerializationTest\SerializationTest.csproj", "{849FB784-B220-4F6F-ADAE-15448873BFB1}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SocketTesting", "SocketTesting", "{CB845ECA-47B9-452D-A404-4DE8E835C2D9}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SocketDto", "SocketTesting\SocketDto\SocketDto.csproj", "{0CC6BAFC-F920-4AB1-ADB1-D44380AEC17D}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SocketDto.Test", "SocketTesting\SocketDto.Test\SocketDto.Test.csproj", "{9CCC071C-CADC-4C50-814D-5779726CFC5F}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SocketTest.Client", "SocketTesting\SocketTest.Client\SocketTest.Client.csproj", "{04E8952A-83DF-4875-A7FC-AA4C57FE3085}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SocketTest.Server", "SocketTesting\SocketTest.Server\SocketTest.Server.csproj", "{349503F8-DFF0-4FBF-9680-5ADAD4EFF733}" 19 | EndProject 20 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Application", "Application", "{2467F89A-512D-4A94-A97E-2EACE1004449}" 21 | EndProject 22 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "解决方案项", "解决方案项", "{FBD28AA3-F56E-4EC7-98BC-BC752D454878}" 23 | ProjectSection(SolutionItems) = preProject 24 | ..\README.md = ..\README.md 25 | EndProjectSection 26 | EndProject 27 | Global 28 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 29 | Debug|Any CPU = Debug|Any CPU 30 | Release|Any CPU = Release|Any CPU 31 | EndGlobalSection 32 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 33 | {849FB784-B220-4F6F-ADAE-15448873BFB1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {849FB784-B220-4F6F-ADAE-15448873BFB1}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {849FB784-B220-4F6F-ADAE-15448873BFB1}.Release|Any CPU.ActiveCfg = Release|Any CPU 36 | {849FB784-B220-4F6F-ADAE-15448873BFB1}.Release|Any CPU.Build.0 = Release|Any CPU 37 | {0CC6BAFC-F920-4AB1-ADB1-D44380AEC17D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {0CC6BAFC-F920-4AB1-ADB1-D44380AEC17D}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {0CC6BAFC-F920-4AB1-ADB1-D44380AEC17D}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {0CC6BAFC-F920-4AB1-ADB1-D44380AEC17D}.Release|Any CPU.Build.0 = Release|Any CPU 41 | {9CCC071C-CADC-4C50-814D-5779726CFC5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 42 | {9CCC071C-CADC-4C50-814D-5779726CFC5F}.Debug|Any CPU.Build.0 = Debug|Any CPU 43 | {9CCC071C-CADC-4C50-814D-5779726CFC5F}.Release|Any CPU.ActiveCfg = Release|Any CPU 44 | {9CCC071C-CADC-4C50-814D-5779726CFC5F}.Release|Any CPU.Build.0 = Release|Any CPU 45 | {04E8952A-83DF-4875-A7FC-AA4C57FE3085}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 46 | {04E8952A-83DF-4875-A7FC-AA4C57FE3085}.Debug|Any CPU.Build.0 = Debug|Any CPU 47 | {04E8952A-83DF-4875-A7FC-AA4C57FE3085}.Release|Any CPU.ActiveCfg = Release|Any CPU 48 | {04E8952A-83DF-4875-A7FC-AA4C57FE3085}.Release|Any CPU.Build.0 = Release|Any CPU 49 | {349503F8-DFF0-4FBF-9680-5ADAD4EFF733}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 50 | {349503F8-DFF0-4FBF-9680-5ADAD4EFF733}.Debug|Any CPU.Build.0 = Debug|Any CPU 51 | {349503F8-DFF0-4FBF-9680-5ADAD4EFF733}.Release|Any CPU.ActiveCfg = Release|Any CPU 52 | {349503F8-DFF0-4FBF-9680-5ADAD4EFF733}.Release|Any CPU.Build.0 = Release|Any CPU 53 | EndGlobalSection 54 | GlobalSection(SolutionProperties) = preSolution 55 | HideSolutionNode = FALSE 56 | EndGlobalSection 57 | GlobalSection(NestedProjects) = preSolution 58 | {849FB784-B220-4F6F-ADAE-15448873BFB1} = {49C052ED-5F1C-4834-8310-F0D425A354F7} 59 | {0CC6BAFC-F920-4AB1-ADB1-D44380AEC17D} = {CB845ECA-47B9-452D-A404-4DE8E835C2D9} 60 | {9CCC071C-CADC-4C50-814D-5779726CFC5F} = {CB845ECA-47B9-452D-A404-4DE8E835C2D9} 61 | {04E8952A-83DF-4875-A7FC-AA4C57FE3085} = {2467F89A-512D-4A94-A97E-2EACE1004449} 62 | {349503F8-DFF0-4FBF-9680-5ADAD4EFF733} = {2467F89A-512D-4A94-A97E-2EACE1004449} 63 | {2467F89A-512D-4A94-A97E-2EACE1004449} = {CB845ECA-47B9-452D-A404-4DE8E835C2D9} 64 | EndGlobalSection 65 | GlobalSection(ExtensibilityGlobals) = postSolution 66 | SolutionGuid = {9799BEAD-32FD-45CD-9B68-124237176477} 67 | EndGlobalSection 68 | EndGlobal 69 | -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto.Test/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using Xunit; 2 | -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto.Test/NumberFormatUnitTest.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Test; 2 | 3 | public class NumberFormatUnitTest 4 | { 5 | private const int Max = 10000; 6 | private const double Min = 0.0001; 7 | 8 | [Fact] 9 | public void Test_NumberToString_Success() 10 | { 11 | var strIntMax = NumberToString(20000); 12 | var strIntCenter = NumberToString(999); 13 | var strIntZero = NumberToString(0); 14 | var strDoubleMax = NumberToString(32983.33223); 15 | var strDoubleCenter = NumberToString(32.358953); 16 | var strDoubleZero = NumberToString(0.00); 17 | var strDoubleSmallThan1 = NumberToString(0.330); 18 | var strDoubleGegative1 = NumberToString(-0.32853); 19 | var strDoubleGegative2 = NumberToString(-0.0001); 20 | var strDoubleGegative3 = NumberToString(-0.00001); 21 | var strDoubleGegative4 = NumberToString(-0.000003235); 22 | 23 | Assert.Equal("0", strIntZero); 24 | } 25 | 26 | 27 | string NumberToString(int number) 28 | { 29 | if (Math.Abs(number) > Max) 30 | { 31 | return number.ToString("0.00e+00"); 32 | } 33 | 34 | return $"{number}"; 35 | } 36 | 37 | string NumberToString(double number) 38 | { 39 | if (number != 0.0 && (Math.Abs(number) > Max || Math.Abs(number) < Min)) 40 | { 41 | return number.ToString("0.00e+00"); 42 | } 43 | 44 | return $"{number}"; 45 | } 46 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto.Test/ResponseProcessListUnitTest.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnet9/CsharpSocketTest/056932a9c4c1dd084bdcc9fd36167c11e4bf6895/src/SocketTesting/SocketDto.Test/ResponseProcessListUnitTest.cs -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto.Test/SocketDto.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net10.0 5 | enable 6 | enable 7 | 8 | false 9 | true 10 | 11 | 12 | 13 | 14 | 15 | 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | all 18 | 19 | 20 | runtime; build; native; contentfiles; analyzers; buildtransitive 21 | all 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto.Test/SocketDtoUnitTest.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnet9/CsharpSocketTest/056932a9c4c1dd084bdcc9fd36167c11e4bf6895/src/SocketTesting/SocketDto.Test/SocketDtoUnitTest.cs -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto.Test/SystemProcessUnitTest.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnet9/CsharpSocketTest/056932a9c4c1dd084bdcc9fd36167c11e4bf6895/src/SocketTesting/SocketDto.Test/SystemProcessUnitTest.cs -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto.Test/UpdateGeneralProcessListUnitTest.cs: -------------------------------------------------------------------------------- 1 | using SocketDto.Enums; 2 | 3 | namespace SocketDto.Test; 4 | 5 | public class UpdateGeneralProcessListUnitTest 6 | { 7 | [Fact] 8 | public void Test_SerializeProcessItemData_Success() 9 | { 10 | Assert.Equal(0, (int)AlarmStatus.Normal); 11 | Assert.Equal(1, (int)AlarmStatus.Overtime); 12 | Assert.Equal(2, (int)AlarmStatus.OverLimit); 13 | Assert.Equal(3, (int)(AlarmStatus.Overtime | AlarmStatus.OverLimit)); 14 | Assert.Equal(4, (int)AlarmStatus.UserChanged); 15 | Assert.Equal(5, (int)(AlarmStatus.Overtime | AlarmStatus.UserChanged)); 16 | Assert.Equal(6, (int)(AlarmStatus.OverLimit | AlarmStatus.UserChanged)); 17 | Assert.Equal(7, 18 | (int)(AlarmStatus.Overtime | AlarmStatus.OverLimit | AlarmStatus.UserChanged)); 19 | Assert.Equal(7, 20 | (int)(AlarmStatus.Overtime | AlarmStatus.Overtime | AlarmStatus.Overtime | AlarmStatus.OverLimit | 21 | AlarmStatus.Overtime | AlarmStatus.UserChanged)); 22 | const AlarmStatus status = AlarmStatus.Overtime | AlarmStatus.OverLimit | AlarmStatus.UserChanged; 23 | Assert.Equal((int)AlarmStatus.Overtime, (int)(AlarmStatus.Overtime & status)); 24 | Assert.Equal((int)AlarmStatus.OverLimit, (int)(AlarmStatus.OverLimit & status)); 25 | Assert.Equal((int)AlarmStatus.UserChanged, (int)(AlarmStatus.UserChanged & status)); 26 | } 27 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/AutoCommand/ChangeProcessList.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.AutoCommand; 2 | 3 | /// 4 | /// 进程结构信息 5 | /// 6 | [NetHead(12, 1)] 7 | public class ChangeProcessList : INetObject 8 | { 9 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/AutoCommand/UpdateProcessList.cs: -------------------------------------------------------------------------------- 1 | using SocketDto.Response; 2 | 3 | namespace SocketDto.AutoCommand; 4 | 5 | /// 6 | /// 更新进程信息 7 | /// 8 | [NetHead(11, 1)] 9 | public class UpdateProcessList : INetObject 10 | { 11 | /// 12 | /// 进程列表 13 | /// 14 | public List? Processes { get; set; } 15 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Enums/AlarmStatus.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Enums; 2 | 3 | /// 4 | /// 进程告警状态(没有意义,只用于测试枚举位域使用) 5 | /// 6 | [Flags] 7 | public enum AlarmStatus 8 | { 9 | [Description("正常")] Normal = 0, 10 | [Description("超时")] Overtime = 1, 11 | [Description("超限")] OverLimit = 2, 12 | [Description("切换用户")] UserChanged = 4 13 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Enums/GpuEngine.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Enums; 2 | 3 | /// 4 | /// GPU引擎 5 | /// 6 | public enum GpuEngine 7 | { 8 | [Description("无")] None, 9 | [Description("GPU 0 - 3D")] Gpu03D 10 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Enums/PowerUsage.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Enums; 2 | 3 | /// 4 | /// 电源使用情况 5 | /// 6 | public enum PowerUsage 7 | { 8 | [Description("非常低")] VeryLow, 9 | [Description("低")] Low, 10 | [Description("中")] Moderate, 11 | [Description("高")] High, 12 | [Description("非常高")] VeryHigh 13 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Enums/ProcessStatus.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Enums; 2 | 3 | /// 4 | /// 进程运行状态 5 | /// 6 | public enum ProcessStatus 7 | { 8 | [Description("新建状态")] New, 9 | [Description("就绪状态")] Ready, 10 | [Description("运行状态")] Running, 11 | [Description("阻塞状态")] Blocked, 12 | [Description("终止状态")] Terminated 13 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Enums/ProcessType.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Enums; 2 | 3 | /// 4 | /// 进程类型 5 | /// 6 | public enum ProcessType 7 | { 8 | [Description("应用")] Application, 9 | [Description("后台进程")] BackgroundProcess 10 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Enums/TerminalType.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Enums; 2 | 3 | /// 4 | /// 终端类型 5 | /// 6 | public enum TerminalType 7 | { 8 | [Description("服务端")] Server, 9 | [Description("客户端")] Client 10 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/EventBus/ChangeTCPStatusCommand.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.EventBus; 2 | 3 | /// 4 | /// Tcp连接状态 5 | /// 6 | public class ChangeTCPStatusCommand(bool isConnect, string? ip = default, int port = default) 7 | : Command 8 | { 9 | public bool IsConnect { get; } = isConnect; 10 | public string? Ip { get; } = ip; 11 | public int Port { get; } = port; 12 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/EventBus/ChangeUDPStatusCommand.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.EventBus; 2 | 3 | /// 4 | /// Udp连接状态 5 | /// 6 | public class ChangeUDPStatusCommand(bool isConnect) : Command 7 | { 8 | public bool IsConnect { get; } = isConnect; 9 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/EventBus/SocketCommand.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Sockets; 2 | 3 | namespace SocketDto.EventBus; 4 | 5 | /// 6 | /// Socket信息,收到其他端网络对象后转换为此对象,在进程之内传递 7 | /// 8 | /// 9 | /// 10 | /// 11 | public class SocketCommand(NetHeadInfo netHead, byte[] buffer, Socket? client = null) 12 | : Command 13 | { 14 | /// 15 | /// 数据包头部信息 16 | /// 17 | private NetHeadInfo HeadInfo { get; } = netHead; 18 | 19 | /// 20 | /// 数据 21 | /// 22 | private byte[] Buffer { get; } = buffer; 23 | 24 | /// 25 | /// Socket对象 26 | /// 27 | public Socket? Client { get; } = client; 28 | 29 | /// 30 | /// 判断是否是指定网络对象 31 | /// 32 | /// 33 | /// 34 | public bool IsMessage() 35 | { 36 | return HeadInfo.IsNetObject(); 37 | } 38 | 39 | /// 40 | /// 使用MessagePack反序列化 41 | /// 42 | /// 43 | /// 44 | public T Message() where T : new() 45 | { 46 | return Buffer.Deserialize(); 47 | } 48 | 49 | /// 50 | /// 不使用压缩方式反序列化,UDP数据包使用该方法 51 | /// 52 | /// 53 | /// 54 | public T MessageByNative() where T : new() 55 | { 56 | return Buffer.Deserialize(); 57 | } 58 | 59 | public override string ToString() 60 | { 61 | return HeadInfo.ToString(); 62 | } 63 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/GlobalUsing.cs: -------------------------------------------------------------------------------- 1 | global using CodeWF.EventBus; 2 | global using CodeWF.NetWeaver; 3 | global using CodeWF.NetWeaver.Base; 4 | global using System.ComponentModel; 5 | -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Heartbeat.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto; 2 | 3 | /// 4 | /// TCP心跳包 5 | /// 6 | [NetHead(199, 1)] 7 | public class Heartbeat : INetObject 8 | { 9 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/ISocketBase.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto; 2 | 3 | /// 4 | /// 套接字接口 5 | /// 6 | public interface ISocketBase 7 | { 8 | /// 9 | /// IP 10 | /// 11 | public string? Ip { get; set; } 12 | 13 | /// 14 | /// 端口 15 | /// 16 | public int Port { get; set; } 17 | 18 | /// 19 | /// 是否正在运行 20 | /// 21 | public bool IsRunning { get; set; } 22 | 23 | /// 24 | /// 发送时间 25 | /// 26 | public DateTime SendTime { get; set; } 27 | 28 | /// 29 | /// 接收时间 30 | /// 31 | public DateTime ReceiveTime { get; set; } 32 | 33 | /// 34 | /// 启动 35 | /// 36 | void Start(); 37 | 38 | /// 39 | /// 停止 40 | /// 41 | void Stop(); 42 | 43 | /// 44 | /// 发送命令 45 | /// 46 | /// 47 | void SendCommand(INetObject command); 48 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Requests/RequestProcessIDList.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Requests; 2 | 3 | /// 4 | /// 请求进程ID列表信息 5 | /// 6 | [NetHead(7, 1)] 7 | public class RequestProcessIDList : INetObject 8 | { 9 | /// 10 | /// 任务Id 11 | /// 12 | public int TaskId { get; set; } 13 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Requests/RequestProcessList.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto; 2 | 3 | /// 4 | /// 请求进程信息 5 | /// 6 | [NetHead(9, 1)] 7 | public class RequestProcessList : INetObject 8 | { 9 | /// 10 | /// 任务Id 11 | /// 12 | public int TaskId { get; set; } 13 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Requests/RequestServiceInfo.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Requests; 2 | 3 | /// 4 | /// 请求基本信息 5 | /// 6 | [NetHead(5, 1)] 7 | public class RequestServiceInfo : INetObject 8 | { 9 | /// 10 | /// 任务Id 11 | /// 12 | public int TaskId { get; set; } 13 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Requests/RequestTargetType.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Requests; 2 | 3 | /// 4 | /// 请求目标类型 5 | /// 6 | [NetHead(1, 1)] 7 | public class RequestTargetType : INetObject 8 | { 9 | /// 10 | /// 任务Id 11 | /// 12 | public int TaskId { get; set; } 13 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Requests/RequestUdpAddress.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Requests; 2 | 3 | /// 4 | /// 请求Udp组播地址 5 | /// 6 | [NetHead(3, 1)] 7 | public class RequestUdpAddress : INetObject 8 | { 9 | /// 10 | /// 任务Id 11 | /// 12 | public int TaskId { get; set; } 13 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Response/ResponseProcessIDList.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Response; 2 | 3 | /// 4 | /// 响应请求进程ID列表信息 5 | /// 6 | [NetHead(8, 1)] 7 | public class ResponseProcessIDList : INetObject 8 | { 9 | /// 10 | /// 任务Id 11 | /// 12 | public int TaskId { get; set; } 13 | 14 | /// 15 | /// 进程ID数组,有顺序,更新进程实时数据包需要根据该数组查找进程、更新数据 16 | /// 17 | public int[]? IDList { get; set; } 18 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Response/ResponseProcessList.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Response; 2 | 3 | /// 4 | /// 响应请求进程信息 5 | /// 6 | [NetHead(10, 1)] 7 | public class ResponseProcessList : INetObject 8 | { 9 | /// 10 | /// 任务Id 11 | /// 12 | public int TaskId { get; set; } 13 | 14 | /// 15 | /// 总数据大小 16 | /// 17 | public int TotalSize { get; set; } 18 | 19 | /// 20 | /// 分页大小 21 | /// 22 | public int PageSize { get; set; } 23 | 24 | /// 25 | /// 总页数 26 | /// 27 | public int PageCount { get; set; } 28 | 29 | /// 30 | /// 页索引 31 | /// 32 | public int PageIndex { get; set; } 33 | 34 | /// 35 | /// 进程列表 36 | /// 37 | public List? Processes { get; set; } 38 | } 39 | 40 | /// 41 | /// 操作系统进程信息 42 | /// 43 | public record ProcessItem 44 | { 45 | /// 46 | /// 进程ID 47 | /// 48 | public int Pid { get; set; } 49 | 50 | /// 51 | /// 进程名称 52 | /// 53 | public string? Name { get; set; } 54 | 55 | /// 56 | /// 进程类型,0:应用,1:后台进程 57 | /// 58 | public byte Type { get; set; } 59 | 60 | /// 61 | /// 进程状态,0:新建状态,1:就绪状态,2:运行状态,3:阻塞状态,4:终止状态 62 | /// 63 | public byte ProcessStatus { get; set; } 64 | 65 | /// 66 | /// 告警状态,没有特别意义,可组合位域状态,0:正常,1:超时,2:超限,切换用户 67 | /// 68 | public byte AlarmStatus { get; set; } 69 | 70 | /// 71 | /// 发布者 72 | /// 73 | public string? Publisher { get; set; } 74 | 75 | /// 76 | /// 命令行 77 | /// 78 | public string? CommandLine { get; set; } 79 | 80 | /// 81 | /// Cpu(所有内核的总处理利用率),最后一位表示小数位,比如253表示25.3% 82 | /// 83 | public short Cpu { get; set; } 84 | 85 | /// 86 | /// 内存(进程占用的物理内存),最后一位表示小数位,比如253表示25.3%,值可根据基本信息计算 87 | /// 88 | public short Memory { get; set; } 89 | 90 | /// 91 | /// 磁盘(所有物理驱动器的总利用率),最后一位表示小数位,比如253表示25.3%,值可根据基本信息计算 92 | /// 93 | public short Disk { get; set; } 94 | 95 | /// 96 | /// 网络(当前主要网络上的网络利用率),最后一位表示小数位,比如253表示25.3%,值可根据基本信息计算 97 | /// 98 | public short Network { get; set; } 99 | 100 | /// 101 | /// GPU(所有GPU引擎的最高利用率),最后一位表示小数位,比如253表示25.3 102 | /// 103 | public short Gpu { get; set; } 104 | 105 | /// 106 | /// GPU引擎,0:无,1:GPU 0 - 3D 107 | /// 108 | public byte GpuEngine { get; set; } 109 | 110 | /// 111 | /// 电源使用情况(CPU、磁盘和GPU对功耗的影响),0:非常低,1:低,2:中,3:高,4:非常高 112 | /// 113 | public byte PowerUsage { get; set; } 114 | 115 | /// 116 | /// 电源使用情况趋势(一段时间内CPU、磁盘和GPU对功耗的影响),0:非常低,1:低,2:中,3:高,4:非常高 117 | /// 118 | public byte PowerUsageTrend { get; set; } 119 | 120 | /// 121 | /// 上次更新时间(当天时间戳:当日0点0分0秒计算的时间戳,单位ms) 122 | /// 123 | public uint LastUpdateTime { get; set; } 124 | 125 | /// 126 | /// 更新时间(当天时间戳:当日0点0分0秒计算的时间戳,单位ms) 127 | /// 128 | public uint UpdateTime { get; set; } 129 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Response/ResponseServiceInfo.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Response; 2 | 3 | /// 4 | /// 响应基本信息 5 | /// 6 | [NetHead(6, 1)] 7 | public class ResponseServiceInfo : INetObject 8 | { 9 | /// 10 | /// 任务Id 11 | /// 12 | public int TaskId { get; set; } 13 | 14 | /// 15 | /// 操作系统名称 16 | /// 17 | public string? OS { get; set; } 18 | 19 | /// 20 | /// 系统内存大小(单位GB) 21 | /// 22 | public byte MemorySize { get; set; } 23 | 24 | /// 25 | /// 处理器个数 26 | /// 27 | public byte ProcessorCount { get; set; } 28 | 29 | /// 30 | /// 硬盘总容量(单位GB) 31 | /// 32 | public short DiskSize { get; set; } 33 | 34 | /// 35 | /// 网络带宽(单位Mbps) 36 | /// 37 | public short NetworkBandwidth { get; set; } 38 | 39 | /// 40 | /// 服务器IP地址,多个地址以“,”分隔 41 | /// 42 | public string? Ips { get; set; } 43 | 44 | /// 45 | /// 通信对象时间戳起始年份,比如:2023,表示2023年1月1号开始计算时间戳,后面的时间戳都以这个字段计算为准,精确到0.1s,即100ms,主要用于节约网络对象传输大小 46 | /// 47 | public int TimestampStartYear { get; set; } 48 | 49 | /// 50 | /// 最后更新时间 51 | /// 52 | public uint LastUpdateTime { get; set; } 53 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Response/ResponseTargetType.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Response; 2 | 3 | /// 4 | /// 响应目标终端类型 5 | /// 6 | [NetHead(2, 1)] 7 | public class ResponseTargetType : INetObject 8 | { 9 | /// 10 | /// 任务Id 11 | /// 12 | public int TaskId { get; set; } 13 | 14 | 15 | /// 16 | /// 终端类型,0:Server,1:Client 17 | /// 18 | public byte Type { get; set; } 19 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Response/ResponseUdpAddress.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Response; 2 | 3 | /// 4 | /// 响应Udp组播地址 5 | /// 6 | [NetHead(4, 1)] 7 | public class ResponseUdpAddress : INetObject 8 | { 9 | /// 10 | /// 任务Id 11 | /// 12 | public int TaskId { get; set; } 13 | 14 | 15 | /// 16 | /// 组播地址 17 | /// 18 | public string? Ip { get; set; } 19 | 20 | /// 21 | /// 组播端口 22 | /// 23 | public int Port { get; set; } 24 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/SocketDto.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net10.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Udp/UpdateGeneralProcessList.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Udp; 2 | 3 | /// 4 | /// 更新进程变化信息,序列化和反序列不能加压缩,部分双精度因为有效位数太长,可能导致UDP包过大而发送失败,所以UDP包不要加压缩 5 | /// 6 | [NetHead(201, 1)] 7 | public class UpdateGeneralProcessList : INetObject 8 | { 9 | /// 10 | /// 总数据大小 11 | /// 12 | public int TotalSize { get; set; } 13 | 14 | /// 15 | /// 分页大小 16 | /// 17 | public int PageSize { get; set; } 18 | 19 | /// 20 | /// 总页数 21 | /// 22 | public int PageCount { get; set; } 23 | 24 | /// 25 | /// 页索引 26 | /// 27 | public int PageIndex { get; set; } 28 | 29 | /// 30 | /// 进程状态,一个进程占1字节(byte) 31 | /// 32 | public byte[] ProcessStatuses { get; set; } = null!; 33 | 34 | /// 35 | /// 告警状态,一个进程占1字节(byte) 36 | /// 37 | public byte[] AlarmStatuses { get; set; } = null!; 38 | 39 | /// 40 | /// 一个进程占2字节(short) 41 | /// 42 | public byte[] Gpus { get; set; } = null!; 43 | 44 | /// 45 | /// 一个进程占1字节(byte) 46 | /// 47 | public byte[] GpuEngine { get; set; } = null!; 48 | 49 | /// 50 | /// 一个进程占1字节(byte) 51 | /// 52 | public byte[] PowerUsage { get; set; } = null!; 53 | 54 | /// 55 | /// 一个进程占1字节(byte) 56 | /// 57 | public byte[] PowerUsageTrend { get; set; } = null!; 58 | 59 | /// 60 | /// 一个进程占4字节(byte) 61 | /// 62 | public byte[] UpdateTimes { get; set; } = null!; 63 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketDto/Udp/UpdateRealtimeProcessList.cs: -------------------------------------------------------------------------------- 1 | namespace SocketDto.Udp; 2 | 3 | /// 4 | /// 更新进程变化信息,序列化和反序列不能加压缩,部分双精度因为有效位数太长,可能导致UDP包过大而发送失败,所以UDP包不要加压缩 5 | /// 6 | [NetHead(200, 1)] 7 | public class UpdateRealtimeProcessList : INetObject 8 | { 9 | /// 10 | /// 总数据大小 11 | /// 12 | public int TotalSize { get; set; } 13 | 14 | /// 15 | /// 分页大小 16 | /// 17 | public int PageSize { get; set; } 18 | 19 | /// 20 | /// 总页数 21 | /// 22 | public int PageCount { get; set; } 23 | 24 | /// 25 | /// 页索引 26 | /// 27 | public int PageIndex { get; set; } 28 | 29 | /// 30 | /// 一个进程占2字节(short) 31 | /// 32 | public byte[] Cpus { get; set; } = null!; 33 | 34 | /// 35 | /// 一个进程占2字节(short) 36 | /// 37 | [NetFieldOffset(10, 10)] 38 | public byte[] Memories { get; set; } = null!; 39 | 40 | /// 41 | /// 一个进程占2字节(short) 42 | /// 43 | [NetFieldOffset(20, 10)] 44 | public byte[] Disks { get; set; } = null!; 45 | 46 | /// 47 | /// 一个进程占2字节(short) 48 | /// 49 | [NetFieldOffset(30, 10)] 50 | public byte[] Networks { get; set; } = null!; 51 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/App.axaml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/App.axaml.cs: -------------------------------------------------------------------------------- 1 | using Avalonia; 2 | using Avalonia.Controls.ApplicationLifetimes; 3 | using Avalonia.Markup.Xaml; 4 | using SocketTest.Client.ViewModels; 5 | using SocketTest.Client.Views; 6 | 7 | namespace SocketTest.Client; 8 | 9 | public class App : Application 10 | { 11 | public override void Initialize() 12 | { 13 | AvaloniaXamlLoader.Load(this); 14 | } 15 | 16 | public override void OnFrameworkInitializationCompleted() 17 | { 18 | if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) 19 | desktop.MainWindow = new MainWindow 20 | { 21 | DataContext = new MainWindowViewModel() 22 | }; 23 | 24 | base.OnFrameworkInitializationCompleted(); 25 | } 26 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/Assets/avalonia-logo.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnet9/CsharpSocketTest/056932a9c4c1dd084bdcc9fd36167c11e4bf6895/src/SocketTesting/SocketTest.Client/Assets/avalonia-logo.ico -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/Converters/AlarmStatusToForegroundConverter.cs: -------------------------------------------------------------------------------- 1 | using Avalonia.Data.Converters; 2 | using Avalonia.Media; 3 | using SocketDto.Enums; 4 | using System; 5 | using System.Globalization; 6 | 7 | namespace SocketTest.Client.Converters; 8 | 9 | public class AlarmStatusToForegroundConverter : IValueConverter 10 | { 11 | public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) 12 | { 13 | if (value is not AlarmStatus status) return Brushes.Red; 14 | return status == AlarmStatus.Normal ? Brushes.Green : Brushes.Red; 15 | } 16 | 17 | public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) 18 | { 19 | throw new NotImplementedException(); 20 | } 21 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/Converters/EnumToDescriptionConverter.cs: -------------------------------------------------------------------------------- 1 | using Avalonia.Data.Converters; 2 | using CodeWF.Tools.Extensions; 3 | using System; 4 | using System.Globalization; 5 | 6 | namespace SocketTest.Client.Converters; 7 | 8 | public class EnumToDescriptionConverter : IValueConverter 9 | { 10 | public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) 11 | { 12 | if (value is not Enum enumValue) return value; 13 | 14 | return enumValue.GetDescription(); 15 | } 16 | 17 | public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) 18 | { 19 | throw new NotImplementedException(); 20 | } 21 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/Converters/ProcessPowerUsageToForegroundConverter.cs: -------------------------------------------------------------------------------- 1 | using Avalonia.Data.Converters; 2 | using Avalonia.Media; 3 | using SocketDto.Enums; 4 | using System; 5 | using System.Globalization; 6 | 7 | namespace SocketTest.Client.Converters; 8 | 9 | public class ProcessPowerUsageToForegroundConverter : IValueConverter 10 | { 11 | public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) 12 | { 13 | if (value == null) return Brushes.Green; 14 | 15 | var powerUsageType = 16 | (PowerUsage)Enum.Parse(typeof(PowerUsage), value.ToString()!); 17 | return powerUsageType switch 18 | { 19 | PowerUsage.VeryLow or PowerUsage.Low => Brushes.LightGreen, 20 | PowerUsage.Moderate => Brushes.Green, 21 | PowerUsage.High => Brushes.DarkOrange, 22 | _ => Brushes.Red 23 | }; 24 | } 25 | 26 | public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) 27 | { 28 | throw new NotImplementedException(); 29 | } 30 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/Converters/ProcessStatusToForegroundConverter.cs: -------------------------------------------------------------------------------- 1 | using Avalonia.Data.Converters; 2 | using Avalonia.Media; 3 | using SocketDto.Enums; 4 | using System; 5 | using System.Globalization; 6 | 7 | namespace SocketTest.Client.Converters; 8 | 9 | public class ProcessStatusToForegroundConverter : IValueConverter 10 | { 11 | public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) 12 | { 13 | if (value is ProcessStatus status) 14 | { 15 | return status switch 16 | { 17 | < ProcessStatus.Running => Brushes.CadetBlue, 18 | > ProcessStatus.Running => Brushes.Green, 19 | _ => Brushes.Red 20 | }; 21 | } 22 | 23 | return Brushes.CadetBlue; 24 | } 25 | 26 | public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) 27 | { 28 | throw new NotImplementedException(); 29 | } 30 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/Converters/UsageToForegroundConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using Avalonia.Data.Converters; 4 | using Avalonia.Media; 5 | 6 | namespace SocketTest.Client.Converters; 7 | 8 | public class UsageToForegroundConverter : IValueConverter 9 | { 10 | public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) 11 | { 12 | if (value == null || !short.TryParse(value.ToString(), out var bValue)) return Brushes.Green; 13 | 14 | var dValue = bValue * 1.0 / 10; 15 | return dValue switch 16 | { 17 | < 5 => Brushes.LightGreen, 18 | < 10 => Brushes.Green, 19 | < 20 => Brushes.DarkOrange, 20 | _ => Brushes.Red 21 | }; 22 | } 23 | 24 | public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) 25 | { 26 | throw new NotImplementedException(); 27 | } 28 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/Converters/UsageToFormatConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using Avalonia.Data.Converters; 4 | using Avalonia.Media; 5 | 6 | namespace SocketTest.Client.Converters; 7 | 8 | public class UsageToFormatConverter : IValueConverter 9 | { 10 | public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) 11 | { 12 | if (value == null || !short.TryParse(value.ToString(), out var bValue)) return Brushes.Green; 13 | 14 | var dValue = bValue * 1.0 / 1000; 15 | return dValue.ToString("P1"); 16 | } 17 | 18 | public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) 19 | { 20 | throw new NotImplementedException(); 21 | } 22 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/Extensions/RangObservableCollection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.ObjectModel; 4 | using System.Collections.Specialized; 5 | 6 | namespace SocketTest.Client.Extensions; 7 | 8 | public class RangObservableCollection : ObservableCollection 9 | { 10 | private bool SuppressNotification { get; set; } = false; 11 | 12 | protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) 13 | { 14 | if (!SuppressNotification) 15 | { 16 | base.OnCollectionChanged(e); 17 | } 18 | } 19 | 20 | public new void Clear() 21 | { 22 | Items.Clear(); 23 | OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); 24 | } 25 | 26 | public void AddRange(IEnumerable collection) 27 | { 28 | if (collection == null) 29 | { 30 | throw new ArgumentNullException(nameof(collection)); 31 | } 32 | 33 | SuppressNotification = true; 34 | 35 | foreach (var item in collection) 36 | { 37 | Items.Add(item); 38 | } 39 | 40 | SuppressNotification = false; 41 | OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); 42 | } 43 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/Helpers/TcpHelper.cs: -------------------------------------------------------------------------------- 1 | using Avalonia.Threading; 2 | using CodeWF.EventBus; 3 | using CodeWF.LogViewer.Avalonia; 4 | using CodeWF.NetWeaver; 5 | using CodeWF.NetWeaver.Base; 6 | using ReactiveUI; 7 | using SocketDto; 8 | using SocketDto.EventBus; 9 | using System; 10 | using System.Collections.Concurrent; 11 | using System.Net; 12 | using System.Net.Sockets; 13 | using System.Threading; 14 | using System.Threading.Tasks; 15 | 16 | namespace SocketTest.Client.Helpers; 17 | 18 | public class TcpHelper : ReactiveObject, ISocketBase 19 | { 20 | private Socket? _client; 21 | public long SystemId { get; private set; } // 服务端标识,TCP数据接收时保存,用于UDP数据包识别 22 | 23 | public readonly BlockingCollection _responses = new(new ConcurrentQueue()); 24 | 25 | #region 公开属性 26 | 27 | private string? _ip = "127.0.0.1"; 28 | 29 | /// 30 | /// Tcp服务IP 31 | /// 32 | public string? Ip 33 | { 34 | get => _ip; 35 | set => this.RaiseAndSetIfChanged(ref _ip, value); 36 | } 37 | 38 | private int _port = 5000; 39 | 40 | /// 41 | /// Tcp服务端口 42 | /// 43 | public int Port 44 | { 45 | get => _port; 46 | set => this.RaiseAndSetIfChanged(ref _port, value); 47 | } 48 | 49 | private bool _isRunning; 50 | 51 | /// 52 | /// 是否正在运行Tcp服务 53 | /// 54 | public bool IsRunning 55 | { 56 | get => _isRunning; 57 | set => this.RaiseAndSetIfChanged(ref _isRunning, value); 58 | } 59 | 60 | private DateTime _sendTime; 61 | 62 | /// 63 | /// 命令发送时间 64 | /// 65 | public DateTime SendTime 66 | { 67 | get => _sendTime; 68 | set => this.RaiseAndSetIfChanged(ref _sendTime, value); 69 | } 70 | 71 | private DateTime _receiveTime; 72 | 73 | /// 74 | /// 响应接收时间 75 | /// 76 | public DateTime ReceiveTime 77 | { 78 | get => _receiveTime; 79 | set => this.RaiseAndSetIfChanged(ref _receiveTime, value); 80 | } 81 | 82 | private DateTime _sendHeartbeatTime; 83 | 84 | /// 85 | /// 心跳发送时间 86 | /// 87 | public DateTime SendHeartbeatTime 88 | { 89 | get => _sendHeartbeatTime; 90 | set => this.RaiseAndSetIfChanged(ref _sendHeartbeatTime, value); 91 | } 92 | 93 | private DateTime _responseHeartbeatTime; 94 | 95 | /// 96 | /// 心跳响应时间 97 | /// 98 | public DateTime ResponseHeartbeatTime 99 | { 100 | get => _responseHeartbeatTime; 101 | set => this.RaiseAndSetIfChanged(ref _responseHeartbeatTime, value); 102 | } 103 | 104 | #endregion 105 | 106 | #region 公开接口 107 | 108 | private CancellationTokenSource? _connectServer; 109 | 110 | public void Start() 111 | { 112 | _connectServer = new CancellationTokenSource(); 113 | var ipEndPoint = new IPEndPoint(IPAddress.Parse(Ip), Port); 114 | Task.Run(async () => 115 | { 116 | while (!_connectServer.IsCancellationRequested) 117 | try 118 | { 119 | _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 120 | await _client.ConnectAsync(ipEndPoint); 121 | 122 | await Dispatcher.UIThread.InvokeAsync(() => IsRunning = true); 123 | 124 | ListenForServer(); 125 | CheckResponse(); 126 | 127 | Logger.Info("连接Tcp服务成功"); 128 | await EventBus.Default.PublishAsync(new ChangeTCPStatusCommand(true, Ip, Port)); 129 | break; 130 | } 131 | catch (Exception ex) 132 | { 133 | IsRunning = false; 134 | Logger.Warn($"连接TCP服务异常,3秒后将重新连接:{ex.Message}"); 135 | await Task.Delay(TimeSpan.FromSeconds(3)); 136 | } 137 | }, _connectServer.Token); 138 | } 139 | 140 | public void Stop() 141 | { 142 | try 143 | { 144 | _connectServer?.Cancel(); 145 | _client?.Close(0); 146 | Logger.Info("停止Tcp服务"); 147 | } 148 | catch (Exception ex) 149 | { 150 | Logger.Warn($"停止TCP服务异常:{ex.Message}"); 151 | } 152 | 153 | IsRunning = false; 154 | } 155 | 156 | public void SendCommand(INetObject command) 157 | { 158 | if (!IsRunning) 159 | { 160 | Logger.Error("Tcp服务未连接,无法发送命令"); 161 | return; 162 | } 163 | 164 | var buffer = command.Serialize(SystemId); 165 | _client!.Send(buffer); 166 | var index = 0; 167 | buffer.ReadHead(ref index, out var head); 168 | Logger.Info($"Send(client={_client.RemoteEndPoint},len={buffer.Length}):{head}"); 169 | if (command is Heartbeat) 170 | { 171 | SendHeartbeatTime = DateTime.Now; 172 | } 173 | else 174 | Logger.Info($"发送命令{command.GetType()}"); 175 | } 176 | 177 | private static int _taskId; 178 | 179 | public static int GetNewTaskId() 180 | { 181 | return ++_taskId; 182 | } 183 | 184 | #endregion 185 | 186 | #region 连接TCP、接收数据 187 | 188 | private void ListenForServer() 189 | { 190 | Task.Run(() => 191 | { 192 | while (IsRunning) 193 | try 194 | { 195 | Logger.Info("Listen server"); 196 | while (_client!.ReadPacket(out var buffer, out var headInfo)) 197 | { 198 | Logger.Info($"Receive(len={buffer.Length}): {headInfo}"); 199 | ReceiveTime = DateTime.Now; 200 | SystemId = headInfo!.SystemId; 201 | _responses.Add(new SocketCommand(headInfo, buffer, _client)); 202 | } 203 | } 204 | catch (SocketException ex) 205 | { 206 | Logger.Error($"接收数据异常:{ex.Message}"); 207 | break; 208 | } 209 | catch (Exception ex) 210 | { 211 | Logger.Error($"接收数据异常:{ex.Message}"); 212 | } 213 | 214 | return Task.CompletedTask; 215 | }); 216 | } 217 | 218 | private void CheckResponse() 219 | { 220 | Task.Run(async () => 221 | { 222 | while (!IsRunning) 223 | { 224 | await Task.Delay(TimeSpan.FromMilliseconds(10)); 225 | } 226 | 227 | while (IsRunning) 228 | { 229 | while (_responses.TryTake(out var message, TimeSpan.FromMilliseconds(10))) 230 | { 231 | Logger.Info($"Send event {message}"); 232 | await EventBus.Default.PublishAsync(message); 233 | } 234 | } 235 | }); 236 | } 237 | 238 | #endregion 239 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/Helpers/UdpHelper.cs: -------------------------------------------------------------------------------- 1 | using CodeWF.EventBus; 2 | using CodeWF.LogViewer.Avalonia; 3 | using CodeWF.NetWeaver; 4 | using CodeWF.NetWeaver.Base; 5 | using ReactiveUI; 6 | using SocketDto; 7 | using SocketDto.EventBus; 8 | using System; 9 | using System.Collections.Concurrent; 10 | using System.Net; 11 | using System.Net.Sockets; 12 | using System.Threading; 13 | using System.Threading.Tasks; 14 | 15 | namespace SocketTest.Client.Helpers; 16 | 17 | public class UdpHelper : ReactiveObject, ISocketBase 18 | { 19 | private readonly BlockingCollection _receivedBuffers = new(new ConcurrentQueue()); 20 | private UdpClient? _client; 21 | private IPEndPoint _remoteEp = new(IPAddress.Any, 0); 22 | 23 | #region 公开属性 24 | 25 | private string? _ip; 26 | 27 | /// 28 | /// UDP组播IP 29 | /// 30 | public string? Ip 31 | { 32 | get => _ip; 33 | set => this.RaiseAndSetIfChanged(ref _ip, value); 34 | } 35 | 36 | private int _port; 37 | 38 | /// 39 | /// UDP组播端口 40 | /// 41 | public int Port 42 | { 43 | get => _port; 44 | set => this.RaiseAndSetIfChanged(ref _port, value); 45 | } 46 | 47 | private bool _isRunning; 48 | 49 | /// 50 | /// 是否正在运行udp组播订阅 51 | /// 52 | public bool IsRunning 53 | { 54 | get => _isRunning; 55 | set => this.RaiseAndSetIfChanged(ref _isRunning, value); 56 | } 57 | 58 | private DateTime _sendTime; 59 | 60 | /// 61 | /// 命令发送时间 62 | /// 63 | public DateTime SendTime 64 | { 65 | get => _sendTime; 66 | set => this.RaiseAndSetIfChanged(ref _sendTime, value); 67 | } 68 | 69 | private DateTime _receiveTime; 70 | 71 | /// 72 | /// 响应接收时间 73 | /// 74 | public DateTime ReceiveTime 75 | { 76 | get => _receiveTime; 77 | set => this.RaiseAndSetIfChanged(ref _receiveTime, value); 78 | } 79 | 80 | /// 81 | /// 新数据通知 82 | /// 83 | public Action? NewDataResponse; 84 | 85 | #endregion 86 | 87 | #region 公开接口 88 | 89 | private CancellationTokenSource? _connectServer; 90 | 91 | public void Start() 92 | { 93 | _connectServer = new CancellationTokenSource(); 94 | Task.Run(async () => 95 | { 96 | while (!_connectServer.IsCancellationRequested) 97 | try 98 | { 99 | _client = new UdpClient(); 100 | _client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); 101 | _client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); 102 | 103 | // 任意IP+广播端口,0是任意端口 104 | _client.Client.Bind(new IPEndPoint(IPAddress.Any, Port)); 105 | 106 | // 加入组播 107 | _client.JoinMulticastGroup(IPAddress.Parse(Ip!)); 108 | IsRunning = true; 109 | 110 | ReceiveData(); 111 | CheckMessage(); 112 | await EventBus.Default.PublishAsync(new ChangeUDPStatusCommand(true)); 113 | break; 114 | } 115 | catch (Exception ex) 116 | { 117 | IsRunning = false; 118 | Logger.Warn($"运行Udp异常,3秒后将重新运行:{ex.Message}"); 119 | await Task.Delay(TimeSpan.FromSeconds(3)); 120 | } 121 | }, _connectServer.Token); 122 | } 123 | 124 | public void Stop() 125 | { 126 | try 127 | { 128 | _connectServer?.Cancel(); 129 | _client?.Close(); 130 | _client = null; 131 | Logger.Info("停止Udp"); 132 | } 133 | catch (Exception ex) 134 | { 135 | Logger.Warn($"停止Udp异常:{ex.Message}"); 136 | } 137 | 138 | IsRunning = false; 139 | } 140 | 141 | public void SendCommand(INetObject command) 142 | { 143 | } 144 | 145 | #endregion 146 | 147 | #region 接收处理数据 148 | 149 | private void ReceiveData() 150 | { 151 | Task.Run(async () => 152 | { 153 | while (IsRunning) 154 | try 155 | { 156 | if (_client?.Client == null || _client.Available < 0) 157 | { 158 | await Task.Delay(TimeSpan.FromMilliseconds(10)); 159 | continue; 160 | } 161 | 162 | var data = _client.Receive(ref _remoteEp); 163 | var readIndex = 0; 164 | if (SerializeHelper.ReadHead(data, ref readIndex, out var headInfo) && 165 | data.Length >= headInfo?.BufferLen) 166 | { 167 | _receivedBuffers.Add(new SocketCommand(headInfo!, data)); 168 | } 169 | else 170 | { 171 | Logger.Warn($"收到错误UDP包:{headInfo}"); 172 | } 173 | 174 | ReceiveTime = DateTime.Now; 175 | } 176 | catch (SocketException ex) 177 | { 178 | Logger.Error(ex.SocketErrorCode == SocketError.Interrupted 179 | ? "Udp中断,停止接收数据!" 180 | : $"接收Udp数据异常:{ex.Message}"); 181 | } 182 | catch (Exception ex) 183 | { 184 | Logger.Error($"接收Udp数据异常:{ex.Message}"); 185 | } 186 | }); 187 | } 188 | 189 | private void CheckMessage() 190 | { 191 | Task.Run(async () => 192 | { 193 | while (!IsRunning) 194 | { 195 | await Task.Delay(TimeSpan.FromMilliseconds(10)); 196 | } 197 | 198 | while (IsRunning) 199 | { 200 | while (_receivedBuffers.TryTake(out var message, TimeSpan.FromMilliseconds(10))) 201 | { 202 | NewDataResponse?.Invoke(message); 203 | } 204 | } 205 | }); 206 | } 207 | 208 | #endregion 209 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/Models/ProcessItemModel.cs: -------------------------------------------------------------------------------- 1 | using CodeWF.Tools.Extensions; 2 | using ReactiveUI; 3 | using SocketDto.Enums; 4 | using SocketDto.Response; 5 | using System; 6 | 7 | namespace SocketTest.Client.Models; 8 | 9 | /// 10 | /// 操作系统进程信息 11 | /// 12 | public class ProcessItemModel : ReactiveObject 13 | { 14 | private string? _commandLine; 15 | 16 | private short _cpu; 17 | 18 | private short _disk; 19 | 20 | private short _gpu; 21 | 22 | private GpuEngine _gpuEngine; 23 | 24 | private DateTime _lastUpdateTime; 25 | 26 | private short _memory; 27 | 28 | private string? _name; 29 | 30 | private short _network; 31 | 32 | private PowerUsage _powerUsage; 33 | 34 | private PowerUsage _powerUsageTrend; 35 | 36 | private string? _publisher; 37 | 38 | private ProcessStatus _status; 39 | 40 | private ProcessType _type; 41 | 42 | private DateTime _updateTime; 43 | 44 | public ProcessItemModel() 45 | { 46 | } 47 | 48 | public ProcessItemModel(ProcessItem process, int timestampStartYear) 49 | { 50 | Update(process, timestampStartYear); 51 | } 52 | 53 | /// 54 | /// 进程ID 55 | /// 56 | public int PID { get; set; } 57 | 58 | /// 59 | /// 进程名称 60 | /// 61 | public string? Name 62 | { 63 | get => _name; 64 | set => this.RaiseAndSetIfChanged(ref _name, value); 65 | } 66 | 67 | /// 68 | /// 进程类型 69 | /// 70 | public ProcessType Type 71 | { 72 | get => _type; 73 | set => this.RaiseAndSetIfChanged(ref _type, value); 74 | } 75 | 76 | /// 77 | /// 进程状态 78 | /// 79 | public ProcessStatus Status 80 | { 81 | get => _status; 82 | set => this.RaiseAndSetIfChanged(ref _status, value); 83 | } 84 | 85 | private AlarmStatus _alarmStatus; 86 | 87 | /// 88 | /// 进程一般状态 89 | /// 90 | public AlarmStatus AlarmStatus 91 | { 92 | get => _alarmStatus; 93 | set => this.RaiseAndSetIfChanged(ref _alarmStatus, value); 94 | } 95 | 96 | /// 97 | /// 发布者 98 | /// 99 | public string? Publisher 100 | { 101 | get => _publisher; 102 | set => this.RaiseAndSetIfChanged(ref _publisher, value); 103 | } 104 | 105 | /// 106 | /// 命令行 107 | /// 108 | public string? CommandLine 109 | { 110 | get => _commandLine; 111 | set => this.RaiseAndSetIfChanged(ref _commandLine, value); 112 | } 113 | 114 | /// 115 | /// CPU使用率 116 | /// 117 | public short Cpu 118 | { 119 | get => _cpu; 120 | set => this.RaiseAndSetIfChanged(ref _cpu, value); 121 | } 122 | 123 | /// 124 | /// 内存使用大小 125 | /// 126 | public short Memory 127 | { 128 | get => _memory; 129 | set => this.RaiseAndSetIfChanged(ref _memory, value); 130 | } 131 | 132 | /// 133 | /// 磁盘使用大小 134 | /// 135 | public short Disk 136 | { 137 | get => _disk; 138 | set => this.RaiseAndSetIfChanged(ref _disk, value); 139 | } 140 | 141 | /// 142 | /// 网络使用值 143 | /// 144 | public short Network 145 | { 146 | get => _network; 147 | set => this.RaiseAndSetIfChanged(ref _network, value); 148 | } 149 | 150 | /// 151 | /// GPU 152 | /// 153 | public short Gpu 154 | { 155 | get => _gpu; 156 | set => this.RaiseAndSetIfChanged(ref _gpu, value); 157 | } 158 | 159 | /// 160 | /// GPU引擎 161 | /// 162 | public GpuEngine GpuEngine 163 | { 164 | get => _gpuEngine; 165 | set => this.RaiseAndSetIfChanged(ref _gpuEngine, value); 166 | } 167 | 168 | /// 169 | /// 电源使用情况 170 | /// 171 | public PowerUsage PowerUsage 172 | { 173 | get => _powerUsage; 174 | set => this.RaiseAndSetIfChanged(ref _powerUsage, value); 175 | } 176 | 177 | /// 178 | /// 电源使用情况趋势 179 | /// 180 | public PowerUsage PowerUsageTrend 181 | { 182 | get => _powerUsageTrend; 183 | set => this.RaiseAndSetIfChanged(ref _powerUsageTrend, value); 184 | } 185 | 186 | /// 187 | /// 上次更新时间 188 | /// 189 | public DateTime LastUpdateTime 190 | { 191 | get => _lastUpdateTime; 192 | set => this.RaiseAndSetIfChanged(ref _lastUpdateTime, value); 193 | } 194 | 195 | /// 196 | /// 更新时间 197 | /// 198 | public DateTime UpdateTime 199 | { 200 | get => _updateTime; 201 | set => this.RaiseAndSetIfChanged(ref _updateTime, value); 202 | } 203 | 204 | public void Update(ProcessItem process, int timestampStartYear) 205 | { 206 | PID = process.Pid; 207 | 208 | Name = process.Name; 209 | Publisher = process.Publisher; 210 | CommandLine = process.CommandLine; 211 | 212 | Cpu = process.Cpu; 213 | Memory = process.Memory; 214 | Disk = process.Disk; 215 | Network = process.Network; 216 | Gpu = process.Gpu; 217 | GpuEngine = (GpuEngine)Enum.Parse(typeof(GpuEngine), process.GpuEngine.ToString()); 218 | PowerUsage = (PowerUsage)Enum.Parse(typeof(PowerUsage), process.PowerUsage.ToString()); 219 | PowerUsageTrend = (PowerUsage)Enum.Parse(typeof(PowerUsage), process.PowerUsageTrend.ToString()); 220 | Type = (ProcessType)Enum.Parse(typeof(ProcessType), process.Type.ToString()); 221 | Status = (ProcessStatus)Enum.Parse(typeof(ProcessStatus), process.ProcessStatus.ToString()); 222 | LastUpdateTime = process.LastUpdateTime.FromSpecialUnixTimeSecondsToDateTime(timestampStartYear); 223 | UpdateTime = process.UpdateTime.FromSpecialUnixTimeSecondsToDateTime(timestampStartYear); 224 | } 225 | 226 | public void Update(short cpu, short memory, short disk, short network) 227 | { 228 | Cpu = cpu; 229 | Memory = memory; 230 | Disk = disk; 231 | Network = network; 232 | } 233 | 234 | public void Update(int timestampStartYear, byte processStatus, byte alarmStatus, short gpu, byte gpuEngine, 235 | byte powerUsage, byte powerUsageTrend, uint updateTime) 236 | { 237 | Status = (ProcessStatus)Enum.Parse(typeof(ProcessStatus), processStatus.ToString()); 238 | AlarmStatus = (AlarmStatus)Enum.Parse(typeof(AlarmStatus), alarmStatus.ToString()); 239 | Gpu = gpu; 240 | GpuEngine = (GpuEngine)Enum.Parse(typeof(GpuEngine), gpuEngine.ToString()); 241 | PowerUsage = (PowerUsage)Enum.Parse(typeof(PowerUsage), powerUsage.ToString()); 242 | PowerUsageTrend = (PowerUsage)Enum.Parse(typeof(PowerUsage), powerUsageTrend.ToString()); 243 | LastUpdateTime = UpdateTime; 244 | UpdateTime = updateTime.FromSpecialUnixTimeSecondsToDateTime(timestampStartYear); 245 | } 246 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Avalonia; 3 | using Avalonia.ReactiveUI; 4 | 5 | namespace SocketTest.Client; 6 | 7 | internal sealed class Program 8 | { 9 | // Initialization code. Don't use any Avalonia, third-party APIs or any 10 | // SynchronizationContext-reliant code before AppMain is called: things aren't initialized 11 | // yet and stuff might break. 12 | [STAThread] 13 | public static void Main(string[] args) 14 | { 15 | BuildAvaloniaApp() 16 | .StartWithClassicDesktopLifetime(args); 17 | } 18 | 19 | // Avalonia configuration, don't remove; also used by visual designer. 20 | public static AppBuilder BuildAvaloniaApp() 21 | { 22 | return AppBuilder.Configure() 23 | .UsePlatformDetect() 24 | .WithInterFont() 25 | .LogToTrace() 26 | .UseReactiveUI(); 27 | } 28 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/Roots.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/SocketTest.Client.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | WinExe 4 | net10.0 5 | enable 6 | true 7 | app.manifest 8 | true 9 | true 10 | true 11 | 12 | 13 | true 14 | true 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/ViewModels/MainWindowViewModel.cs: -------------------------------------------------------------------------------- 1 | using Avalonia.Controls; 2 | using Avalonia.Controls.Notifications; 3 | using Avalonia.Threading; 4 | using CodeWF.EventBus; 5 | using CodeWF.Tools.Extensions; 6 | using ReactiveUI; 7 | using SocketDto; 8 | using SocketDto.AutoCommand; 9 | using SocketDto.Enums; 10 | using SocketDto.EventBus; 11 | using SocketDto.Requests; 12 | using SocketDto.Response; 13 | using SocketDto.Udp; 14 | using SocketTest.Client.Extensions; 15 | using SocketTest.Client.Helpers; 16 | using SocketTest.Client.Models; 17 | using System; 18 | using System.Collections.Generic; 19 | using System.Linq; 20 | using System.Reactive; 21 | using System.Reactive.Linq; 22 | using System.Threading.Tasks; 23 | using System.Timers; 24 | using CodeWF.LogViewer.Avalonia; 25 | using Notification = Avalonia.Controls.Notifications.Notification; 26 | 27 | namespace SocketTest.Client.ViewModels; 28 | 29 | public class MainWindowViewModel : ReactiveObject 30 | { 31 | public WindowNotificationManager? NotificationManager { get; set; } 32 | private readonly List _receivedProcesses = new(); 33 | 34 | private string? _baseInfo; 35 | 36 | private int[]? _processIdArray; 37 | private Dictionary? _processIdAndItems; 38 | 39 | private string? _searchKey; 40 | 41 | private Timer? _sendDataTimer; 42 | private int _timestampStartYear; 43 | 44 | public MainWindowViewModel() 45 | { 46 | DisplayProcesses = new(); 47 | 48 | void RegisterCommand() 49 | { 50 | var isTcpRunning = this.WhenAnyValue(x => x.TcpHelper.IsRunning); 51 | RefreshCommand = ReactiveCommand.Create(HandleRefreshCommand, isTcpRunning); 52 | RefreshAllCommand = ReactiveCommand.Create(HandleRefreshAllCommand, isTcpRunning); 53 | } 54 | 55 | EventBus.Default.Subscribe(this); 56 | RegisterCommand(); 57 | 58 | Logger.Info("连接服务端后获取数据"); 59 | } 60 | 61 | public Window? Owner { get; set; } 62 | public RangObservableCollection DisplayProcesses { get; } 63 | 64 | public TcpHelper TcpHelper { get; set; } = new(); 65 | public UdpHelper UdpHelper { get; set; } = new(); 66 | 67 | public string? SearchKey 68 | { 69 | get => _searchKey; 70 | set => this.RaiseAndSetIfChanged(ref _searchKey, value); 71 | } 72 | 73 | /// 74 | /// 基本信息 75 | /// 76 | public string? BaseInfo 77 | { 78 | get => _baseInfo; 79 | set => this.RaiseAndSetIfChanged(ref _baseInfo, value); 80 | } 81 | 82 | 83 | /// 84 | /// 刷新数据 85 | /// 86 | public ReactiveCommand? RefreshCommand { get; private set; } 87 | 88 | /// 89 | /// 刷新数据 90 | /// 91 | public ReactiveCommand? RefreshAllCommand { get; private set; } 92 | 93 | public void HandleConnectTcpCommandAsync() 94 | { 95 | if (!TcpHelper.IsRunning) 96 | { 97 | TcpHelper.Start(); 98 | } 99 | else 100 | { 101 | TcpHelper.Stop(); 102 | UdpHelper.Stop(); 103 | UdpHelper.NewDataResponse -= ReceiveUdpCommand; 104 | } 105 | } 106 | 107 | private void HandleRefreshCommand() 108 | { 109 | if (!TcpHelper.IsRunning) 110 | { 111 | _ = Log("未连接Tcp服务,无法发送命令", LogType.Error); 112 | return; 113 | } 114 | 115 | ClearData(); 116 | TcpHelper.SendCommand(new RequestServiceInfo { TaskId = TcpHelper.GetNewTaskId() }); 117 | _ = Log("发送请求服务基本信息命令"); 118 | } 119 | 120 | private void HandleRefreshAllCommand() 121 | { 122 | if (!TcpHelper.IsRunning) 123 | { 124 | Logger.Error("未连接Tcp服务,无法发送命令"); 125 | return; 126 | } 127 | 128 | TcpHelper.SendCommand(new ChangeProcessList()); 129 | Logger.Info("发送刷新所有客户端命令"); 130 | } 131 | 132 | private IEnumerable FilterData(IEnumerable processes) 133 | { 134 | return string.IsNullOrWhiteSpace(SearchKey) 135 | ? processes 136 | : processes.Where(process => 137 | !string.IsNullOrWhiteSpace(process.Name) && process.Name.Contains(SearchKey)); 138 | } 139 | 140 | private void ClearData() 141 | { 142 | _receivedProcesses.Clear(); 143 | Invoke(DisplayProcesses.Clear); 144 | } 145 | 146 | private void SendHeartbeat() 147 | { 148 | _sendDataTimer = new Timer(); 149 | _sendDataTimer.Interval = 200; 150 | _sendDataTimer.Elapsed += MockSendData; 151 | _sendDataTimer.Start(); 152 | } 153 | 154 | private void MockSendData(object? sender, ElapsedEventArgs e) 155 | { 156 | if (!TcpHelper.IsRunning) return; 157 | 158 | TcpHelper.SendCommand(new Heartbeat()); 159 | } 160 | 161 | private void Try(string actionName, Action action, Action? exceptionAction = null) 162 | { 163 | try 164 | { 165 | action.Invoke(); 166 | } 167 | catch (Exception ex) 168 | { 169 | if (exceptionAction == null) 170 | Logger.Error($"执行{actionName}异常:{ex.Message}"); 171 | else 172 | exceptionAction.Invoke(ex); 173 | } 174 | } 175 | 176 | private void Invoke(Action action) 177 | { 178 | Dispatcher.UIThread.Post(action.Invoke); 179 | } 180 | 181 | private async Task InvokeAsync(Action action) 182 | { 183 | await Dispatcher.UIThread.InvokeAsync(action.Invoke); 184 | } 185 | 186 | 187 | #region 接收事件 188 | 189 | [EventHandler] 190 | private void ReceiveTcpStatusMessage(ChangeTCPStatusCommand message) 191 | { 192 | TcpHelper.SendCommand(new RequestTargetType()); 193 | _ = Log("发送命令查询目标终端类型是否是服务端"); 194 | } 195 | 196 | [EventHandler] 197 | private void ReceiveUdpStatusMessage(ChangeUDPStatusCommand message) 198 | { 199 | _ = Log("Udp组播订阅成功!"); 200 | } 201 | 202 | private void ReceiveTcpData() 203 | { 204 | // 开启线程接收数据 205 | Task.Run(async () => 206 | { 207 | while (!TcpHelper.IsRunning) await Task.Delay(TimeSpan.FromMilliseconds(10)); 208 | 209 | HandleRefreshCommand(); 210 | }); 211 | } 212 | 213 | /// 214 | /// 处理接收的Socket消息 215 | /// 216 | /// 217 | /// 218 | [EventHandler] 219 | private void ReceivedSocketMessage(SocketCommand message) 220 | { 221 | Logger.Info($"Dill command: {message}"); 222 | if (message.IsMessage()) 223 | { 224 | ReceivedSocketMessage(message.Message()); 225 | } 226 | else if (message.IsMessage()) 227 | { 228 | ReceivedSocketMessage(message.Message()); 229 | } 230 | else if (message.IsMessage()) 231 | { 232 | ReceivedSocketMessage(message.Message()); 233 | } 234 | else if (message.IsMessage()) 235 | { 236 | ReceivedSocketMessage(message.Message()); 237 | } 238 | else if (message.IsMessage()) 239 | { 240 | ReceivedSocketMessage(message.Message()); 241 | } 242 | else if (message.IsMessage()) 243 | { 244 | ReceivedSocketMessage(message.Message()); 245 | } 246 | else if (message.IsMessage()) 247 | { 248 | HandleRefreshCommand(); 249 | } 250 | else if (message.IsMessage()) 251 | { 252 | ReceivedSocketMessage(message.Message()); 253 | } 254 | } 255 | 256 | private void ReceiveUdpCommand(SocketCommand command) 257 | { 258 | if (command.IsMessage()) 259 | { 260 | ReceivedSocketMessage(command.MessageByNative()); 261 | } 262 | else if (command.IsMessage()) 263 | { 264 | ReceivedSocketMessage(command.MessageByNative()); 265 | } 266 | } 267 | 268 | private void ReceivedSocketMessage(ResponseTargetType response) 269 | { 270 | var type = (TerminalType)Enum.Parse(typeof(TerminalType), response.Type.ToString()); 271 | if (response.Type == (byte)TerminalType.Server) 272 | { 273 | _ = Log($"正确连接{type.GetDescription()},程序正常运行"); 274 | 275 | TcpHelper.SendCommand(new RequestUdpAddress()); 276 | _ = Log("发送命令获取Udp组播地址"); 277 | 278 | HandleRefreshCommand(); 279 | } 280 | else 281 | { 282 | _ = Log($"目标终端非服务端(type: {type.GetDescription()}),请检查地址是否配置正确(重点检查端口),即将断开连接", LogType.Error); 283 | } 284 | } 285 | 286 | private void ReceivedSocketMessage(ResponseUdpAddress response) 287 | { 288 | _ = Log($"收到Udp组播地址=》{response.Ip}:{response.Port}"); 289 | 290 | UdpHelper.Ip = response.Ip; 291 | UdpHelper.Port = response.Port; 292 | UdpHelper.Start(); 293 | UdpHelper.NewDataResponse += ReceiveUdpCommand; 294 | _ = Log("尝试订阅Udp组播"); 295 | } 296 | 297 | private void ReceivedSocketMessage(ResponseServiceInfo response) 298 | { 299 | _timestampStartYear = response.TimestampStartYear; 300 | var oldBaseInfo = BaseInfo; 301 | BaseInfo = 302 | $"更新时间【{response.LastUpdateTime.FromSpecialUnixTimeSecondsToDateTime(response.TimestampStartYear):yyyy:MM:dd HH:mm:ss fff}】:操作系统【{response.OS}】-内存【{response.MemorySize}GB】-处理器【{response.ProcessorCount}个】-硬盘【{response.DiskSize}GB】-带宽【{response.NetworkBandwidth}Mbps】"; 303 | 304 | Logger.Info(response.TaskId == default ? "收到服务端推送的基本信息" : "收到请求基本信息响应"); 305 | Logger.Info($"【旧】{oldBaseInfo}"); 306 | Logger.Info($"【新】{BaseInfo}"); 307 | _ = Log(BaseInfo); 308 | 309 | TcpHelper.SendCommand(new RequestProcessIDList() { TaskId = TcpHelper.GetNewTaskId() }); 310 | _ = Log("发送请求进程ID列表命令"); 311 | 312 | ClearData(); 313 | } 314 | 315 | private void ReceivedSocketMessage(ResponseProcessIDList response) 316 | { 317 | _processIdArray = response.IDList!; 318 | _ = Log($"收到进程ID列表,共{_processIdArray.Length}个进程"); 319 | 320 | TcpHelper.SendCommand(new RequestProcessList { TaskId = TcpHelper.GetNewTaskId() }); 321 | _ = Log("发送请求进程详细信息列表命令"); 322 | } 323 | 324 | private void ReceivedSocketMessage(ResponseProcessList response) 325 | { 326 | var processes = 327 | response.Processes?.ConvertAll(process => new ProcessItemModel(process, _timestampStartYear)); 328 | if (!(processes?.Count > 0)) return; 329 | 330 | _receivedProcesses.AddRange(processes); 331 | var filterData = FilterData(processes); 332 | Invoke(()=>DisplayProcesses.AddRange(filterData)); 333 | if (_receivedProcesses.Count == response.TotalSize) 334 | _processIdAndItems = _receivedProcesses.ToDictionary(process => process.PID); 335 | 336 | var msg = response.TaskId == default ? "收到推送" : "收到请求响应"; 337 | Logger.Info( 338 | $"{msg}【{response.PageIndex + 1}/{response.PageCount}】进程{processes.Count}条({_receivedProcesses.Count}/{response.TotalSize})"); 339 | } 340 | 341 | private void ReceivedSocketMessage(UpdateProcessList response) 342 | { 343 | if (_processIdAndItems == null) return; 344 | 345 | response.Processes?.ForEach(updateProcess => 346 | { 347 | if (_processIdAndItems.TryGetValue(updateProcess.Pid, out var point)) 348 | point.Update(updateProcess, _timestampStartYear); 349 | else 350 | throw new Exception($"收到更新数据包,遇到本地缓存不存在的进程:{updateProcess.Name}"); 351 | }); 352 | Logger.Info($"更新数据{response.Processes?.Count}条"); 353 | } 354 | 355 | private void ReceivedSocketMessage(Heartbeat response) 356 | { 357 | } 358 | 359 | #endregion 360 | 361 | #region 接收Udp数据 362 | 363 | private void ReceivedSocketMessage(UpdateRealtimeProcessList response) 364 | { 365 | void LogNotExistProcess(int index) 366 | { 367 | Console.WriteLine($"【实时】收到更新数据包,遇到本地缓存不存在的进程,索引:{index}"); 368 | } 369 | 370 | try 371 | { 372 | var startIndex = response.PageIndex * response.PageSize; 373 | var dataCount = response.Cpus.Length / 2; 374 | for (var i = 0; i < dataCount; i++) 375 | { 376 | if (_processIdArray?.Length > startIndex && _processIdAndItems?.Count > startIndex) 377 | { 378 | var processId = _processIdArray[startIndex]; 379 | if (_processIdAndItems.TryGetValue(processId, out var process)) 380 | { 381 | var cpu = BitConverter.ToInt16(response.Cpus, i * sizeof(Int16)); 382 | var memory = BitConverter.ToInt16(response.Memories, i * sizeof(Int16)); 383 | var disk = BitConverter.ToInt16(response.Disks, i * sizeof(Int16)); 384 | var network = BitConverter.ToInt16(response.Networks, i * sizeof(Int16)); 385 | process.Update(cpu, memory, disk, network); 386 | } 387 | else 388 | { 389 | LogNotExistProcess(startIndex); 390 | } 391 | } 392 | else 393 | { 394 | LogNotExistProcess(startIndex); 395 | } 396 | 397 | startIndex++; 398 | } 399 | 400 | Console.WriteLine($"【实时】更新数据{dataCount}条"); 401 | } 402 | catch (Exception ex) 403 | { 404 | Logger.Error($"【实时】更新数据异常:{ex.Message}"); 405 | } 406 | } 407 | 408 | private void ReceivedSocketMessage(UpdateGeneralProcessList response) 409 | { 410 | void LogNotExistProcess(int index) 411 | { 412 | Console.WriteLine($"【实时】收到更新一般数据包,遇到本地缓存不存在的进程,索引:{index}"); 413 | } 414 | 415 | try 416 | { 417 | var startIndex = response.PageIndex * response.PageSize; 418 | var dataCount = response.ProcessStatuses.Length; 419 | for (var i = 0; i < dataCount; i++) 420 | { 421 | if (_processIdArray?.Length > startIndex && _processIdAndItems?.Count > startIndex) 422 | { 423 | var processId = _processIdArray[startIndex]; 424 | if (_processIdAndItems.TryGetValue(processId, out var process)) 425 | { 426 | var processStatus = response.ProcessStatuses[i]; 427 | var alarmStatus = response.AlarmStatuses[i]; 428 | var gpu = BitConverter.ToInt16(response.Gpus, i * sizeof(short)); 429 | var gpuEngine = response.GpuEngine[i]; 430 | var powerUsage = response.PowerUsage[i]; 431 | var powerUsageTrend = response.PowerUsageTrend[i]; 432 | var updateTime = BitConverter.ToUInt32(response.UpdateTimes, i * sizeof(uint)); 433 | process.Update(_timestampStartYear, processStatus, alarmStatus, gpu, gpuEngine, powerUsage, 434 | powerUsageTrend, updateTime); 435 | } 436 | else 437 | { 438 | LogNotExistProcess(startIndex); 439 | } 440 | } 441 | else 442 | { 443 | LogNotExistProcess(startIndex); 444 | } 445 | 446 | startIndex++; 447 | } 448 | 449 | Console.WriteLine($"【实时】更新一般数据{dataCount}条"); 450 | } 451 | catch (Exception ex) 452 | { 453 | Logger.Error($"【实时】更新一般数据异常:{ex.Message}"); 454 | } 455 | } 456 | 457 | #endregion 458 | 459 | private async Task Log(string msg, LogType type = LogType.Info, bool showNotification = true) 460 | { 461 | if (type == LogType.Info) 462 | { 463 | Logger.Info(msg); 464 | } 465 | else if (type == LogType.Error) 466 | { 467 | Logger.Error(msg); 468 | } 469 | 470 | await ShowNotificationAsync(showNotification, msg, type); 471 | } 472 | 473 | private async Task ShowNotificationAsync(bool showNotification, string msg, LogType type) 474 | { 475 | if (!showNotification) return; 476 | 477 | var notificationType = type switch 478 | { 479 | LogType.Warn => NotificationType.Warning, 480 | LogType.Error => NotificationType.Error, 481 | _ => NotificationType.Information 482 | }; 483 | 484 | await InvokeAsync(() => NotificationManager?.Show(new Notification(title: "提示", msg, notificationType))); 485 | } 486 | } -------------------------------------------------------------------------------- /src/SocketTesting/SocketTest.Client/Views/MainWindow.axaml: -------------------------------------------------------------------------------- 1 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 21 | 21 22 | 23 | 24 | 27 | 31 | 34 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 58 | 59 | 60 | 62 |