From 68221dcae55a3771709511046006fd2e2c919395 Mon Sep 17 00:00:00 2001 From: Cxx0822 <1556464090@qq.com> Date: Sun, 19 Apr 2026 21:24:06 +0800 Subject: [PATCH] =?UTF-8?q?feat:=E5=88=9D=E5=A7=8B=E5=8C=96=E5=B7=A5?= =?UTF-8?q?=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 203 +++++++++++++++++++++++++++++++++++++ SocketHub.sln | 25 +++++ SocketHub/Program.cs | 139 +++++++++++++++++++++++++ SocketHub/SocketHub.csproj | 22 ++++ SocketHub/appsettings.json | 22 ++++ 5 files changed, 411 insertions(+) create mode 100644 .gitignore create mode 100644 SocketHub.sln create mode 100644 SocketHub/Program.cs create mode 100644 SocketHub/SocketHub.csproj create mode 100644 SocketHub/appsettings.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b7edd51 --- /dev/null +++ b/.gitignore @@ -0,0 +1,203 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017/2019/2022 cache/options directory +.vs/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config + +# NuGet Symbol Packages +*.snupkg + +# .NET Core SDK +project.fragment.lock.json +artifacts/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp \ No newline at end of file diff --git a/SocketHub.sln b/SocketHub.sln new file mode 100644 index 0000000..3fc121e --- /dev/null +++ b/SocketHub.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.13.35818.85 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SocketHub", "SocketHub\SocketHub.csproj", "{802FB65F-272C-4C6F-AF31-19881EF58FEC}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {802FB65F-272C-4C6F-AF31-19881EF58FEC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {802FB65F-272C-4C6F-AF31-19881EF58FEC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {802FB65F-272C-4C6F-AF31-19881EF58FEC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {802FB65F-272C-4C6F-AF31-19881EF58FEC}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {41885D59-8EAD-4685-8B0C-E90596F00A49} + EndGlobalSection +EndGlobal diff --git a/SocketHub/Program.cs b/SocketHub/Program.cs new file mode 100644 index 0000000..148bea5 --- /dev/null +++ b/SocketHub/Program.cs @@ -0,0 +1,139 @@ +using System.Buffers; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; +using SuperSocket.ProtoBase; +using SuperSocket.Server; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Host; +using SuperSocket.WebSocket.Server; + +var host = Host.CreateDefaultBuilder(args) + .ConfigureServices((context, services) => + { + + }) + .AsMultipleServerHostBuilder() + .AddServer(builder => + { + builder + .UsePackageHandler(async (session, package) => + { + Console.WriteLine($"Magic={package.Magic:X4}, Type={package.Type}, Len={package.Length}"); + await session.SendAsync(package.Payload); + }) + .ConfigureServerOptions((ctx, config) => + { + return config.GetSection("TcpServer"); + }); + }) + .AddWebSocketServer(builder => + { + builder + .UseWebSocketMessageHandler(async (session, package) => + { + Console.WriteLine($"[WebSocket] ${package.Message}"); + await session.SendAsync("ok"); + }) + .ConfigureServerOptions((ctx, config) => + { + return config.GetSection("WebSocketServer"); + }); + }) + .Build(); + +await host.RunAsync(); + +public class TcpService : SuperSocketService +{ + public TcpService(IServiceProvider serviceProvider, IOptions serverOptions) + : base(serviceProvider, serverOptions) + { + + } +} + +/// +/// 协议数据结构 +/// +/// 帧头标识 +/// 数据长度 +/// 数据类型 +/// 数据内容 +/// +public record ProtocolFrame( + ushort Magic, + ushort Length, + ushort Type, + byte[] Payload +); + +/// +/// 二进制解析器: 把 TCP 字节流 → 拆包 → 转成 ProtocolFrame +/// +public class BinaryPipelineFilter : FixedHeaderPipelineFilter +{ + /// + /// 固定头长度 + /// + public BinaryPipelineFilter() : base(6) + { + } + + /// + /// 从包头中解析出 Body 长度 + /// + /// 字节流 + /// Body 长度 + protected override int GetBodyLengthFromHeader(ref ReadOnlySequence buffer) + { + var reader = new SequenceReader(buffer); + + // 读取前2字节 → magic + reader.TryReadBigEndian(out ushort magic); + + // 再读2字节 → Length + reader.TryReadBigEndian(out ushort length); + + // 再读2字节 → Type + reader.TryReadBigEndian(out ushort type); + + // 校验帧头 + if (magic != 0x656D) + { + throw new Exception("非法帧头"); + } + + // 限制长度 + if (length == 0 || length > 8192) + { + throw new Exception("非法长度"); + } + + // 返回 Payload 长度 + return length; + } + + /// + /// 把完整字节包 → 转换成 ProtocolFrame + /// + /// 字节流 + /// ProtocolFrame + protected override ProtocolFrame DecodePackage(ref ReadOnlySequence buffer) + { + var reader = new SequenceReader(buffer); + + // 读取前2字节 → magic + reader.TryReadBigEndian(out ushort magic); + + // 再读2字节 → Length + reader.TryReadBigEndian(out ushort length); + + // 再读2字节 → Type + reader.TryReadBigEndian(out ushort type); + + var payload = buffer.Slice(6, length).ToArray(); + + // 构造ProtocolFrame + return new ProtocolFrame(magic, length, type, payload); + } +} \ No newline at end of file diff --git a/SocketHub/SocketHub.csproj b/SocketHub/SocketHub.csproj new file mode 100644 index 0000000..459a0df --- /dev/null +++ b/SocketHub/SocketHub.csproj @@ -0,0 +1,22 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + + + + + Always + + + + diff --git a/SocketHub/appsettings.json b/SocketHub/appsettings.json new file mode 100644 index 0000000..4cd0fee --- /dev/null +++ b/SocketHub/appsettings.json @@ -0,0 +1,22 @@ +{ + "serverOptions": { + "TcpServer": { + "name": "TcpServer", + "listeners": [ + { + "ip": "Any", + "port": 4040 + } + ] + }, + "WebSocketServer": { + "name": "WebSocket", + "listeners": [ + { + "ip": "Any", + "port": 5050 + } + ] + } + } +} \ No newline at end of file