├── .github └── workflows │ ├── build.yml │ └── myget_release.yml ├── .gitignore ├── .vscode ├── launch.json ├── settings.json └── tasks.json ├── Dependencies.props ├── Directory.Build.props ├── LICENSE ├── README.md ├── WebSocket4Net.sln ├── assets └── supersocket.pfx ├── src └── WebSocket4Net │ ├── AutoPingOptions.cs │ ├── HandshakePipelineFilter.cs │ ├── IWebSocket.cs │ ├── InternalsVisibleTo.cs │ ├── PingPongStatus.cs │ ├── WebSocket.cs │ ├── WebSocket4Net.csproj │ └── WebSocketState.cs ├── test └── WebSocket4Net.Tests │ ├── IHostConfigurator.cs │ ├── MainTest.cs │ ├── RegularHostConfigurator.cs │ ├── SecureHostConfigurator.cs │ ├── TestBase.cs │ ├── WebSocket4Net.Tests.csproj │ └── xunit.runner.json └── version.json /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | build: 13 | strategy: 14 | matrix: 15 | os: 16 | - ubuntu-latest 17 | - windows-latest 18 | - macos-latest 19 | runs-on: ${{matrix.os}} 20 | env: 21 | DOTNET_CLI_TELEMETRY_OPTOUT: 1 22 | steps: 23 | - uses: actions/checkout@v1 24 | - name: Setup .NET Core 25 | uses: actions/setup-dotnet@v3 26 | with: 27 | dotnet-version: '9.0.x' 28 | - name: Build 29 | run: dotnet build -c Release 30 | - name: Test 31 | run: | 32 | cd test/WebSocket4Net.Tests 33 | dotnet test 34 | - uses: dotnet/nbgv@master 35 | id: nbgv 36 | if: runner.os == 'macOS' 37 | - name: Pack & push nuget packages to myget 38 | if: runner.os == 'macOS' 39 | run: | 40 | dotnet clean 41 | dotnet workload install android ios maccatalyst tvos macos maui wasm-tools --source https://aka.ms/dotnet8/nuget/index.json --source https://api.nuget.org/v3/index.json 42 | dotnet pack -c Release -p:IncludeMobileTargetFramework=true -p:PackageVersion=${{ steps.nbgv.outputs.NuGetPackageVersion }}.${{ github.run_number }} -p:Version=${{ steps.nbgv.outputs.NuGetPackageVersion }}.${{ github.run_number }} -p:AssemblyVersion=${{ steps.nbgv.outputs.AssemblyVersion }} -p:AssemblyFileVersion=${{ steps.nbgv.outputs.AssemblyFileVersion }} -p:AssemblyInformationalVersion=${{ steps.nbgv.outputs.AssemblyInformationalVersion }} /p:NoPackageAnalysis=true 43 | dotnet nuget push **/*.nupkg --api-key ${{ secrets.MYGET_API_KEY }} --source https://www.myget.org/F/websocket4net/api/v3/index.json -------------------------------------------------------------------------------- /.github/workflows/myget_release.yml: -------------------------------------------------------------------------------- 1 | name: myget-release 2 | on: [workflow_dispatch] 3 | jobs: 4 | push: 5 | runs-on: macos-latest 6 | steps: 7 | - uses: actions/checkout@v1 8 | - name: Install required workloads 9 | run: | 10 | dotnet workload install android ios maccatalyst tvos macos maui wasm-tools --source https://aka.ms/dotnet8/nuget/index.json --source https://api.nuget.org/v3/index.json 11 | - name: Setup .NET Core 12 | uses: actions/setup-dotnet@v3 13 | with: 14 | dotnet-version: '9.0.x' 15 | - name: Set env 16 | run: echo "DOTNET_CLI_TELEMETRY_OPTOUT=1" >> $GITHUB_ENV 17 | - uses: dotnet/nbgv@master 18 | id: nbgv 19 | - name: Pack 20 | run: dotnet pack -c Release -p:IncludeMobileTargetFramework=true -p:PackageVersion=${{ steps.nbgv.outputs.NuGetPackageVersion }} -p:Version=${{ steps.nbgv.outputs.NuGetPackageVersion }}.${{ github.run_number }} -p:AssemblyVersion=${{ steps.nbgv.outputs.AssemblyVersion }} -p:AssemblyFileVersion=${{ steps.nbgv.outputs.AssemblyFileVersion }} -p:AssemblyInformationalVersion=${{ steps.nbgv.outputs.AssemblyInformationalVersion }} /p:NoPackageAnalysis=true 21 | - name: Push 22 | run: dotnet nuget push **/*.nupkg --api-key ${{ secrets.MYGET_API_KEY }} --source https://www.myget.org/F/websocket4net/api/v3/index.json 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | obj 3 | publish 4 | _ReSharper.* 5 | *.suo 6 | *.user 7 | *.lock.json 8 | *.log 9 | .vs 10 | .DS_Store 11 | *.nupkg 12 | *.snupkg -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to find out which attributes exist for C# debugging 3 | // Use hover for the description of the existing attributes 4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/test/WebSocket4Net.Tests/bin/Debug/netcoreapp3.1/WebSocket4Net.Tests.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}/test/WebSocket4Net.Tests", 16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console 17 | "console": "internalConsole", 18 | "stopAtEntry": false 19 | }, 20 | { 21 | "name": ".NET Core Attach", 22 | "type": "coreclr", 23 | "request": "attach", 24 | "processId": "${command:pickProcess}" 25 | } 26 | ] 27 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/test/WebSocket4Net.Tests/WebSocket4Net.Tests.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/test/WebSocket4Net.Tests/WebSocket4Net.Tests.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/test/WebSocket4Net.Tests/WebSocket4Net.Tests.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /Dependencies.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 2.0.0 4 | 5 | -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10.0 5 | 6 | 7 | net6.0;net7.0;net8.0;net9.0 8 | net7.0-ios;net7.0-android;net7.0-macos;net7.0-tvos;net8.0-ios;net8.0-android;net8.0-macos;net8.0-tvos;net9.0-ios;net9.0-android;net9.0-macos;net9.0-tvos 9 | 10 | 11 | https://github.com/kerryjiang/WebSocket4Net 12 | https://github.com/kerryjiang/WebSocket4Net.git 13 | Apache-2.0 14 | true 15 | snupkg 16 | true 17 | Kerry Jiang and other contributors 18 | Kerry Jiang 19 | A popular .NET websocket client. 20 | README.md 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WebSocket4Net 2 | 3 | [![build](https://github.com/kerryjiang/WebSocket4Net/workflows/build/badge.svg)](https://travis-ci.org/kerryjiang/WebSocket4Net) 4 | [![MyGet Version](https://img.shields.io/myget/websocket4net/vpre/WebSocket4Net)](https://www.myget.org/feed/websocket4net/package/nuget/WebSocket4Net) 5 | [![NuGet Beta Version](https://img.shields.io/nuget/vpre/WebSocket4Net.svg?style=flat)](https://www.nuget.org/packages/WebSocket4Net/) 6 | [![NuGet Version](https://img.shields.io/nuget/v/WebSocket4Net.svg?style=flat)](https://www.nuget.org/packages/WebSocket4Net/) 7 | [![NuGet](https://img.shields.io/nuget/dt/WebSocket4Net.svg)](https://www.nuget.org/packages/WebSocket4Net) 8 | [![Badge](https://img.shields.io/badge/link-996.icu-red.svg)](https://996.icu/#/en_US) 9 | 10 | 11 | A popular .NET WebSocket Client 12 | 13 | This new version is built on SuperSocket 2.0 and modern .NET (.NET Core). It includes breaking changes from the previous WebSocket4Net version, so code adjustments may be necessary for upgrading. 14 | 15 | ## Usage 1: Read messages from event handler. 16 | 17 | ```csharp 18 | 19 | using WebSocket4Net; 20 | 21 | var websocket = new WebSocket("https://localhost/live"); 22 | 23 | websocket.PackageHandler += (sender, package) => 24 | { 25 | Console.WriteLine(package.Message); 26 | } 27 | 28 | await websocket.OpenAsync(); 29 | 30 | websocket.StartReceive(); 31 | 32 | await websocket.SendAsync("Hello"); 33 | 34 | //... 35 | 36 | await websocket.CloseAsync(); 37 | 38 | ``` 39 | 40 | ## Usage 1: Read messages on demand. 41 | 42 | ```csharp 43 | 44 | using WebSocket4Net; 45 | 46 | var websocket = new WebSocket("https://localhost/live"); 47 | 48 | await websocket.OpenAsync(); 49 | 50 | await websocket.SendAsync("Hello"); 51 | 52 | while (true) 53 | { 54 | var package = await websocket.ReceiveAsync(); 55 | 56 | if (package == null) 57 | break; 58 | 59 | Console.WriteLine(package.Message); 60 | } 61 | 62 | //... 63 | 64 | await websocket.CloseAsync(); 65 | 66 | ``` -------------------------------------------------------------------------------- /WebSocket4Net.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26124.0 5 | MinimumVisualStudioVersion = 15.0.26124.0 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{FA8E0D3F-5235-45FE-B7FA-7E71E1FD2C3D}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebSocket4Net", "src\WebSocket4Net\WebSocket4Net.csproj", "{5090F80A-B7A2-44FB-9E18-A2E6021C3934}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{CD84063F-769C-4DEC-B9FE-E479856FFAA2}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebSocket4Net.Tests", "test\WebSocket4Net.Tests\WebSocket4Net.Tests.csproj", "{97B06DB6-764A-4F48-AD7C-466E911D2F29}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Debug|x64 = Debug|x64 18 | Debug|x86 = Debug|x86 19 | Release|Any CPU = Release|Any CPU 20 | Release|x64 = Release|x64 21 | Release|x86 = Release|x86 22 | EndGlobalSection 23 | GlobalSection(SolutionProperties) = preSolution 24 | HideSolutionNode = FALSE 25 | EndGlobalSection 26 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 27 | {5090F80A-B7A2-44FB-9E18-A2E6021C3934}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {5090F80A-B7A2-44FB-9E18-A2E6021C3934}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {5090F80A-B7A2-44FB-9E18-A2E6021C3934}.Debug|x64.ActiveCfg = Debug|Any CPU 30 | {5090F80A-B7A2-44FB-9E18-A2E6021C3934}.Debug|x64.Build.0 = Debug|Any CPU 31 | {5090F80A-B7A2-44FB-9E18-A2E6021C3934}.Debug|x86.ActiveCfg = Debug|Any CPU 32 | {5090F80A-B7A2-44FB-9E18-A2E6021C3934}.Debug|x86.Build.0 = Debug|Any CPU 33 | {5090F80A-B7A2-44FB-9E18-A2E6021C3934}.Release|Any CPU.ActiveCfg = Release|Any CPU 34 | {5090F80A-B7A2-44FB-9E18-A2E6021C3934}.Release|Any CPU.Build.0 = Release|Any CPU 35 | {5090F80A-B7A2-44FB-9E18-A2E6021C3934}.Release|x64.ActiveCfg = Release|Any CPU 36 | {5090F80A-B7A2-44FB-9E18-A2E6021C3934}.Release|x64.Build.0 = Release|Any CPU 37 | {5090F80A-B7A2-44FB-9E18-A2E6021C3934}.Release|x86.ActiveCfg = Release|Any CPU 38 | {5090F80A-B7A2-44FB-9E18-A2E6021C3934}.Release|x86.Build.0 = Release|Any CPU 39 | {97B06DB6-764A-4F48-AD7C-466E911D2F29}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 40 | {97B06DB6-764A-4F48-AD7C-466E911D2F29}.Debug|Any CPU.Build.0 = Debug|Any CPU 41 | {97B06DB6-764A-4F48-AD7C-466E911D2F29}.Debug|x64.ActiveCfg = Debug|Any CPU 42 | {97B06DB6-764A-4F48-AD7C-466E911D2F29}.Debug|x64.Build.0 = Debug|Any CPU 43 | {97B06DB6-764A-4F48-AD7C-466E911D2F29}.Debug|x86.ActiveCfg = Debug|Any CPU 44 | {97B06DB6-764A-4F48-AD7C-466E911D2F29}.Debug|x86.Build.0 = Debug|Any CPU 45 | {97B06DB6-764A-4F48-AD7C-466E911D2F29}.Release|Any CPU.ActiveCfg = Release|Any CPU 46 | {97B06DB6-764A-4F48-AD7C-466E911D2F29}.Release|Any CPU.Build.0 = Release|Any CPU 47 | {97B06DB6-764A-4F48-AD7C-466E911D2F29}.Release|x64.ActiveCfg = Release|Any CPU 48 | {97B06DB6-764A-4F48-AD7C-466E911D2F29}.Release|x64.Build.0 = Release|Any CPU 49 | {97B06DB6-764A-4F48-AD7C-466E911D2F29}.Release|x86.ActiveCfg = Release|Any CPU 50 | {97B06DB6-764A-4F48-AD7C-466E911D2F29}.Release|x86.Build.0 = Release|Any CPU 51 | EndGlobalSection 52 | GlobalSection(NestedProjects) = preSolution 53 | {5090F80A-B7A2-44FB-9E18-A2E6021C3934} = {FA8E0D3F-5235-45FE-B7FA-7E71E1FD2C3D} 54 | {97B06DB6-764A-4F48-AD7C-466E911D2F29} = {CD84063F-769C-4DEC-B9FE-E479856FFAA2} 55 | EndGlobalSection 56 | EndGlobal 57 | -------------------------------------------------------------------------------- /assets/supersocket.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kerryjiang/WebSocket4Net/56ca74085516f1c1d402fe1b990bea5568045b9e/assets/supersocket.pfx -------------------------------------------------------------------------------- /src/WebSocket4Net/AutoPingOptions.cs: -------------------------------------------------------------------------------- 1 | namespace WebSocket4Net 2 | { 3 | public class AutoPingOptions 4 | { 5 | /// 6 | /// The interval the client send ping to server 7 | /// 8 | /// in seconds 9 | public int AutoPingInterval { get; set; } 10 | 11 | /// 12 | /// How long we expect receive pong after ping is sent 13 | /// 14 | /// in seconds 15 | public int ExpectedPongDelay { get; set; } 16 | 17 | public AutoPingOptions(int interval, int expectPongDelay) 18 | { 19 | AutoPingInterval = interval; 20 | ExpectedPongDelay = expectPongDelay; 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /src/WebSocket4Net/HandshakePipelineFilter.cs: -------------------------------------------------------------------------------- 1 | 2 | using System.Collections.Specialized; 3 | using SuperSocket.WebSocket; 4 | 5 | namespace WebSocket4Net 6 | { 7 | internal class HandshakePipelineFilter : WebSocketPipelineFilter 8 | { 9 | public HandshakePipelineFilter() 10 | : base(requireMask: false) 11 | { 12 | } 13 | 14 | protected override HttpHeader CreateHttpHeader(string verbItem1, string verbItem2, string verbItem3, NameValueCollection items) 15 | { 16 | return HttpHeader.CreateForResponse(verbItem1, verbItem2, verbItem3, items); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /src/WebSocket4Net/IWebSocket.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Buffers; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using SuperSocket.Client; 6 | using SuperSocket.WebSocket; 7 | 8 | namespace WebSocket4Net 9 | { 10 | public interface IWebSocket 11 | { 12 | ValueTask OpenAsync(CancellationToken cancellationToken = default); 13 | 14 | void StartReceive(); 15 | 16 | event PackageHandler PackageHandler; 17 | 18 | ValueTask ReceiveAsync(); 19 | 20 | ValueTask SendAsync(string message); 21 | 22 | ValueTask SendAsync(ReadOnlyMemory data); 23 | 24 | ValueTask SendAsync(ref ReadOnlySequence sequence); 25 | 26 | ValueTask CloseAsync(CloseReason closeReason, string message = null); 27 | 28 | event EventHandler Closed; 29 | } 30 | } -------------------------------------------------------------------------------- /src/WebSocket4Net/InternalsVisibleTo.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | [assembly: InternalsVisibleTo("WebSocket4Net.Tests")] -------------------------------------------------------------------------------- /src/WebSocket4Net/PingPongStatus.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using SuperSocket.WebSocket; 5 | 6 | namespace WebSocket4Net 7 | { 8 | public class PingPongStatus 9 | { 10 | private TaskCompletionSource _pongReceivedTaskSource; 11 | 12 | public DateTimeOffset LastPingReceived { get; internal set; } 13 | 14 | public DateTimeOffset LastPongReceived { get; internal set; } 15 | 16 | internal PingPongStatus() 17 | { 18 | } 19 | 20 | internal async Task RunAutoPing(WebSocket webSocket, AutoPingOptions options) 21 | { 22 | while (webSocket.State == WebSocketState.Open) 23 | { 24 | var autoPingInterval = Math.Max(options.AutoPingInterval, 60) * 1000; 25 | 26 | await Task.Delay(autoPingInterval); 27 | 28 | _pongReceivedTaskSource = new TaskCompletionSource(); 29 | 30 | await webSocket.SendAsync(new WebSocketPackage 31 | { 32 | OpCode = OpCode.Ping 33 | }); 34 | 35 | var pongExpectAfterPing = Math.Max(options.ExpectedPongDelay, autoPingInterval * 3); 36 | var task = await Task.WhenAny(_pongReceivedTaskSource.Task, Task.Delay(pongExpectAfterPing)); 37 | 38 | if (task is Task) 39 | { 40 | continue; 41 | } 42 | 43 | // Pong doesn't arrive on time 44 | await webSocket.CloseAsync(CloseReason.UnexpectedCondition, "Pong is not received on time."); 45 | break; 46 | } 47 | } 48 | 49 | internal void OnPongReceived(WebSocketPackage pong) 50 | { 51 | LastPongReceived = DateTimeOffset.Now; 52 | _pongReceivedTaskSource.SetResult(pong); 53 | } 54 | 55 | internal void OnPingReceived(WebSocketPackage ping) 56 | { 57 | LastPingReceived = DateTimeOffset.Now; 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /src/WebSocket4Net/WebSocket.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Buffers; 3 | using System.Buffers.Binary; 4 | using System.Collections.Generic; 5 | using System.IO.Pipelines; 6 | using System.Net; 7 | using System.Net.Sockets; 8 | using System.Security.Cryptography; 9 | using System.Text; 10 | using System.Threading; 11 | using System.Threading.Tasks; 12 | using Microsoft.Extensions.Logging; 13 | using Microsoft.Extensions.Logging.Abstractions; 14 | using SuperSocket.Connection; 15 | using SuperSocket.Client; 16 | using SuperSocket.ProtoBase; 17 | using SuperSocket.WebSocket; 18 | using CloseReason = SuperSocket.WebSocket.CloseReason; 19 | 20 | namespace WebSocket4Net 21 | { 22 | public class WebSocket : EasyClient, IWebSocket 23 | { 24 | private static readonly Encoding _asciiEncoding = Encoding.ASCII; 25 | private static readonly Encoding _utf8Encoding = new UTF8Encoding(false); 26 | private const string _magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; 27 | 28 | private TaskCompletionSource _closePackageReceivedTaskSource; 29 | 30 | private bool _packageHandlerMode = false; 31 | 32 | public Uri Uri { get; private set; } 33 | 34 | public bool AutoPingEnabled { get; set; } 35 | 36 | public CloseStatus CloseStatus { get; private set; } 37 | 38 | public PingPongStatus PingPongStatus { get; private set; } 39 | 40 | private readonly string _origin; 41 | 42 | private readonly EndPoint _remoteEndPoint; 43 | 44 | private static readonly IPackageEncoder _packageEncoder = new WebSocketMaskedEncoder(ArrayPool.Shared, new int[] 45 | { 46 | 1024, 47 | 1024 * 4, 48 | 1024 * 8, 49 | 1024 * 16, 50 | 1024 * 32, 51 | 1024 * 64 52 | }); 53 | 54 | private List _subProtocols; 55 | 56 | public IReadOnlyList SubProtocols => _subProtocols; 57 | 58 | private Dictionary _headers; 59 | 60 | public Dictionary Headers 61 | { 62 | get 63 | { 64 | return _headers ?? (_headers = new Dictionary(StringComparer.OrdinalIgnoreCase)); 65 | } 66 | } 67 | 68 | public WebSocketState State { get; private set; } = WebSocketState.None; 69 | 70 | static ConnectionOptions PrepareConnectionOptions(ConnectionOptions connectionOptions, ILogger logger) 71 | { 72 | connectionOptions ??= new ConnectionOptions(); 73 | connectionOptions.Logger = logger ?? NullLogger.Instance; 74 | return connectionOptions; 75 | } 76 | 77 | public WebSocket(string url, string origin = null, ILogger logger = null, ConnectionOptions connectionOptions = null) 78 | : base(new HandshakePipelineFilter(), PrepareConnectionOptions(connectionOptions, logger)) 79 | { 80 | Uri = new Uri(url); 81 | _origin = origin; 82 | 83 | if ("ws".Equals(Uri.Scheme, StringComparison.OrdinalIgnoreCase)) 84 | { 85 | _remoteEndPoint = ResolveUri(Uri, 80); 86 | } 87 | else if ("wss".Equals(Uri.Scheme, StringComparison.OrdinalIgnoreCase)) 88 | { 89 | _remoteEndPoint = ResolveUri(Uri, 443); 90 | } 91 | else 92 | { 93 | throw new ArgumentException("Unexpected url schema.", nameof(url)); 94 | } 95 | 96 | PingPongStatus = new PingPongStatus(); 97 | } 98 | 99 | private EndPoint ResolveUri(Uri uri, int defaultPort) 100 | { 101 | EndPoint remoteEndPoint; 102 | 103 | var port = uri.Port; 104 | 105 | if (port <= 0) 106 | port = defaultPort; 107 | 108 | if (IPAddress.TryParse(uri.Host, out IPAddress ipAddress)) 109 | remoteEndPoint = new IPEndPoint(ipAddress, port); 110 | else 111 | remoteEndPoint = new DnsEndPoint(uri.Host, port); 112 | 113 | return remoteEndPoint; 114 | } 115 | 116 | public void AddSubProtocol(string protocol) 117 | { 118 | var subProtocols = _subProtocols; 119 | 120 | subProtocols ??= _subProtocols = new List(); 121 | subProtocols.Add(protocol); 122 | } 123 | 124 | protected override void SetupConnection(IConnection connection) 125 | { 126 | Closed += OnConnectionClosed; 127 | base.SetupConnection(connection); 128 | } 129 | 130 | public async ValueTask OpenAsync(CancellationToken cancellationToken = default) 131 | { 132 | State = WebSocketState.Connecting; 133 | 134 | if (!await ConnectAsync(_remoteEndPoint, cancellationToken)) 135 | { 136 | State = WebSocketState.Closed; 137 | return false; 138 | } 139 | 140 | var (key, acceptKey) = MakeSecureKey(); 141 | await Connection.SendAsync((writer) => WriteHandshakeRequest(writer, key)); 142 | 143 | var handshakeResponse = await ReceiveAsync(); 144 | 145 | if (handshakeResponse == null) 146 | { 147 | State = WebSocketState.Closed; 148 | return false; 149 | } 150 | 151 | var responseHeader = handshakeResponse.HttpHeader; 152 | 153 | // 101 switch 154 | if (responseHeader.StatusCode != "101") 155 | { 156 | OnError($"Unexpected response: {responseHeader.StatusCode} - {responseHeader.StatusDescription}"); 157 | await base.CloseAsync(); // close the socket 158 | State = WebSocketState.Closed; 159 | return false; 160 | } 161 | 162 | var acceptKeyResponse = responseHeader.Items["Sec-WebSocket-Accept"]; 163 | 164 | if (string.IsNullOrEmpty(acceptKeyResponse) || !acceptKeyResponse.Equals(acceptKey)) 165 | { 166 | OnError($"The value of Sec-WebSocket-Accept is incorrect."); 167 | await base.CloseAsync(); // close the socket 168 | State = WebSocketState.Closed; 169 | return false; 170 | } 171 | 172 | State = WebSocketState.Open; 173 | 174 | if (AutoPingEnabled) 175 | { 176 | var autoPingTask = PingPongStatus.RunAutoPing(this, new AutoPingOptions(60 * 5, 5)); 177 | _ = autoPingTask.ContinueWith(t => OnError("AutoPing failed", t.Exception), TaskContinuationOptions.OnlyOnFaulted); 178 | } 179 | 180 | return true; 181 | } 182 | 183 | private string CalculateChallenge(string secKey, string magic) 184 | => Convert.ToBase64String(SHA1.Create().ComputeHash(_asciiEncoding.GetBytes(secKey + magic))); 185 | 186 | private (string, string) MakeSecureKey() 187 | { 188 | var secKey = Convert.ToBase64String(_asciiEncoding.GetBytes(Guid.NewGuid().ToString()[..16])); 189 | return (secKey, CalculateChallenge(secKey, _magic)); 190 | } 191 | 192 | private void WriteHandshakeRequest(PipeWriter writer, string secKey) 193 | { 194 | writer.Write($"GET {Uri.PathAndQuery} HTTP/1.1\r\n", _asciiEncoding); 195 | writer.Write($"{WebSocketConstant.Host}: {Uri.Host}\r\n", _asciiEncoding); 196 | writer.Write($"{WebSocketConstant.ResponseUpgradeLine}", _asciiEncoding); 197 | writer.Write($"{WebSocketConstant.ResponseConnectionLine}", _asciiEncoding); 198 | writer.Write($"{WebSocketConstant.SecWebSocketKey}: {secKey}\r\n", _asciiEncoding); 199 | 200 | if (!string.IsNullOrEmpty(_origin)) 201 | { 202 | writer.Write($"{WebSocketConstant.Origin}: {_origin}\r\n", _asciiEncoding); 203 | } 204 | 205 | var subProtocols = _subProtocols; 206 | 207 | if (subProtocols != null && subProtocols.Count > 0) 208 | { 209 | var strSubProtocols = string.Join(", ", subProtocols); 210 | writer.Write($"{WebSocketConstant.SecWebSocketProtocol}: {strSubProtocols}\r\n", _asciiEncoding); 211 | } 212 | 213 | writer.Write($"{WebSocketConstant.SecWebSocketVersion}: 13\r\n", _asciiEncoding); 214 | 215 | if (_headers != null) 216 | { 217 | // Write extra headers 218 | foreach (var header in _headers) 219 | writer.Write($"{header.Key}: {header.Value}\r\n", _asciiEncoding); 220 | } 221 | 222 | // Ensure end of the handshake request handshake 223 | writer.Write("\r\n", _asciiEncoding); 224 | } 225 | 226 | public void StartReceive() 227 | { 228 | if (State != WebSocketState.Open) 229 | { 230 | throw new InvalidOperationException($"You cannot call the method {nameof(StartReceive)} when the websocket connection is not open."); 231 | } 232 | 233 | _packageHandlerMode = true; 234 | 235 | StartReceiveAsync().ContinueWith(t => 236 | { 237 | if (t.IsFaulted) 238 | { 239 | OnError("Receive error", t.Exception); 240 | } 241 | }, TaskContinuationOptions.OnlyOnFaulted); 242 | } 243 | 244 | public new async ValueTask ReceiveAsync() 245 | => await ReceiveAsync( 246 | handleControlPackage: true, 247 | returnControlPackage: false); 248 | 249 | internal async ValueTask ReceiveAsync(bool handleControlPackage, bool returnControlPackage) 250 | { 251 | if (_packageHandlerMode) 252 | { 253 | throw new InvalidOperationException($"You cannot call the method {nameof(ReceiveAsync)} if you already setup the client to process packages by PackageHandler."); 254 | } 255 | 256 | var package = await base.ReceiveAsync(); 257 | 258 | if (package == null) 259 | return null; 260 | 261 | if (package.OpCode != OpCode.Binary && package.OpCode != OpCode.Text && package.OpCode != OpCode.Handshake) 262 | { 263 | if (handleControlPackage) 264 | { 265 | await HandleControlPackage(package); 266 | } 267 | 268 | if (!returnControlPackage) 269 | { 270 | return await ReceiveAsync(handleControlPackage, returnControlPackage); 271 | } 272 | } 273 | 274 | return package; 275 | } 276 | 277 | protected override async ValueTask OnPackageReceived(WebSocketPackage package) 278 | { 279 | if (package.OpCode != OpCode.Binary && package.OpCode != OpCode.Text) 280 | { 281 | if (package.OpCode == OpCode.Close && _closePackageReceivedTaskSource is TaskCompletionSource closePackageReceivedTaskSource) 282 | { 283 | if (Interlocked.CompareExchange(ref _closePackageReceivedTaskSource, null, closePackageReceivedTaskSource) == closePackageReceivedTaskSource) 284 | { 285 | closePackageReceivedTaskSource.SetResult(package); 286 | return; 287 | } 288 | } 289 | 290 | await HandleControlPackage(package); 291 | return; 292 | } 293 | 294 | await base.OnPackageReceived(package); 295 | } 296 | 297 | private async ValueTask HandleControlPackage(WebSocketPackage package) 298 | { 299 | switch (package.OpCode) 300 | { 301 | case OpCode.Close: 302 | await HandleCloseHandshake(package); 303 | break; 304 | 305 | case OpCode.Ping: 306 | PingPongStatus.OnPingReceived(package); 307 | package.OpCode = OpCode.Pong; 308 | await SendAsync(package); 309 | break; 310 | 311 | case OpCode.Pong: 312 | PingPongStatus.OnPongReceived(package); 313 | break; 314 | } 315 | } 316 | 317 | public async ValueTask SendAsync(string message) 318 | { 319 | var package = new WebSocketPackage 320 | { 321 | OpCode = OpCode.Text, 322 | Message = message 323 | }; 324 | await SendAsync(package); 325 | } 326 | 327 | internal async ValueTask SendAsync(WebSocketPackage package) 328 | => await SendAsync(_packageEncoder, package); 329 | 330 | public new async ValueTask SendAsync(ReadOnlyMemory data) 331 | { 332 | var package = new WebSocketPackage 333 | { 334 | OpCode = OpCode.Binary 335 | }; 336 | 337 | var sequenceElement = new SequenceSegment(data); 338 | package.Data = new ReadOnlySequence(sequenceElement, 0, sequenceElement, sequenceElement.Memory.Length); 339 | 340 | await SendAsync(_packageEncoder, package); 341 | } 342 | 343 | public ValueTask SendAsync(ref ReadOnlySequence sequence) 344 | { 345 | var package = new WebSocketPackage 346 | { 347 | OpCode = OpCode.Binary, 348 | Data = sequence 349 | }; 350 | return SendAsync(_packageEncoder, package); 351 | } 352 | 353 | private byte[] GetBuffer(int size) => new byte[size]; 354 | 355 | public override async ValueTask CloseAsync() 356 | => await CloseAsync(CloseReason.NormalClosure, string.Empty); 357 | 358 | public async ValueTask CloseAsync(CloseReason closeReason, string message = null) 359 | { 360 | var package = new WebSocketPackage 361 | { 362 | OpCode = OpCode.Close 363 | }; 364 | 365 | var bufferSize = !string.IsNullOrEmpty(message) ? _utf8Encoding.GetMaxByteCount(message.Length) : 0; 366 | bufferSize += 2; 367 | 368 | var buffer = GetBuffer(bufferSize); 369 | var len = 2; 370 | 371 | BinaryPrimitives.WriteUInt16BigEndian(buffer, (ushort)package.OpCode); 372 | 373 | if (!string.IsNullOrEmpty(message)) 374 | { 375 | len += _utf8Encoding.GetBytes(message, 0, message.Length, buffer, 2); 376 | } 377 | 378 | package.Data = new ReadOnlySequence(buffer, 0, len); 379 | 380 | CloseStatus = new CloseStatus 381 | { 382 | Reason = closeReason, 383 | ReasonText = message 384 | }; 385 | 386 | var closePackageReceivedTaskSource = default(TaskCompletionSource); 387 | 388 | if (_packageHandlerMode) 389 | { 390 | closePackageReceivedTaskSource = _closePackageReceivedTaskSource = new (); 391 | } 392 | 393 | await SendAsync(_packageEncoder, package); 394 | 395 | State = WebSocketState.CloseSent; 396 | 397 | var closeHandshakeResponse = closePackageReceivedTaskSource != null 398 | ? await closePackageReceivedTaskSource.Task 399 | : await ReceiveAsync(handleControlPackage: false, returnControlPackage: true); 400 | 401 | if (closeHandshakeResponse.OpCode != OpCode.Close) 402 | { 403 | OnError($"Unexpected close package, OpCode: {closeHandshakeResponse.OpCode}"); 404 | } 405 | else 406 | { 407 | await HandleCloseHandshake(closeHandshakeResponse); 408 | } 409 | 410 | await base.CloseAsync(); 411 | 412 | State = WebSocketState.Closed; 413 | } 414 | 415 | private CloseStatus DecodeCloseStatus(WebSocketPackage closePackage) 416 | { 417 | var reader = new SequenceReader(closePackage.Data); 418 | reader.TryReadBigEndian(out ushort closeReason); 419 | var reasonText = reader.ReadString(_utf8Encoding); 420 | 421 | return new CloseStatus 422 | { 423 | Reason = (CloseReason)closeReason, 424 | ReasonText = reasonText 425 | }; 426 | } 427 | 428 | private async ValueTask HandleCloseHandshake(WebSocketPackage receivedClosePackage) 429 | { 430 | var closeStatusFromRemote = DecodeCloseStatus(receivedClosePackage); 431 | 432 | var closeStatus = CloseStatus; 433 | 434 | if (closeStatus == null) 435 | { 436 | State = WebSocketState.CloseReceived; 437 | closeStatusFromRemote.RemoteInitiated = true; 438 | CloseStatus = closeStatusFromRemote; 439 | // Send close pong message to server side. 440 | await SendAsync(receivedClosePackage); 441 | } 442 | else 443 | { 444 | if (closeStatus.Reason != closeStatusFromRemote.Reason) 445 | { 446 | OnError("Unmatched CloseReason"); 447 | return; 448 | } 449 | 450 | // Received the close pong message from server, 451 | // so we can close the connection safely now 452 | await base.CloseAsync(); 453 | } 454 | } 455 | 456 | private void OnConnectionClosed(object sender, EventArgs eventArgs) 457 | => State = WebSocketState.Closed; 458 | } 459 | } 460 | -------------------------------------------------------------------------------- /src/WebSocket4Net/WebSocket4Net.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | $(DotNetTargetFrameworks);$(MobileTargetFrameworks) 4 | 5 | 6 | $(DotNetTargetFrameworks) 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/WebSocket4Net/WebSocketState.cs: -------------------------------------------------------------------------------- 1 | namespace WebSocket4Net 2 | { 3 | public enum WebSocketState 4 | { 5 | None, 6 | Connecting, 7 | Open, 8 | CloseSent, 9 | CloseReceived, 10 | Closed 11 | } 12 | } -------------------------------------------------------------------------------- /test/WebSocket4Net.Tests/IHostConfigurator.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Net.Sockets; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | using SuperSocket.Server.Abstractions; 8 | 9 | namespace WebSocket4Net.Tests 10 | { 11 | public interface IHostConfigurator 12 | { 13 | void Configure(HostBuilderContext context, IServiceCollection services); 14 | 15 | string WebSocketSchema { get; } 16 | 17 | bool IsSecure { get; } 18 | 19 | ListenOptions Listener { get; } 20 | 21 | WebSocket ConfigureClient(WebSocket client); 22 | } 23 | } -------------------------------------------------------------------------------- /test/WebSocket4Net.Tests/MainTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Buffers; 3 | using System.Collections.Concurrent; 4 | using System.Collections.Generic; 5 | using System.Collections.Specialized; 6 | using System.Linq; 7 | using System.Net; 8 | using System.Text; 9 | using System.Threading; 10 | using System.Threading.Tasks; 11 | using SuperSocket; 12 | using SuperSocket.Server.Host; 13 | using SuperSocket.WebSocket; 14 | using SuperSocket.WebSocket.Server; 15 | using Xunit; 16 | using Xunit.Abstractions; 17 | using Microsoft.AspNetCore.Hosting; 18 | using Microsoft.AspNetCore.Builder; 19 | using Microsoft.Extensions.Logging; 20 | using Meziantou.Extensions.Logging.Xunit; 21 | 22 | namespace WebSocket4Net.Tests 23 | { 24 | public class MainTest : TestBase 25 | { 26 | private string _loopbackIP; 27 | public MainTest(ITestOutputHelper outputHelper) 28 | : base(outputHelper) 29 | { 30 | _loopbackIP = IPAddress.Loopback.ToString(); 31 | } 32 | 33 | 34 | [Theory] 35 | [InlineData(typeof(RegularHostConfigurator))] 36 | [InlineData(typeof(SecureHostConfigurator))] 37 | public async Task TestHandshake(Type hostConfiguratorType) 38 | { 39 | var hostConfigurator = CreateObject(hostConfiguratorType); 40 | 41 | var serverSessionPath = string.Empty; 42 | var connected = false; 43 | 44 | using (var server = CreateWebSocketSocketServerBuilder(builder => 45 | { 46 | builder.UseSessionHandler(async (s) => 47 | { 48 | serverSessionPath = (s as WebSocketSession).Path; 49 | connected = true; 50 | await Task.CompletedTask; 51 | }, 52 | async (s, e) => 53 | { 54 | connected = false; 55 | await Task.CompletedTask; 56 | }); 57 | 58 | return builder; 59 | }, hostConfigurator: hostConfigurator) 60 | .BuildAsServer()) 61 | { 62 | Assert.True(await server.StartAsync()); 63 | OutputHelper.WriteLine("Server started."); 64 | 65 | var path = "/app/talk"; 66 | var url = $"{hostConfigurator.WebSocketSchema}://{_loopbackIP}:{hostConfigurator.Listener.Port}" + path; 67 | 68 | var websocket = new WebSocket(url); 69 | 70 | hostConfigurator.ConfigureClient(websocket); 71 | 72 | Assert.Equal(WebSocketState.None, websocket.State); 73 | 74 | Assert.True(await websocket.OpenAsync(), "Failed to connect"); 75 | 76 | Assert.Equal(WebSocketState.Open, websocket.State); 77 | 78 | await Task.Delay(1 * 1000); 79 | // test path 80 | Assert.Equal(path, serverSessionPath); 81 | Assert.True(connected); 82 | 83 | await websocket.CloseAsync(); 84 | 85 | Assert.NotNull(websocket.CloseStatus); 86 | Assert.Equal(CloseReason.NormalClosure, websocket.CloseStatus.Reason); 87 | 88 | await Task.Delay(1 * 1000); 89 | 90 | Assert.Equal(WebSocketState.Closed, websocket.State); 91 | Assert.False(connected); 92 | 93 | await server.StopAsync(); 94 | } 95 | } 96 | 97 | [Theory] 98 | [InlineData(typeof(RegularHostConfigurator))] 99 | [InlineData(typeof(SecureHostConfigurator))] 100 | public async Task TestCustomHeaderItems(Type hostConfiguratorType) 101 | { 102 | var hostConfigurator = CreateObject(hostConfiguratorType); 103 | 104 | var serverSessionPath = string.Empty; 105 | var connected = false; 106 | 107 | var httpHeaderFromServer = default(NameValueCollection); 108 | 109 | var serverConnectedTaskSource = new TaskCompletionSource(); 110 | 111 | using (var server = CreateWebSocketSocketServerBuilder(builder => 112 | { 113 | builder.UseSessionHandler(async (s) => 114 | { 115 | httpHeaderFromServer = (s as WebSocketSession).HttpHeader.Items; 116 | connected = true; 117 | serverConnectedTaskSource.SetResult(); 118 | await Task.CompletedTask; 119 | }, 120 | async (s, e) => 121 | { 122 | connected = false; 123 | await Task.CompletedTask; 124 | }); 125 | 126 | return builder; 127 | }, hostConfigurator: hostConfigurator) 128 | .BuildAsServer()) 129 | { 130 | Assert.True(await server.StartAsync()); 131 | OutputHelper.WriteLine("Server started."); 132 | 133 | var url = $"{hostConfigurator.WebSocketSchema}://{_loopbackIP}:{hostConfigurator.Listener.Port}"; 134 | 135 | var websocket = new WebSocket(url); 136 | 137 | var userId = Guid.NewGuid().ToString(); 138 | 139 | websocket.Headers["UserId"] = userId; 140 | 141 | hostConfigurator.ConfigureClient(websocket); 142 | 143 | Assert.Equal(WebSocketState.None, websocket.State); 144 | 145 | Assert.True(await websocket.OpenAsync(), "Failed to connect"); 146 | 147 | Assert.Equal(WebSocketState.Open, websocket.State); 148 | 149 | await serverConnectedTaskSource.Task.WaitAsync(TimeSpan.FromSeconds(30)); 150 | 151 | Assert.True(connected); 152 | 153 | Assert.NotNull(httpHeaderFromServer); 154 | 155 | var userIdFromHttpHeader = httpHeaderFromServer.Get("UserId"); 156 | 157 | Assert.NotNull(userIdFromHttpHeader); 158 | Assert.Equal(userId, userIdFromHttpHeader); 159 | 160 | await websocket.CloseAsync(); 161 | 162 | Assert.NotNull(websocket.CloseStatus); 163 | Assert.Equal(CloseReason.NormalClosure, websocket.CloseStatus.Reason); 164 | 165 | await Task.Delay(1 * 1000); 166 | 167 | Assert.Equal(WebSocketState.Closed, websocket.State); 168 | Assert.False(connected); 169 | 170 | await server.StopAsync(); 171 | } 172 | } 173 | 174 | [Fact] 175 | public async Task TestWithAspNetCoreWebSocketServer() 176 | { 177 | // Create a test server with ASP.NET Core WebSocket support 178 | var builder = new WebHostBuilder() 179 | .ConfigureLogging(logging => 180 | { 181 | logging.AddProvider(new XUnitLoggerProvider(OutputHelper)); 182 | logging.SetMinimumLevel(LogLevel.Debug); 183 | }) 184 | .UseKestrel() 185 | .Configure(app => 186 | { 187 | app.UseWebSockets(); 188 | app.Use(async (context, next) => 189 | { 190 | if (context.Request.Path == "/ws") 191 | { 192 | if (context.WebSockets.IsWebSocketRequest) 193 | { 194 | using var webSocket = await context.WebSockets.AcceptWebSocketAsync(); 195 | var buffer = new byte[1024 * 4]; 196 | 197 | while (webSocket.State == System.Net.WebSockets.WebSocketState.Open) 198 | { 199 | var result = await webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); 200 | 201 | if (result.MessageType == System.Net.WebSockets.WebSocketMessageType.Text) 202 | { 203 | // Echo the message back 204 | await webSocket.SendAsync( 205 | new ArraySegment(buffer, 0, result.Count), 206 | System.Net.WebSockets.WebSocketMessageType.Text, 207 | result.EndOfMessage, 208 | CancellationToken.None); 209 | } 210 | else if (result.MessageType == System.Net.WebSockets.WebSocketMessageType.Close) 211 | { 212 | await webSocket.CloseAsync( 213 | System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, 214 | "Closing", 215 | CancellationToken.None); 216 | break; 217 | } 218 | } 219 | } 220 | else 221 | { 222 | context.Response.StatusCode = 400; 223 | } 224 | } 225 | else 226 | { 227 | await next(); 228 | } 229 | }); 230 | }); 231 | 232 | using var host = builder.Build(); 233 | 234 | try 235 | { 236 | await host.StartAsync(); 237 | 238 | // Get the server URL 239 | var serverUrl = $"ws://localhost:5000/ws"; 240 | 241 | // Create WebSocket client 242 | var websocket = new WebSocket(serverUrl); 243 | 244 | // Connect to the server 245 | Assert.True(await websocket.OpenAsync(), "Failed to connect to ASP.NET Core WebSocket server"); 246 | Assert.Equal(WebSocketState.Open, websocket.State); 247 | 248 | // Test echo functionality 249 | for (var i = 0; i < 10; i++) 250 | { 251 | var text = Guid.NewGuid().ToString(); 252 | await websocket.SendAsync(text); 253 | var receivedText = (await websocket.ReceiveAsync()).Message; 254 | Assert.Equal(text, receivedText); 255 | } 256 | 257 | await websocket.CloseAsync(); 258 | 259 | Assert.NotNull(websocket.CloseStatus); 260 | Assert.Equal(CloseReason.NormalClosure, websocket.CloseStatus.Reason); 261 | Assert.Equal(WebSocketState.Closed, websocket.State); 262 | } 263 | finally 264 | { 265 | // Clean up 266 | await host.StopAsync(); 267 | } 268 | } 269 | 270 | 271 | [Theory] 272 | [InlineData(typeof(RegularHostConfigurator), 10)] 273 | [InlineData(typeof(SecureHostConfigurator), 10)] 274 | public async Task TestEchoMessage(Type hostConfiguratorType, int repeat) 275 | { 276 | var hostConfigurator = CreateObject(hostConfiguratorType); 277 | 278 | var serverSessionPath = string.Empty; 279 | var connected = false; 280 | 281 | var resetEvent = new AutoResetEvent(false); 282 | 283 | using (var server = CreateWebSocketSocketServerBuilder(builder => 284 | { 285 | builder.UseSessionHandler(async (s) => 286 | { 287 | connected = true; 288 | resetEvent.Set(); 289 | await Task.CompletedTask; 290 | }, 291 | async (s, e) => 292 | { 293 | connected = false; 294 | resetEvent.Set(); 295 | await Task.CompletedTask; 296 | }); 297 | 298 | builder.UseWebSocketMessageHandler(async (s, p) => 299 | { 300 | var session = s as WebSocketSession; 301 | await session.SendAsync(p.Message); 302 | }); 303 | 304 | return builder; 305 | }, hostConfigurator: hostConfigurator) 306 | .BuildAsServer()) 307 | { 308 | Assert.True(await server.StartAsync()); 309 | OutputHelper.WriteLine("Server started."); 310 | 311 | var websocket = new WebSocket($"{hostConfigurator.WebSocketSchema}://{_loopbackIP}:{hostConfigurator.Listener.Port}"); 312 | 313 | hostConfigurator.ConfigureClient(websocket); 314 | 315 | Assert.True(await websocket.OpenAsync(), "Failed to connect"); 316 | 317 | Assert.Equal(WebSocketState.Open, websocket.State); 318 | 319 | Assert.True(resetEvent.WaitOne(1000)); 320 | Assert.True(connected); 321 | 322 | for (var i = 0; i < repeat; i++) 323 | { 324 | var text = Guid.NewGuid().ToString(); 325 | await websocket.SendAsync(text); 326 | var receivedText = (await websocket.ReceiveAsync()).Message; 327 | Assert.Equal(text, receivedText); 328 | } 329 | 330 | await websocket.CloseAsync(); 331 | 332 | Assert.NotNull(websocket.CloseStatus); 333 | Assert.Equal(CloseReason.NormalClosure, websocket.CloseStatus.Reason); 334 | 335 | Assert.True(resetEvent.WaitOne(1000)); 336 | 337 | Assert.Equal(WebSocketState.Closed, websocket.State); 338 | Assert.False(connected); 339 | 340 | await server.StopAsync(); 341 | } 342 | } 343 | 344 | [Theory] 345 | [InlineData(typeof(RegularHostConfigurator), 10)] 346 | [InlineData(typeof(SecureHostConfigurator), 10)] 347 | public async Task TestEchoMessageByPackageHandler(Type hostConfiguratorType, int repeat) 348 | { 349 | var hostConfigurator = CreateObject(hostConfiguratorType); 350 | 351 | var serverSessionPath = string.Empty; 352 | var connected = false; 353 | 354 | var resetEvent = new AutoResetEvent(false); 355 | 356 | using (var server = CreateWebSocketSocketServerBuilder(builder => 357 | { 358 | builder.UseSessionHandler(async (s) => 359 | { 360 | connected = true; 361 | resetEvent.Set(); 362 | await Task.CompletedTask; 363 | }, 364 | async (s, e) => 365 | { 366 | connected = false; 367 | resetEvent.Set(); 368 | await Task.CompletedTask; 369 | }); 370 | 371 | builder.UseWebSocketMessageHandler(async (s, p) => 372 | { 373 | var session = s as WebSocketSession; 374 | await session.SendAsync(p.Message); 375 | }); 376 | 377 | return builder; 378 | }, hostConfigurator: hostConfigurator) 379 | .BuildAsServer()) 380 | { 381 | Assert.True(await server.StartAsync()); 382 | OutputHelper.WriteLine("Server started."); 383 | 384 | var websocket = new WebSocket($"{hostConfigurator.WebSocketSchema}://{_loopbackIP}:{hostConfigurator.Listener.Port}"); 385 | 386 | hostConfigurator.ConfigureClient(websocket); 387 | 388 | Assert.True(await websocket.OpenAsync(), "Failed to connect"); 389 | 390 | Assert.Equal(WebSocketState.Open, websocket.State); 391 | 392 | Assert.True(resetEvent.WaitOne(1000)); 393 | Assert.True(connected); 394 | 395 | var lastReceivedMessage = string.Empty; 396 | 397 | websocket.PackageHandler += (s, p) => 398 | { 399 | lastReceivedMessage = p.Message; 400 | resetEvent.Set(); 401 | return ValueTask.CompletedTask; 402 | }; 403 | 404 | websocket.StartReceive(); 405 | 406 | for (var i = 0; i < repeat; i++) 407 | { 408 | var text = Guid.NewGuid().ToString(); 409 | await websocket.SendAsync(text); 410 | Assert.True(resetEvent.WaitOne(1000)); 411 | Assert.Equal(text, lastReceivedMessage); 412 | } 413 | 414 | await websocket.CloseAsync(); 415 | 416 | Assert.NotNull(websocket.CloseStatus); 417 | Assert.Equal(CloseReason.NormalClosure, websocket.CloseStatus.Reason); 418 | 419 | Assert.True(resetEvent.WaitOne(1000)); 420 | 421 | Assert.Equal(WebSocketState.Closed, websocket.State); 422 | Assert.False(connected); 423 | 424 | await server.StopAsync(); 425 | } 426 | } 427 | 428 | 429 | [Theory] 430 | [InlineData(typeof(RegularHostConfigurator))] 431 | [InlineData(typeof(SecureHostConfigurator))] 432 | public async Task TestPingFromServer(Type hostConfiguratorType) 433 | { 434 | var hostConfigurator = CreateObject(hostConfiguratorType); 435 | 436 | WebSocketSession session = null; 437 | 438 | using (var server = CreateWebSocketSocketServerBuilder(builder => 439 | { 440 | builder.UseSessionHandler(async (s) => 441 | { 442 | session = s as WebSocketSession; 443 | await Task.CompletedTask; 444 | }); 445 | return builder; 446 | }, hostConfigurator: hostConfigurator) 447 | .BuildAsServer()) 448 | { 449 | Assert.True(await server.StartAsync()); 450 | OutputHelper.WriteLine("Server started."); 451 | 452 | var websocket = new WebSocket($"{hostConfigurator.WebSocketSchema}://{_loopbackIP}:{hostConfigurator.Listener.Port}"); 453 | 454 | hostConfigurator.ConfigureClient(websocket); 455 | 456 | Assert.True(await websocket.OpenAsync(), "Failed to connect"); 457 | 458 | var lastPingReceived = websocket.PingPongStatus.LastPingReceived; 459 | 460 | Assert.Equal(WebSocketState.Open, websocket.State); 461 | 462 | await Task.Delay(1 * 1000); 463 | 464 | Assert.NotNull(session); 465 | 466 | // send ping from server 467 | await session.SendAsync(new WebSocketPackage 468 | { 469 | OpCode = OpCode.Ping, 470 | Data = new ReadOnlySequence(Utf8Encoding.GetBytes("Hello")) 471 | }); 472 | 473 | var package = await websocket.ReceiveAsync( 474 | handleControlPackage: true, 475 | returnControlPackage: true); 476 | 477 | Assert.NotNull(package); 478 | 479 | var lastPingReceivedNow = websocket.PingPongStatus.LastPingReceived; 480 | 481 | Assert.NotEqual(lastPingReceived, lastPingReceivedNow); 482 | 483 | await websocket.CloseAsync(); 484 | 485 | await server.StopAsync(); 486 | } 487 | } 488 | 489 | [Theory] 490 | [InlineData(typeof(RegularHostConfigurator))] 491 | [InlineData(typeof(SecureHostConfigurator))] 492 | public async Task TestIncorrectDNS(Type hostConfiguratorType) 493 | { 494 | var hostConfigurator = CreateObject(hostConfiguratorType); 495 | 496 | using (var server = CreateWebSocketSocketServerBuilder(hostConfigurator: hostConfigurator) 497 | .BuildAsServer()) 498 | { 499 | Assert.True(await server.StartAsync()); 500 | OutputHelper.WriteLine("Server started."); 501 | 502 | var wrongHost = "localhost_x"; 503 | 504 | var websocket = new WebSocket($"{hostConfigurator.WebSocketSchema}://{wrongHost}:{hostConfigurator.Listener.Port}"); 505 | 506 | hostConfigurator.ConfigureClient(websocket); 507 | 508 | using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30)); 509 | 510 | Assert.False(await websocket.OpenAsync(cancellationTokenSource.Token), "Failed to connect"); 511 | Assert.Equal(WebSocketState.Closed, websocket.State); 512 | 513 | await server.StopAsync(); 514 | } 515 | } 516 | 517 | [Theory] 518 | [InlineData(typeof(RegularHostConfigurator))] 519 | [InlineData(typeof(SecureHostConfigurator))] 520 | public async Task TestReconnect(Type hostConfiguratorType) 521 | { 522 | var hostConfigurator = CreateObject(hostConfiguratorType); 523 | 524 | using (var server = CreateWebSocketSocketServerBuilder(hostConfigurator: hostConfigurator) 525 | .BuildAsServer()) 526 | { 527 | Assert.True(await server.StartAsync()); 528 | OutputHelper.WriteLine("Server started."); 529 | 530 | var websocket = new WebSocket($"{hostConfigurator.WebSocketSchema}://{_loopbackIP}:{hostConfigurator.Listener.Port}"); 531 | 532 | hostConfigurator.ConfigureClient(websocket); 533 | 534 | using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(60)); 535 | 536 | for (var i = 0; i < 100; i++) 537 | { 538 | Assert.True(await websocket.OpenAsync(cancellationTokenSource.Token), "Failed to connect"); 539 | Assert.Equal(WebSocketState.Open, websocket.State); 540 | 541 | await Task.WhenAny(websocket.CloseAsync(CloseReason.NormalClosure).AsTask(), Task.Delay(TimeSpan.FromSeconds(30))); 542 | Assert.Equal(WebSocketState.Closed, websocket.State); 543 | 544 | cancellationTokenSource.TryReset(); 545 | } 546 | 547 | await server.StopAsync(); 548 | } 549 | } 550 | 551 | [Theory] 552 | [InlineData(typeof(RegularHostConfigurator))] 553 | [InlineData(typeof(SecureHostConfigurator))] 554 | public async Task TestUnreachableReconnectA(Type hostConfiguratorType) 555 | { 556 | var hostConfigurator = CreateObject(hostConfiguratorType); 557 | 558 | using (var server = CreateWebSocketSocketServerBuilder(hostConfigurator: hostConfigurator) 559 | .BuildAsServer()) 560 | { 561 | var websocket = new WebSocket($"{hostConfigurator.WebSocketSchema}://{_loopbackIP}:{hostConfigurator.Listener.Port}"); 562 | 563 | hostConfigurator.ConfigureClient(websocket); 564 | 565 | Assert.True(await server.StartAsync()); 566 | 567 | using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(60)); 568 | 569 | Assert.True(await websocket.OpenAsync(cancellationTokenSource.Token), "Failed to connect"); 570 | Assert.Equal(WebSocketState.Open, websocket.State); 571 | await Task.WhenAny(websocket.CloseAsync(CloseReason.NormalClosure).AsTask(), Task.Delay(TimeSpan.FromSeconds(30))); 572 | Assert.Equal(WebSocketState.Closed, websocket.State); 573 | 574 | await server.StopAsync(); 575 | 576 | cancellationTokenSource.TryReset(); 577 | 578 | Assert.False(await websocket.OpenAsync(cancellationTokenSource.Token), "Failed to connect"); 579 | Assert.Equal(WebSocketState.Closed, websocket.State); 580 | 581 | Assert.True(await server.StartAsync()); 582 | 583 | cancellationTokenSource.TryReset(); 584 | 585 | Assert.True(await websocket.OpenAsync(cancellationTokenSource.Token), "Failed to connect"); 586 | Assert.Equal(WebSocketState.Open, websocket.State); 587 | await Task.WhenAny(websocket.CloseAsync(CloseReason.NormalClosure).AsTask(), Task.Delay(TimeSpan.FromSeconds(30))); 588 | Assert.Equal(WebSocketState.Closed, websocket.State); 589 | 590 | await server.StopAsync(); 591 | } 592 | } 593 | 594 | [Theory] 595 | [InlineData(typeof(RegularHostConfigurator))] 596 | [InlineData(typeof(SecureHostConfigurator))] 597 | public async Task TestUnreachableReconnectB(Type hostConfiguratorType) 598 | { 599 | var hostConfigurator = CreateObject(hostConfiguratorType); 600 | 601 | using (var server = CreateWebSocketSocketServerBuilder(hostConfigurator: hostConfigurator) 602 | .BuildAsServer()) 603 | { 604 | var websocket = new WebSocket($"{hostConfigurator.WebSocketSchema}://{_loopbackIP}:{hostConfigurator.Listener.Port}"); 605 | 606 | hostConfigurator.ConfigureClient(websocket); 607 | 608 | using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(60)); 609 | 610 | Assert.False(await websocket.OpenAsync(cancellationTokenSource.Token), "Failed to connect"); 611 | Assert.Equal(WebSocketState.Closed, websocket.State); 612 | 613 | Assert.True(await server.StartAsync()); 614 | 615 | cancellationTokenSource.TryReset(); 616 | 617 | Assert.True(await websocket.OpenAsync(cancellationTokenSource.Token), "Failed to connect"); 618 | Assert.Equal(WebSocketState.Open, websocket.State); 619 | await Task.WhenAny(websocket.CloseAsync(CloseReason.NormalClosure).AsTask(), Task.Delay(TimeSpan.FromSeconds(30))); 620 | Assert.Equal(WebSocketState.Closed, websocket.State); 621 | 622 | await server.StopAsync(); 623 | } 624 | } 625 | 626 | [Theory] 627 | [InlineData(typeof(RegularHostConfigurator))] 628 | [InlineData(typeof(SecureHostConfigurator))] 629 | public async Task TestCloseWebSocket(Type hostConfiguratorType) 630 | { 631 | var hostConfigurator = CreateObject(hostConfiguratorType); 632 | 633 | using (var server = CreateWebSocketSocketServerBuilder( 634 | configurator: builder => { 635 | builder.UseWebSocketMessageHandler(async (s, p) => 636 | { 637 | if (p.Message == "QUIT") 638 | { 639 | await s.CloseAsync(CloseReason.NormalClosure); 640 | } 641 | }); 642 | 643 | return builder; 644 | }, 645 | hostConfigurator: hostConfigurator) 646 | .BuildAsServer()) 647 | { 648 | var manualResetEvent = new ManualResetEvent(false); 649 | 650 | var websocket = new WebSocket($"{hostConfigurator.WebSocketSchema}://{_loopbackIP}:{hostConfigurator.Listener.Port}"); 651 | 652 | websocket.Closed += (s, e) => 653 | { 654 | manualResetEvent.Set(); 655 | }; 656 | 657 | hostConfigurator.ConfigureClient(websocket); 658 | 659 | Assert.True(await server.StartAsync()); 660 | 661 | using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(60)); 662 | 663 | Assert.True(await websocket.OpenAsync(cancellationTokenSource.Token), "Failed to connect"); 664 | Assert.Equal(WebSocketState.Open, websocket.State); 665 | 666 | await websocket.SendAsync("QUIT"); 667 | 668 | await Task.WhenAny(websocket.ReceiveAsync().AsTask(), Task.Delay(TimeSpan.FromSeconds(30))); 669 | 670 | Assert.True(manualResetEvent.WaitOne(TimeSpan.FromSeconds(5)), "The connection failed to close on time"); 671 | Assert.Equal(WebSocketState.Closed, websocket.State); 672 | 673 | await server.StopAsync(); 674 | } 675 | } 676 | 677 | [Theory] 678 | [InlineData(typeof(RegularHostConfigurator))] 679 | [InlineData(typeof(SecureHostConfigurator))] 680 | public async Task TestSendMessage(Type hostConfiguratorType) 681 | { 682 | var hostConfigurator = CreateObject(hostConfiguratorType); 683 | 684 | using (var server = CreateWebSocketSocketServerBuilder( 685 | configurator: builder => 686 | { 687 | builder.UseWebSocketMessageHandler(async (s, p) => 688 | { 689 | if (p.Message.StartsWith("ECHO", StringComparison.OrdinalIgnoreCase)) 690 | { 691 | await s.SendAsync(p.Message.Substring(5)); 692 | } 693 | }); 694 | 695 | return builder; 696 | }, 697 | hostConfigurator: hostConfigurator) 698 | .BuildAsServer()) 699 | { 700 | var websocket = new WebSocket($"{hostConfigurator.WebSocketSchema}://{_loopbackIP}:{hostConfigurator.Listener.Port}"); 701 | 702 | hostConfigurator.ConfigureClient(websocket); 703 | 704 | Assert.True(await server.StartAsync()); 705 | 706 | using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(60)); 707 | 708 | Assert.True(await websocket.OpenAsync(cancellationTokenSource.Token), "Failed to connect"); 709 | Assert.Equal(WebSocketState.Open, websocket.State); 710 | 711 | var sb = new StringBuilder(); 712 | 713 | for (int i = 0; i < 10; i++) 714 | { 715 | sb.Append(Guid.NewGuid().ToString()); 716 | } 717 | 718 | string messageSource = sb.ToString(); 719 | 720 | var rd = new Random(); 721 | 722 | for (int i = 0; i < 100; i++) 723 | { 724 | int startPos = rd.Next(0, messageSource.Length - 2); 725 | int endPos = rd.Next(startPos + 1, messageSource.Length - 1); 726 | 727 | string message = messageSource.Substring(startPos, endPos - startPos); 728 | 729 | await websocket.SendAsync("ECHO " + message); 730 | 731 | var receivedMessage = await websocket.ReceiveAsync(); 732 | 733 | Assert.NotNull(receivedMessage); 734 | Assert.Equal(message, receivedMessage.Message); 735 | } 736 | 737 | await server.StopAsync(); 738 | } 739 | } 740 | 741 | [Theory] 742 | [InlineData(typeof(RegularHostConfigurator))] 743 | [InlineData(typeof(SecureHostConfigurator))] 744 | public async Task TestSendData(Type hostConfiguratorType) 745 | { 746 | var hostConfigurator = CreateObject(hostConfiguratorType); 747 | 748 | using (var server = CreateWebSocketSocketServerBuilder( 749 | configurator: builder => 750 | { 751 | builder.UseWebSocketMessageHandler(async (s, p) => 752 | { 753 | await s.SendAsync(p.Data.ToArray()); 754 | }); 755 | 756 | return builder; 757 | }, 758 | hostConfigurator: hostConfigurator) 759 | .BuildAsServer()) 760 | { 761 | var websocket = new WebSocket($"{hostConfigurator.WebSocketSchema}://{_loopbackIP}:{hostConfigurator.Listener.Port}"); 762 | 763 | hostConfigurator.ConfigureClient(websocket); 764 | 765 | Assert.True(await server.StartAsync()); 766 | 767 | using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(60)); 768 | 769 | Assert.True(await websocket.OpenAsync(cancellationTokenSource.Token), "Failed to connect"); 770 | Assert.Equal(WebSocketState.Open, websocket.State); 771 | 772 | var sb = new StringBuilder(); 773 | 774 | for (int i = 0; i < 10; i++) 775 | { 776 | sb.Append(Guid.NewGuid().ToString()); 777 | } 778 | 779 | string messageSource = sb.ToString(); 780 | 781 | var rd = new Random(); 782 | 783 | for (int i = 0; i < 100; i++) 784 | { 785 | int startPos = rd.Next(0, messageSource.Length - 2); 786 | int endPos = rd.Next(startPos + 1, messageSource.Length - 1); 787 | 788 | string message = messageSource.Substring(startPos, endPos - startPos); 789 | 790 | await websocket.SendAsync(Encoding.UTF8.GetBytes(message)); 791 | 792 | var receivedMessage = await websocket.ReceiveAsync(); 793 | 794 | Assert.NotNull(receivedMessage); 795 | Assert.Equal(message, Encoding.UTF8.GetString(receivedMessage.Data)); 796 | } 797 | 798 | await server.StopAsync(); 799 | } 800 | } 801 | 802 | [Theory] 803 | [InlineData(typeof(RegularHostConfigurator))] 804 | [InlineData(typeof(SecureHostConfigurator))] 805 | public async Task TestConcurrentSend(Type hostConfiguratorType) 806 | { 807 | var lines = new string[100]; 808 | 809 | for (int i = 0; i < lines.Length; i++) 810 | { 811 | lines[i] = Guid.NewGuid().ToString(); 812 | } 813 | 814 | var messDict = new ConcurrentDictionary(lines.Select(line => new KeyValuePair(line, line))); 815 | 816 | var hostConfigurator = CreateObject(hostConfiguratorType); 817 | 818 | var allMessageReceivedEvent = new ManualResetEventSlim(false); 819 | 820 | using (var server = CreateWebSocketSocketServerBuilder( 821 | configurator: builder => 822 | { 823 | builder.UseWebSocketMessageHandler((s, p) => 824 | { 825 | if (messDict.Remove(p.Message, out _)) 826 | { 827 | if (messDict.Count == 0) 828 | { 829 | allMessageReceivedEvent.Set(); 830 | } 831 | } 832 | 833 | return ValueTask.CompletedTask; 834 | }); 835 | 836 | return builder; 837 | }, 838 | hostConfigurator: hostConfigurator) 839 | .BuildAsServer()) 840 | { 841 | var websocket = new WebSocket($"{hostConfigurator.WebSocketSchema}://{_loopbackIP}:{hostConfigurator.Listener.Port}"); 842 | 843 | hostConfigurator.ConfigureClient(websocket); 844 | 845 | Assert.True(await server.StartAsync()); 846 | 847 | using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(60)); 848 | 849 | Assert.True(await websocket.OpenAsync(cancellationTokenSource.Token), "Failed to connect"); 850 | Assert.Equal(WebSocketState.Open, websocket.State); 851 | 852 | await AsyncParallel.ForEach( 853 | lines, 854 | async line => 855 | { 856 | await websocket.SendAsync(line); 857 | }, 858 | lines.Length); 859 | 860 | Assert.True(allMessageReceivedEvent.Wait(TimeSpan.FromSeconds(10)), "The server side didn't receive all messages in time."); 861 | await server.StopAsync(); 862 | } 863 | } 864 | } 865 | } 866 | -------------------------------------------------------------------------------- /test/WebSocket4Net.Tests/RegularHostConfigurator.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using System.Net.Sockets; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Hosting; 8 | using SuperSocket.Server.Abstractions; 9 | 10 | namespace WebSocket4Net.Tests 11 | { 12 | public class RegularHostConfigurator : IHostConfigurator 13 | { 14 | public string WebSocketSchema => "ws"; 15 | 16 | public bool IsSecure => false; 17 | 18 | public ListenOptions Listener { get; private set; } 19 | 20 | public void Configure(HostBuilderContext context, IServiceCollection services) 21 | { 22 | services.Configure((options) => 23 | { 24 | var listener = options.Listeners[0]; 25 | Listener = listener; 26 | }); 27 | } 28 | 29 | public WebSocket ConfigureClient(WebSocket client) 30 | { 31 | return client; 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /test/WebSocket4Net.Tests/SecureHostConfigurator.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using System.Net.Security; 4 | using System.Net.Sockets; 5 | using System.Security.Authentication; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Hosting; 8 | using SuperSocket; 9 | using SuperSocket.Client; 10 | using SuperSocket.Server.Abstractions; 11 | 12 | namespace WebSocket4Net.Tests 13 | { 14 | public class SecureHostConfigurator : IHostConfigurator 15 | { 16 | public string WebSocketSchema => "wss"; 17 | 18 | public bool IsSecure => true; 19 | 20 | public ListenOptions Listener { get; private set; } 21 | 22 | public void Configure(HostBuilderContext context, IServiceCollection services) 23 | { 24 | services.Configure((options) => 25 | { 26 | var listener = options.Listeners[0]; 27 | 28 | var authenticationOptions = listener.AuthenticationOptions; 29 | 30 | if (authenticationOptions == null) 31 | { 32 | authenticationOptions = listener.AuthenticationOptions = new ServerAuthenticationOptions(); 33 | } 34 | 35 | authenticationOptions.CertificateOptions = new CertificateOptions 36 | { 37 | FilePath = "supersocket.pfx", 38 | Password = "supersocket" 39 | }; 40 | 41 | if (authenticationOptions.EnabledSslProtocols == SslProtocols.None) 42 | { 43 | authenticationOptions.EnabledSslProtocols = GetServerEnabledSslProtocols(); 44 | } 45 | 46 | Listener = listener; 47 | }); 48 | } 49 | 50 | protected virtual SslProtocols GetServerEnabledSslProtocols() 51 | { 52 | return SslProtocols.Tls13 | SslProtocols.Tls12; 53 | } 54 | 55 | protected virtual SslProtocols GetClientEnabledSslProtocols() 56 | { 57 | return SslProtocols.Tls13 | SslProtocols.Tls12; 58 | } 59 | 60 | public WebSocket ConfigureClient(WebSocket client) 61 | { 62 | client.Security = new SecurityOptions 63 | { 64 | TargetHost = "supersocket", 65 | EnabledSslProtocols = GetClientEnabledSslProtocols(), 66 | RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true 67 | }; 68 | 69 | return client; 70 | } 71 | } 72 | 73 | public class TLS13OnlySecureHostConfigurator : SecureHostConfigurator 74 | { 75 | protected override SslProtocols GetServerEnabledSslProtocols() 76 | { 77 | return SslProtocols.Tls13; 78 | } 79 | 80 | protected override SslProtocols GetClientEnabledSslProtocols() 81 | { 82 | return SslProtocols.Tls13; 83 | } 84 | } 85 | } -------------------------------------------------------------------------------- /test/WebSocket4Net.Tests/TestBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net; 4 | using System.Text; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | using SuperSocket.Server.Abstractions.Host; 10 | using SuperSocket.WebSocket; 11 | using SuperSocket.WebSocket.Server; 12 | using Xunit.Abstractions; 13 | 14 | namespace WebSocket4Net.Tests 15 | { 16 | public abstract class TestBase 17 | { 18 | protected readonly ITestOutputHelper OutputHelper; 19 | protected static readonly Encoding Utf8Encoding = new UTF8Encoding(false); 20 | protected readonly static int DefaultServerPort = 4040; 21 | 22 | protected IPEndPoint GetDefaultServerEndPoint() 23 | { 24 | return new IPEndPoint(IPAddress.Loopback, DefaultServerPort); 25 | } 26 | 27 | protected static ILoggerFactory DefaultLoggerFactory { get; } = LoggerFactory.Create(builder => 28 | { 29 | builder.AddConsole(); 30 | }); 31 | 32 | protected TestBase(ITestOutputHelper outputHelper) 33 | { 34 | OutputHelper = outputHelper; 35 | } 36 | 37 | protected virtual void ConfigureServices(HostBuilderContext context, IServiceCollection services) 38 | { 39 | 40 | } 41 | 42 | protected ISuperSocketHostBuilder CreateWebSocketSocketServerBuilder(Func, ISuperSocketHostBuilder> configurator = null, IHostConfigurator hostConfigurator = null) 43 | { 44 | var hostBuilder = WebSocketHostBuilder.Create() as ISuperSocketHostBuilder; 45 | 46 | if (configurator != null) 47 | hostBuilder = configurator(hostBuilder); 48 | 49 | return Configure(hostBuilder, hostConfigurator) as ISuperSocketHostBuilder; 50 | } 51 | 52 | protected T CreateObject(Type type) 53 | { 54 | return (T)Activator.CreateInstance(type); 55 | } 56 | 57 | protected IHostBuilder Configure(IHostBuilder hostBuilder, IHostConfigurator configurator = null) 58 | { 59 | var builder = hostBuilder.ConfigureAppConfiguration((hostCtx, configApp) => 60 | { 61 | configApp.AddInMemoryCollection(new Dictionary 62 | { 63 | { "serverOptions:name", "TestWebSocketServer" }, 64 | { "serverOptions:listeners:0:ip", "Any" }, 65 | { "serverOptions:listeners:0:backLog", "100" }, 66 | { "serverOptions:listeners:0:port", DefaultServerPort.ToString() } 67 | }); 68 | }) 69 | .ConfigureLogging((hostCtx, loggingBuilder) => 70 | { 71 | loggingBuilder.AddConsole(); 72 | loggingBuilder.AddDebug(); 73 | }) 74 | .ConfigureServices((hostCtx, services) => 75 | { 76 | ConfigureServices(hostCtx, services); 77 | }); 78 | 79 | if (configurator != null) 80 | { 81 | builder = builder.ConfigureServices((ctx, services) => 82 | { 83 | configurator.Configure(ctx, services); 84 | }); 85 | } 86 | 87 | return builder; 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /test/WebSocket4Net.Tests/WebSocket4Net.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | PreserveNewest 24 | 25 | 26 | PreserveNewest 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /test/WebSocket4Net.Tests/xunit.runner.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://xunit.github.io/schema/current/xunit.runner.schema.json", 3 | "parallelizeTestCollections": false 4 | } -------------------------------------------------------------------------------- /version.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json", 3 | "version": "1.0.0-beta.5", 4 | "publicReleaseRefSpec": [ 5 | "^refs/heads/master$", 6 | "^refs/heads/v\\d+(?:\\.\\d+)?$" 7 | ], 8 | "cloudBuild": { 9 | "buildNumber": { 10 | "enabled": true, 11 | "setVersionVariables": true 12 | } 13 | }, 14 | "nugetPackageVersion": { 15 | "semVer": 2 16 | } 17 | } --------------------------------------------------------------------------------