├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── TinyFox.WebSocket.sln ├── WebSocket ├── README.md ├── TinyFox.WebSocket.csproj ├── WSContext.cs ├── WebSocket.cs └── WebSocketWorkerBase.cs └── test ├── App.config ├── MyWebSocketWorker.cs ├── Program.cs ├── Properties └── AssemblyInfo.cs ├── README.md ├── Startup.cs ├── packages.config ├── test.csproj └── wwwroot └── index.html /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 jws-admin 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 | # TinyFox.WebSocket 2 | WebSocket For TinyFox Or Other Any OWIN Server. 3 | 4 | TinyFox.WebSocket是一款工作在 TinyFox 或者其它 OWIN 宿主服务器上的 WebSocket 服务器端类库。 5 | -------------------------------------------------------------------------------- /TinyFox.WebSocket.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.28803.352 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TinyFox.WebSocket", "WebSocket\TinyFox.WebSocket.csproj", "{D52B40B7-6991-4CA8-8E74-9A7E185A046D}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "test", "test\test.csproj", "{01357E88-97DF-4A2B-A433-C0EF61117594}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {D52B40B7-6991-4CA8-8E74-9A7E185A046D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {D52B40B7-6991-4CA8-8E74-9A7E185A046D}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {D52B40B7-6991-4CA8-8E74-9A7E185A046D}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {D52B40B7-6991-4CA8-8E74-9A7E185A046D}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {01357E88-97DF-4A2B-A433-C0EF61117594}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {01357E88-97DF-4A2B-A433-C0EF61117594}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {01357E88-97DF-4A2B-A433-C0EF61117594}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {01357E88-97DF-4A2B-A433-C0EF61117594}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {8B01E461-82EB-4589-8C58-219E9034148B} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /WebSocket/README.md: -------------------------------------------------------------------------------- 1 | # WebSocket 2 | 这是 TinyFox 的 WebSocket 服务类,可以在所有的OWIN服务器上运行。 3 | -------------------------------------------------------------------------------- /WebSocket/TinyFox.WebSocket.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net45; netstandard2.0 5 | WebSocket For OWIN 6 | www.linuxdot.net 7 | true 8 | LiuBing 9 | www.linuxdot.net 10 | 1.1.0 11 | 1.1.0 12 | 1.2.1 13 | false 14 | MIT 15 | https://github.com/yuneike/TinyFox.WebSocket 16 | true 17 | 18 | 19 | 20 | true 21 | 22 | 23 | 24 | true 25 | 26 | 27 | 28 | bin\$(Configuration)\$(TargetFramework)\TinyFox.WebSocket.xml 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /WebSocket/WSContext.cs: -------------------------------------------------------------------------------- 1 | namespace TinyFox.WebSocket 2 | { 3 | using System; 4 | using System.Threading.Tasks; 5 | using System.Text; 6 | 7 | 8 | /// 9 | /// WebSocket会话上下文对象 10 | /// 一个会话对象代表一个具体的连接 11 | /// 12 | public class WSContext 13 | { 14 | 15 | 16 | #region <私有变量> 17 | 18 | /// 19 | /// 与本上下文关联的websocket对象 20 | /// 21 | private WebSocket _ws = null; 22 | 23 | #endregion 24 | 25 | 26 | 27 | #region <公共字段> 28 | 29 | /// 30 | /// 开发者附加在该会话的对象 31 | /// 32 | public object Tag = null; 33 | 34 | 35 | #endregion 36 | 37 | 38 | 39 | #region <公共属性> 40 | 41 | /// 42 | /// 会话的本地IP地址 43 | /// 44 | public string LocalIpAddress { get; private set; } 45 | 46 | /// 47 | /// 会话的本地端口号 48 | /// 49 | public int LocalPort { get; private set; } 50 | 51 | /// 52 | /// 客户端IP地址 53 | /// 54 | public string RemoteIpAddress { get; private set; } 55 | 56 | /// 57 | /// 客户端端口号 58 | /// 59 | public int RemotePort { get; private set; } 60 | 61 | /// 62 | /// 访问的URL路径 63 | /// 64 | public string RequestPath { get; private set; } 65 | 66 | /// 67 | /// 访问的查询字串 68 | /// 69 | public string QueryString { get; private set; } 70 | 71 | 72 | #endregion 73 | 74 | 75 | 76 | #region <构造与析构> 77 | 78 | /// 79 | /// 实例化一个WSContext上下文对象 80 | /// 81 | /// 82 | public WSContext(WebSocket ws) 83 | { 84 | _ws = ws; 85 | 86 | LocalIpAddress = ws.LocalIpAddress; 87 | LocalPort = ws.LocalPort; 88 | RemoteIpAddress = ws.RemoteIpAddress; 89 | RemotePort = ws.RemotePort; 90 | RequestPath = ws.RequestPath; 91 | QueryString = ws.Query; 92 | } 93 | 94 | 95 | /// 96 | /// 析构函数 97 | /// 98 | ~WSContext() 99 | { 100 | if (_ws == null) return; 101 | _ws.Close(); 102 | _ws = null; 103 | } 104 | 105 | #endregion 106 | 107 | 108 | 109 | #region <公用方法> 110 | 111 | 112 | /// 113 | /// 向客户端非阻塞发送文本数据(utf8字符集) 114 | /// 115 | /// 116 | public void SendMessage(string msg) { _ws.SendMessage(msg); } 117 | 118 | /// 119 | /// 向客户端非阻塞发送文本数据 120 | /// 121 | /// 文本 122 | /// 字符集 123 | public void SendMessage(string text, Encoding encoding) { _ws.SendMessage(text, encoding); } 124 | 125 | /// 126 | /// 异步发送文本数据 127 | /// 128 | /// 文本 129 | /// 字符集 130 | /// 131 | public async Task SendMessageAsync(string msg, Encoding encoding) { await _ws.SendMessageAsync(msg, encoding); } 132 | 133 | /// 134 | /// 向客户端发送二进制数据 135 | /// 136 | /// 数据 137 | /// 是否是一个继续发送任务的最后一个片断 138 | public void SendBytes(ArraySegment buffer, bool isEndOfMessage = true) { _ws.SendBytes(buffer, isEndOfMessage); } 139 | 140 | 141 | /// 142 | /// 异步发送二进制数据 143 | /// 144 | /// 数据 145 | /// 是否是最后一块数据 146 | /// 147 | public async Task SendBytesAsync(ArraySegment buffer, bool isEndOfMsg = true) { await _ws.SendBytesAsync(buffer, isEndOfMsg); } 148 | 149 | /// 150 | /// 关闭与客户端的连接 151 | /// 152 | public void Close(int code = 1000, string reason = null) { _ws.Close(code, reason); } 153 | 154 | 155 | #endregion 156 | 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /WebSocket/WebSocket.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using System.Threading; 6 | 7 | namespace TinyFox.WebSocket 8 | { 9 | 10 | 11 | #region 12 | 13 | // 异步接受客户端连接(握手)的方法代理 14 | using WebSocketAccept = 15 | Action, //Accept字典,可以为null 16 | Func< //握手成功后的回调函数 17 | IDictionary, //包含 SendAsync, ReceiveAsync, CloseAsync 等关键字的字典 18 | Task> //返回给服务器的表示本回调函数是否执行完成的字典 19 | >; 20 | 21 | 22 | // 异步关闭连的函数代理 23 | using WebSocketCloseAsync = 24 | Func; 29 | 30 | // 异步读取数据的函数代理 31 | using WebSocketReceiveAsync = 32 | Func, // 接受数据的缓冲区 33 | CancellationToken, // 传递操作是否取消 34 | Task< // 返回值 35 | Tuple< 36 | int, // 第一分量,表示接收到的数据类型(1表示本文数据,2表示二进制数据,8表示对方关闭连接) 37 | bool, // 第二分量,表示是否是一个数据帖的最后一块或者独立块 38 | int // 第三分量,表示有效数据的长度 39 | > 40 | > 41 | >; 42 | 43 | 44 | // 异步发送数据的函数代表 45 | using WebSocketSendAsync = 46 | Func, // 待发送的缓冲区 47 | int, // 数据类型,只能是1、2、8 48 | bool, // 这一块数据是否是一条信息的最后一块 49 | CancellationToken, // 取消任务的通知 50 | Task // 返回值 51 | >; 52 | 53 | 54 | #endregion 55 | 56 | 57 | /// 58 | /// WebSocket对象 59 | /// 60 | public sealed class WebSocket 61 | { 62 | 63 | /**************************************************************** 64 | * 这是一个对OWIN WebSocket 进行了一定程度封装的对象, 65 | * 已经较为完整,不建议使用者随意修改,修改要特别小心! 66 | * ---------------------------------------------------------- 67 | * 包括4个方法和三个代理(你可以改为事件) 68 | * ========================================================== 69 | * * 公开的4个方法分别是: 70 | * Accept: 接受远端WebSocket连接 71 | * StartRead: 开始接收数据 72 | * Send: 发送文本数据 73 | * Close: 关闭与完端的连接 74 | * ----------------------------------------------------------- 75 | * 3个委托是: 76 | * OnSend: 表示数据发送完成 77 | * OnRead: 表示数据读取完成 78 | * OnClose: 表示远端主动提供断开连接 79 | **************************************************************/ 80 | 81 | 82 | #region <共用委托> 83 | 84 | /// 85 | /// 表示文本数据读取完成的委托 86 | /// 87 | /// 88 | /// 89 | public delegate void DelegateReadComplete(WebSocket ws, string message); 90 | 91 | /// 92 | /// 表示发送了二进制数据读取事件的委托 93 | /// 94 | /// 95 | /// 96 | /// 97 | public delegate void DelegateReadByteComplete(WebSocket ws, ArraySegment buffer, bool endOfMessage); 98 | 99 | /// 100 | /// 表示文本数据发送完成的委托 101 | /// 102 | /// 103 | public delegate void DelegateWriteComplete(WebSocket ws); 104 | 105 | /// 106 | /// 表示客户端发生关闭事件的委托 107 | /// 108 | /// 109 | public delegate void DelegateCloseComplete(WebSocket ws); 110 | 111 | #endregion 112 | 113 | 114 | 115 | #region <私有变量> 116 | 117 | /// 118 | /// 进行连接的函数 119 | /// 120 | private WebSocketAccept _accept; 121 | 122 | 123 | /// 124 | /// 发送数据的函数 125 | /// 126 | private WebSocketSendAsync _sendAsync; 127 | 128 | /// 129 | /// 接收数据的函数 130 | /// 131 | private WebSocketReceiveAsync _receiveAsync; 132 | 133 | /// 134 | /// 关闭连接的函数 135 | /// 136 | private WebSocketCloseAsync _closeAsync; 137 | 138 | 139 | /// 140 | /// 是否已经关闭 141 | /// 142 | private bool _isClosed = true; 143 | 144 | /// 145 | /// 是否已经开始读取循环 146 | /// 147 | private int _reading; 148 | 149 | /// 150 | /// 用于保存前边收到的,还不完整的数据 151 | /// 152 | private byte[] _lastReadData; 153 | 154 | 155 | /// 156 | /// websocket工作任务完成状态 157 | /// 158 | private TaskCompletionSource _webSocketCompSource; 159 | 160 | /// 161 | /// 异步Accept完成信号 162 | /// 163 | private AutoResetEvent _acceptwaiter = new AutoResetEvent(false); 164 | 165 | 166 | 167 | #endregion 168 | 169 | 170 | 171 | #region <共有字段> 172 | 173 | /// 174 | /// 数据读取完成 175 | /// 176 | public DelegateReadComplete OnReadMessage; 177 | 178 | /// 179 | /// 二制制数据收取事件 180 | /// 181 | public DelegateReadByteComplete OnReadBytes; 182 | 183 | /// 184 | /// 连接已经断开 185 | /// 186 | public DelegateCloseComplete OnClose; 187 | 188 | /// 189 | /// 数据发送完成 190 | /// 191 | public DelegateWriteComplete OnSend; 192 | 193 | 194 | #endregion 195 | 196 | 197 | 198 | #region <共用属性> 199 | 200 | /// 201 | /// 客户端IP地址 202 | /// 203 | public string RemoteIpAddress { get; private set; } 204 | 205 | /// 206 | /// 客户端端口 207 | /// 208 | public int RemotePort { get; private set; } 209 | 210 | /// 211 | /// 本地IP地址 212 | /// 213 | public string LocalIpAddress { get; private set; } 214 | 215 | /// 216 | /// 本地端口 217 | /// 218 | public int LocalPort { get; private set; } 219 | 220 | 221 | /// 222 | /// 请求的路径 223 | /// 224 | public string RequestPath { get; private set; } 225 | 226 | 227 | /// 228 | /// URL查询字串 229 | /// 230 | public string Query { get; private set; } 231 | 232 | /// 233 | /// WebSocket运行状态 234 | /// 235 | public Task WorkTask { get { return _webSocketCompSource.Task; } } 236 | 237 | 238 | #endregion 239 | 240 | 241 | 242 | #region <构造与析构> 243 | 244 | 245 | /// 246 | /// 构造函数 247 | /// 248 | /// Owin字典 249 | public WebSocket(IDictionary owinEnv) 250 | { 251 | // 检查是否是websocket请求 252 | if (!owinEnv.IsWebSocket()) throw new Exception("Not Is WebSocket Request."); 253 | 254 | // 获取Accept方法 255 | _accept = owinEnv.Get("websocket.Accept"); 256 | if (_accept == null) throw new Exception("Not Is Websocket Request"); 257 | 258 | // SERVER 259 | RemoteIpAddress = owinEnv.Get("server.RemoteIpAddress"); 260 | RemotePort = int.Parse(owinEnv.Get("server.RemotePort")); 261 | LocalIpAddress = owinEnv.Get("server.LocalIpAddress"); 262 | LocalPort = int.Parse(owinEnv.Get("server.LocalPort")); 263 | //var islocal = owinEnv.Get("server.IsLocal"); 264 | 265 | // OWIN 266 | RequestPath = owinEnv.Get("owin.RequestPath"); 267 | Query = owinEnv.Get("owin.RequestQueryString"); 268 | 269 | _webSocketCompSource = new TaskCompletionSource(); 270 | // owinEnv.Get("owin.RequestMethod"); GET/POST/.... 271 | 272 | } 273 | 274 | #endregion 275 | 276 | 277 | 278 | #region <接受连接与关闭连接的操作> 279 | 280 | 281 | 282 | /// 283 | /// 响应客户端握手请求 284 | /// 285 | /// 返回真表示按WebSocket的方式成功连接 286 | internal bool Accept(IDictionary param = null) 287 | { 288 | if (_accept == null) return false; 289 | 290 | try 291 | { _accept(param, AcceptCallback); } 292 | catch { return false; } 293 | 294 | _acceptwaiter.WaitOne(); 295 | return _isClosed == false; 296 | 297 | } 298 | 299 | /// 300 | /// 握手完成后的回调函数 301 | /// 302 | /// 底层提供的SendAsync、ReceiveAsync等方法 303 | /// 304 | private Task AcceptCallback(IDictionary env) 305 | { 306 | if (env == null) 307 | { 308 | _acceptwaiter.Set(); 309 | return Task.Delay(0); 310 | } 311 | 312 | //从字典中取出服务器提供的WebSocket操作方法 313 | _sendAsync = env.Get("websocket.SendAsync"); 314 | _receiveAsync = env.Get("websocket.ReceiveAsync"); 315 | _closeAsync = env.Get("websocket.CloseAsync"); 316 | 317 | //标记连接成功 318 | _isClosed = false; 319 | _acceptwaiter.Set(); 320 | 321 | //通知服务器(容器),表示连接事件已经处理完成 322 | return Task.Delay(0); 323 | 324 | } 325 | 326 | 327 | 328 | /// 329 | /// 关闭连接 330 | /// 331 | /// 状态码 332 | /// 关闭原因 333 | internal void Close(int code = 1000, string reason = null) 334 | { 335 | if (_isClosed) return; 336 | _isClosed = true; 337 | 338 | if (code < 1000) code = 1000; 339 | if (code >= 5000) code = 4999; 340 | 341 | _closeAsync(code, reason, CancellationToken.None).ContinueWith(t => 342 | { 343 | //清理异常 344 | if (t.IsFaulted && t.Exception != null) t.Exception.Handle(_ => true); 345 | 346 | //通知服务层,当前WebScoket会话已经完成 347 | _webSocketCompSource.TrySetResult(1); 348 | }); 349 | } 350 | 351 | 352 | #endregion 353 | 354 | 355 | 356 | #region <发送操作> 357 | 358 | /// 359 | /// 是否正在发送数据(发送还没有完成的标记) 360 | /// 361 | private bool _writting = false; 362 | 363 | 364 | 365 | /// 366 | /// 非阻塞发送以字节数组表示的文本内容 367 | /// 强调:必须是UTF8编码的文本数据 368 | /// 369 | /// UTF8文本的字节数据 370 | private void SendTextBytes(byte[] bytMessage) 371 | { 372 | if (bytMessage == null) 373 | { 374 | var err = new ArgumentNullException(); 375 | _webSocketCompSource.TrySetException(err); 376 | throw err; 377 | } 378 | 379 | if (_isClosed) throw new Exception("WebSocket Is Closed."); 380 | if (_writting) throw new Exception("WebSocket Is Writting."); 381 | 382 | try 383 | { 384 | _writting = true; 385 | var t = _sendAsync(new ArraySegment(bytMessage), 1, true, CancellationToken.None); 386 | t.ContinueWith(InternalWriteComplete); 387 | } 388 | catch (Exception e) 389 | { 390 | _writting = false; 391 | _webSocketCompSource.TrySetException(e); 392 | throw e; 393 | } 394 | } 395 | 396 | 397 | 398 | 399 | /// 400 | /// 非阻塞发送UTF8字符集文本 401 | /// 402 | /// UTF8文本内容 403 | public void SendMessage(string message) 404 | { 405 | SendTextBytes(Encoding.UTF8.GetBytes(message)); 406 | } 407 | 408 | /// 409 | /// 发送指的字符集的文本 410 | /// 411 | /// 内容 412 | /// 字符集 413 | public void SendMessage(string message, Encoding encoding) 414 | { 415 | SendTextBytes(encoding.GetBytes(message)); 416 | } 417 | 418 | /// 419 | /// 异步发送文本数据 420 | /// 421 | /// 422 | /// 423 | public async Task SendMessageAsync(string message, Encoding encoding) 424 | { 425 | 426 | if (message == null) throw new ArgumentNullException("message"); 427 | if (_isClosed) throw new Exception("WebSocket Is Closed."); 428 | if (_writting) throw new Exception("WebSocket Is Writting."); 429 | 430 | var bytMessage = encoding.GetBytes(message); 431 | try 432 | { 433 | _writting = true; 434 | await _sendAsync(new ArraySegment(bytMessage), 1, true, CancellationToken.None); 435 | _writting = false; 436 | } 437 | catch (Exception e) 438 | { 439 | _writting = false; 440 | _webSocketCompSource.TrySetException(e); 441 | throw e; 442 | } 443 | } 444 | 445 | 446 | 447 | 448 | /// 449 | /// 非阻塞发送二进制数据 450 | /// 451 | /// 二进制数据 452 | /// 本次发送是否是当前发送任务的最后一次 453 | public void SendBytes(ArraySegment buffer, bool isEndMessage) 454 | { 455 | 456 | if (_isClosed) throw new Exception("WebSocket Is Closed."); 457 | if (_writting) throw new Exception("WebSocket Is Writting."); 458 | 459 | try 460 | { 461 | _writting = true; 462 | var t = _sendAsync(buffer, 2, isEndMessage, CancellationToken.None); 463 | t.ContinueWith(InternalWriteComplete); 464 | } 465 | catch (Exception e) 466 | { 467 | _writting = false; 468 | _webSocketCompSource.TrySetException(e); 469 | throw e; 470 | } 471 | } 472 | 473 | 474 | /// 475 | /// 异步发送二制数数据 476 | /// 477 | /// 478 | /// 479 | /// 480 | public async Task SendBytesAsync(ArraySegment buffer, bool isEndMessage) 481 | { 482 | 483 | if (_isClosed) throw new Exception("WebSocket Is Closed."); 484 | if (_writting) throw new Exception("WebSocket Is Writting."); 485 | 486 | try 487 | { 488 | _writting = true; 489 | await _sendAsync(buffer, 2, isEndMessage, CancellationToken.None); 490 | _writting = false; 491 | } 492 | catch (Exception e) 493 | { 494 | _writting = false; 495 | _webSocketCompSource.TrySetException(e); 496 | throw e; 497 | } 498 | } 499 | 500 | 501 | 502 | /// 503 | /// 发送完成的回调函数 504 | /// 505 | /// 506 | private void InternalWriteComplete(Task task) 507 | { 508 | _writting = false; 509 | 510 | // 如果任务失败 511 | if (task.IsCanceled || task.IsFaulted) 512 | { 513 | _isClosed = true; 514 | if (task.IsFaulted && task.Exception != null) { task.Exception.Handle(_ => true); } 515 | 516 | OnClose?.Invoke(this); OnClose = null; 517 | _webSocketCompSource.TrySetResult(1); 518 | return; 519 | } 520 | 521 | 522 | // 通知应用层 523 | 524 | try 525 | { 526 | if (OnSend == null) return; 527 | OnSend(this); 528 | } 529 | catch (Exception e) 530 | { 531 | _webSocketCompSource.TrySetException(e); 532 | throw e; 533 | } 534 | } 535 | 536 | 537 | #endregion 538 | 539 | 540 | 541 | #region <接收操作> 542 | 543 | /// 544 | /// 开始接收客户数据(无阻塞) 545 | /// 546 | internal void StartAsync() 547 | { 548 | if (_isClosed) throw new Exception("WebSocket Is Closed."); 549 | if (Interlocked.CompareExchange(ref _reading, 1, 0) == 1) return; 550 | 551 | InternalRealRead(new byte[1024 * 32]); //接收缓冲区 552 | } 553 | 554 | /// 555 | /// 内部方法:接收数据 556 | /// 557 | /// 558 | private void InternalRealRead(byte[] buffer) 559 | { 560 | if (_isClosed) return; 561 | var arraySeg = new ArraySegment(buffer); 562 | 563 | //开始异步接收数据 564 | _receiveAsync(arraySeg, CancellationToken.None).ContinueWith(_t => 565 | { 566 | //如果出现了异常 567 | if (_t.IsFaulted || _t.IsCanceled) 568 | { 569 | _isClosed = true; 570 | OnClose?.Invoke(this); OnClose = null; 571 | if (_t.IsFaulted) { if (_t.Exception != null) _t.Exception.Handle(_ => true); }; 572 | _webSocketCompSource.TrySetResult(1); 573 | return; 574 | } 575 | 576 | //处理接收到的数据 577 | InternalReadComplte(arraySeg, _t.Result.Item1, _t.Result.Item2, _t.Result.Item3); 578 | }); 579 | } 580 | 581 | 582 | /// 583 | /// 内部方法:数据接收成功的回调函数 584 | /// 585 | /// 586 | /// 587 | /// 588 | /// 589 | private void InternalReadComplte(ArraySegment buffer, int type, bool endOfMessage, int size) 590 | { 591 | 592 | // 只接受客户端文本数据,否则关闭,如果需要接收二进制数据,请自行添加处理方法 593 | // type==8:对端已关闭; 594 | // type =2:二进制数据, 本类目前暂不作支持二进制支持,可以自行扩展 595 | if (type == 8) 596 | { 597 | _isClosed = true; 598 | 599 | try 600 | { _closeAsync(1000, null, CancellationToken.None); } 601 | catch { } 602 | 603 | if (OnClose != null) { OnClose(this); OnClose = null; } 604 | _webSocketCompSource.TrySetResult(1); 605 | return; 606 | } 607 | 608 | // 如果是二进制数据 609 | if (type == 2) 610 | { 611 | var byts = new byte[size]; 612 | Buffer.BlockCopy(buffer.Array, 0, byts, 0, size); 613 | 614 | //通知应用层 615 | OnReadBytes?.Invoke(this, new ArraySegment(byts), endOfMessage); 616 | 617 | //继续接收 618 | InternalRealRead(buffer.Array); 619 | return; 620 | } 621 | 622 | 623 | // 如果一帧数据已经完成 624 | if (endOfMessage) 625 | { 626 | var lastSize = _lastReadData == null ? 0 : _lastReadData.Length; 627 | var data = new byte[size + lastSize]; 628 | if (lastSize != 0) Buffer.BlockCopy(_lastReadData, 0, data, 0, lastSize); 629 | Buffer.BlockCopy(buffer.Array, 0, data, lastSize, size); 630 | _lastReadData = null; 631 | 632 | //通知应用层 633 | OnReadMessage?.Invoke(this, Encoding.UTF8.GetString(data)); 634 | 635 | //继续接收 636 | InternalRealRead(buffer.Array); 637 | return; 638 | } 639 | 640 | 641 | // 不完整数据帧,保存起来 642 | var oldSize = _lastReadData == null ? 0 : _lastReadData.Length; 643 | var tmpData = new byte[oldSize + size]; 644 | if (oldSize > 0) Buffer.BlockCopy(_lastReadData, 0, tmpData, 0, oldSize); 645 | Buffer.BlockCopy(buffer.Array, 0, tmpData, oldSize, size); 646 | _lastReadData = tmpData; 647 | 648 | //继续接收 649 | InternalRealRead(buffer.Array); 650 | 651 | } 652 | 653 | #endregion 654 | 655 | 656 | 657 | #region <静态方法> 658 | 659 | /// 660 | /// 当前请求是否是WebSocket连接请求 661 | /// 662 | /// Owin字典 663 | /// 664 | public static bool IsWebSocket(IDictionary env) 665 | { 666 | return env.IsWebSocket(); 667 | } 668 | 669 | #endregion 670 | 671 | } 672 | 673 | 674 | #region <其它> 675 | 676 | 677 | /// 678 | /// Dictionary扩展类 679 | /// 680 | internal static class DictionaryExtensions 681 | { 682 | /// 683 | /// 获取指定的键值 684 | /// 685 | /// 值的类型 686 | /// 当前字典 687 | /// 键 688 | /// 689 | internal static T Get(this IDictionary dictionary, string key) 690 | { 691 | return dictionary.TryGetValue(key, out object value) ? (T)value : default(T); 692 | } 693 | 694 | /// 695 | /// 是否是WebSocket连接请求 696 | /// 697 | /// 698 | /// 699 | internal static bool IsWebSocket(this IDictionary env) 700 | { 701 | return env != null && env.Keys.Contains("websocket.Accept"); 702 | } 703 | } 704 | 705 | #endregion 706 | 707 | } 708 | -------------------------------------------------------------------------------- /WebSocket/WebSocketWorkerBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | 5 | namespace TinyFox.WebSocket 6 | { 7 | 8 | /// 9 | /// 自定义WebSocket工作器的基类 10 | /// 11 | public abstract class WebSocketWorkerBase 12 | { 13 | 14 | /*************************************************************** 15 | * 注意:不建议开发者随意修改本类; 16 | * 即命名修改,也要小心,要尽量简洁,确保无错 17 | * *************************************************************/ 18 | 19 | 20 | 21 | #region <变量定义> 22 | 23 | 24 | /// 25 | /// 与本自定义绑定的WebSocket实例(子类可读) 26 | /// 27 | private readonly WebSocket _webSocket; 28 | 29 | /// 30 | /// 与webSocket实例绑定的“会话对话” 31 | /// 32 | private WSContext _content; 33 | 34 | #endregion; 35 | 36 | 37 | 38 | #region <初始化与开始WebSocket交互的方法实现> 39 | 40 | /// 41 | /// MyWebSocket构造函数 42 | /// 43 | /// 44 | public WebSocketWorkerBase(IDictionary owinenv) 45 | { 46 | 47 | _webSocket = new WebSocket(owinenv) 48 | { 49 | OnSend = (ws) => OnSendComplete(_content), 50 | OnClose = (ws) => OnClose(_content), 51 | OnReadMessage = (ws, txt) => OnMessage(_content, txt), 52 | OnReadBytes = (ws, byts, end) => OnReadyBytes(_content, byts, end) 53 | }; 54 | } 55 | 56 | 57 | 58 | /// 59 | /// 完成与客户端握手并开启数据交流过程 60 | /// 61 | ///用于WebSocket握手响应用的参数 62 | /// 63 | public Task Open(IDictionary param = null) 64 | { 65 | //尝试握手,同意请求 66 | //如果握手成功 67 | if (_webSocket.Accept(param)) 68 | { 69 | _content = new WSContext(_webSocket); 70 | 71 | //激活OnAccept事件,通知应用层握手已经完成 72 | OnAccept(_content); 73 | 74 | //开始接受远端数据 75 | //本方法只需在连接成功后调用一次,然后就能不断继续。 76 | _webSocket.StartAsync(); 77 | 78 | 79 | //返回WebSocket工作任务 80 | return _webSocket.WorkTask; 81 | } 82 | 83 | //如果握手失败 84 | Console.WriteLine("Error: 与客户端握手失败, 客户端 IP 地址是: {0}", _webSocket.RemoteIpAddress); 85 | 86 | //返回(失败的)完成任务 87 | return Task.FromResult(new Exception("WebSocket Accept Error.")); 88 | } 89 | 90 | 91 | 92 | #endregion 93 | 94 | 95 | 96 | #region <定义需要子类具体实现的方法> 97 | 98 | 99 | 100 | /// 101 | /// 与客户端握手完成事件 102 | /// 103 | ///当前会话对象 104 | protected virtual void OnAccept(WSContext content) { } 105 | 106 | /// 107 | /// 发送完成事件 108 | /// 109 | /// 会话对象 110 | protected abstract void OnSendComplete(WSContext content); 111 | 112 | 113 | /// 114 | /// 接收到客户端文本数据的事件 115 | /// 116 | /// 会话对象 117 | /// 内容 118 | protected abstract void OnMessage(WSContext content, string message); 119 | 120 | /// 121 | /// 接收到客户端发送过来的一段二进制数据的事件 122 | /// 123 | /// WS会话对象 124 | /// 数据 125 | /// 是否是连续数据块的最后一块数据 126 | protected abstract void OnReadyBytes(WSContext context, ArraySegment buffer, bool endOfMessage); 127 | 128 | /// 129 | /// 客户端关闭事件 130 | /// 131 | /// 会话对象 132 | protected abstract void OnClose(WSContext content); 133 | 134 | 135 | #endregion 136 | 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /test/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /test/MyWebSocketWorker.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using TinyFox.WebSocket; 4 | 5 | namespace test 6 | { 7 | /// 8 | /// 自定义的WebSocket工作类 9 | /// 10 | public sealed class MyWebSocketWorker : WebSocketWorkerBase 11 | { 12 | 13 | #region <构造函数> 14 | 15 | /// 16 | /// 构造函数 17 | /// 18 | /// OWIN字典 19 | public MyWebSocketWorker(IDictionary reqEnv) : base(reqEnv) { } 20 | 21 | #endregion 22 | 23 | 24 | #region <对父类事件的具体实现> 25 | 26 | 27 | /// 28 | /// 有新用户连接过来并且成功完成了握手等操作 29 | /// 30 | /// 与新连接绑定的"会话对象" 31 | protected override void OnAccept(WSContext content) 32 | { 33 | // 可以做一些初始化工作,比如登记客户IP地址之类的事情 34 | // var rip = content.RemoteIpAddress; 35 | // var url = content.RequestPath; 36 | // content.Tag = "xxx"; 37 | } 38 | 39 | 40 | /// 41 | /// 接到到了数据的事件 42 | /// 43 | /// 会话对象 44 | /// 消息内容 45 | protected override void OnMessage(WSContext content, string message) 46 | { 47 | 48 | //约定:如果客户端发来 "exit" "close" 字串 49 | //服务器就关闭这个连接 50 | if (message == "exit" || message == "close") 51 | { 52 | //服务器关闭会话 53 | content.Close(); 54 | return; 55 | } 56 | 57 | //回应客户端发送过来的内容 58 | content.SendMessage(message); 59 | } 60 | 61 | /// 62 | /// 收到二进制数据 63 | /// 64 | /// 65 | /// 66 | /// 67 | protected override void OnReadyBytes(WSContext context, ArraySegment buffer, bool endOfMessage) 68 | { 69 | throw new NotImplementedException(); 70 | } 71 | 72 | /// 73 | /// 数据发送完成的事件 74 | /// 75 | /// 会话对象 76 | protected override void OnSendComplete(WSContext content) 77 | { 78 | 79 | // your code ... 80 | 81 | /// ..... //// 82 | } 83 | 84 | 85 | 86 | /// 87 | /// 客户端关闭连接事件 88 | /// 89 | /// 会话对象 90 | protected override void OnClose(WSContext content) 91 | { 92 | 93 | // your code; 94 | } 95 | 96 | #endregion 97 | 98 | 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /test/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Threading; 7 | 8 | 9 | using TinyFox; 10 | 11 | namespace test 12 | { 13 | class Program 14 | { 15 | static void Main(string[] args) 16 | { 17 | TinyFoxService.Port = 8080; 18 | 19 | TinyFoxService.Start(new Startup().OwinMain); 20 | 21 | while (true) { 22 | Thread.Sleep(1000); 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /test/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // 有关程序集的一般信息由以下 6 | // 控制。更改这些特性值可修改 7 | // 与程序集关联的信息。 8 | [assembly: AssemblyTitle("test")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("test")] 13 | [assembly: AssemblyCopyright("Copyright © 2019")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // 将 ComVisible 设置为 false 会使此程序集中的类型 18 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 19 | //请将此类型的 ComVisible 特性设置为 true。 20 | [assembly: ComVisible(false)] 21 | 22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 23 | [assembly: Guid("01357e88-97df-4a2b-a433-c0ef61117594")] 24 | 25 | // 程序集的版本信息由下列四个值组成: 26 | // 27 | // 主版本 28 | // 次版本 29 | // 生成号 30 | // 修订号 31 | // 32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 33 | //通过使用 "*",如下所示: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /test/README.md: -------------------------------------------------------------------------------- 1 | # Class Text 2 | 这是测试项目 3 | -------------------------------------------------------------------------------- /test/Startup.cs: -------------------------------------------------------------------------------- 1 | /*************************************************************** 2 | * WebSocket 应用示例 之二 3 | * ============================================================= 4 | * 本DEMO的目的意义: 5 | * 演示封装一个 WebSocket 对象 6 | * 7 | * 使用方法:将编译得到的dll放到网站的bin文件夹中。 8 | * *************************************************************/ 9 | 10 | 11 | #region 12 | 13 | using System.Collections.Generic; 14 | using System.Text; 15 | using System.Threading.Tasks; 16 | using System.IO; 17 | using TinyFox.WebSocket; 18 | 19 | #endregion 20 | 21 | 22 | namespace test 23 | { 24 | 25 | /// 26 | /// 为Jexus/Tinyfox提示的适配器 27 | /// 28 | public class Startup 29 | { 30 | 31 | 32 | 33 | /// 34 | /// OWIN适配器的主函数 35 | /// 36 | /// 37 | /// 38 | public Task OwinMain(IDictionary env) 39 | { 40 | 41 | //检查是否是WebSocket会话请求 42 | if (WebSocket.IsWebSocket(env)) 43 | { 44 | return new MyWebSocketWorker(env).Open(); 45 | //注:Open方法可以带参数 46 | //如:Open(new Dictionary { {"websocket.SubProtocol","yourxxx"} }); 47 | } 48 | 49 | 50 | //如果不是websocket请求,就接普通OWIN处理 51 | return ProcessOtherRequest(env); 52 | } 53 | 54 | 55 | 56 | /// 57 | /// 普通OWIN请求的处理函数 58 | /// 59 | /// 60 | /// 61 | private Task ProcessOtherRequest(IDictionary env) 62 | { 63 | 64 | // 从字典中获取向客户(浏览器)发送数据的“流”对象 65 | ///////////////////////////////////////////////////////// 66 | var responseStream = env["owin.ResponseBody"] as Stream; 67 | 68 | // 你准备发送的数据 69 | const string outString = "Jexus Owin ServerJexus Owin Server!

Jexus Owin Server,放飞您灵感的翅膀...

\r\n"; 70 | var outBytes = Encoding.UTF8.GetBytes(outString); 71 | 72 | // 从参数字典中获取Response HTTP头的字典对象 73 | var responseHeaders = env["owin.ResponseHeaders"] as IDictionary; 74 | 75 | // 设置必要的http响应头 76 | //////////////////////////////////////////////////////////////// 77 | 78 | // 设置 Content-Type头 79 | responseHeaders.Add("Content-Type", new[] { "text/html; charset=utf-8" }); 80 | 81 | 82 | // 把正文写入流中,发送给浏览器 83 | responseStream.Write(outBytes, 0, outBytes.Length); 84 | 85 | 86 | return Task.FromResult(1); 87 | 88 | } 89 | 90 | 91 | } 92 | 93 | 94 | } 95 | -------------------------------------------------------------------------------- /test/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /test/test.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {01357E88-97DF-4A2B-A433-C0EF61117594} 8 | Exe 9 | test 10 | test 11 | v4.5.1 12 | 512 13 | true 14 | 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | ..\packages\Owin.1.0\lib\net40\Owin.dll 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | ..\packages\TinyFox.4.1.1\lib\net451\TinyFox.dll 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | {d52b40b7-6991-4ca8-8e74-9a7e185a046d} 65 | TinyFox.WebSocket 66 | 67 | 68 | 69 | 70 | Always 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /test/wwwroot/index.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | WebSocket Test 7 | 8 | 9 | 43 | 44 | 45 | 46 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 |


你输入什么,服务器就回复什么,试试!!
59 |
60 |
61 |

62 |
63 |
64 |
65 |
66 | 67 |
68 | 69 | 70 | 71 | --------------------------------------------------------------------------------