├── .appveyor.yml ├── .clang-format ├── .gitattributes ├── .github ├── dependabot.yml ├── stale.yml └── workflows │ ├── build.yml │ ├── codeql.yml │ └── docs.yml ├── .gitignore ├── .gitmodules ├── .lgtm.yml ├── .readthedocs.yml ├── 1k ├── 1kiss.ps1 ├── CPM.cmake ├── dm │ ├── CMakeLists.txt │ ├── dm.c │ └── dm.ps1 ├── extensions.ps1 ├── fetch.cmake ├── fetch.ps1 ├── fsync.ps1 ├── install-pwsh.sh ├── ios.cmake ├── manifest.ps1 ├── platforms.cmake └── resolv-url.ps1 ├── 3rdparty ├── .gitignore ├── README.md ├── c-ares │ └── CMakeLists.txt ├── half │ ├── README.md │ └── half.hpp ├── kaguya │ ├── README.md │ └── kaguya.hpp ├── moodycamel │ ├── README.md │ ├── atomicops.h │ └── readerwriterqueue.h ├── openssl │ └── CMakeLists.txt ├── sol │ ├── README.md │ ├── config.hpp │ ├── forward.hpp │ └── sol.hpp ├── sol2 │ ├── README.md │ ├── sol.hpp │ └── sol_forward.hpp └── websocket-parser │ ├── CMakeLists.txt │ ├── websocket_parser.c │ └── websocket_parser.h ├── BSL_1_0.txt ├── CHANGELOG.md ├── CMakeLists.txt ├── CMakePresets.json ├── LICENSE ├── README.md ├── README_EN.md ├── benchmark.md ├── build.ps1 ├── certs ├── ca-cer.crt ├── ca-cer.pem ├── ca-prk.pem ├── cacert.pem ├── gen.sh ├── server-cer.crt ├── server-cer.pem ├── server-csr.pem ├── server-prk.pem ├── sslcerts.hpp.in └── v3.ext ├── docs ├── api │ └── reference │ │ ├── endpoint-class.md │ │ ├── ibstream-class.md │ │ ├── io_channel-class.md │ │ ├── io_event-class.md │ │ ├── io_service-class.md │ │ ├── io_service-options.md │ │ ├── object_pool-class.md │ │ ├── obstream-class.md │ │ ├── others.md │ │ ├── singleton-class.md │ │ └── xxsocket-class.md ├── assets │ ├── images │ │ ├── framework.png │ │ ├── framework_en.png │ │ └── logo.png │ └── stylesheets │ │ └── extra.css ├── faq.md ├── index.md ├── interop.md ├── preprocessor.md ├── prerequisites.txt ├── requirements.txt └── unpacking.md ├── examples ├── js │ └── example.js └── lua │ ├── CMakeLists.txt │ ├── example_lua.xsxproj │ ├── main.cpp │ └── scripts │ ├── example.lua │ ├── http_client.lua │ ├── protocol_base.lua │ ├── protocol_dec.lua │ ├── protocol_enc.lua │ └── protocol_enums.lua ├── extensions └── yasio_http │ ├── .clang-format │ ├── CMakeLists.txt │ ├── HttpClient.cpp │ ├── HttpClient.h │ ├── HttpCookie.cpp │ ├── HttpCookie.h │ ├── HttpRequest.h │ ├── HttpResponse.h │ ├── Uri.cpp │ ├── Uri.h │ ├── utils │ └── concurrent_deque.h │ └── yasio_http.cpp ├── manifest.json ├── mkdocs.yml ├── tests ├── echo_client │ ├── CMakeLists.txt │ └── main.cpp ├── echo_server │ ├── CMakeLists.txt │ └── main.cpp ├── http │ ├── CMakeLists.txt │ └── main.cpp ├── icmp │ ├── CMakeLists.txt │ └── main.cpp ├── issue166 │ ├── CMakeLists.txt │ └── main.cpp ├── issue178 │ ├── CMakeLists.txt │ └── main.cpp ├── issue201 │ ├── CMakeLists.txt │ └── main.cpp ├── issue208 │ ├── CMakeLists.txt │ └── main.cpp ├── issue245 │ ├── CMakeLists.txt │ └── main.cpp ├── issue256 │ ├── CMakeLists.txt │ └── main.cpp ├── issue377 │ ├── CMakeLists.txt │ └── main.cpp ├── issue384 │ ├── CMakeLists.txt │ └── main.cpp ├── mcast │ ├── CMakeLists.txt │ └── main.cpp ├── mcast2 │ ├── CMakeLists.txt │ └── main.cpp ├── mtu │ ├── CMakeLists.txt │ └── main.cpp ├── speed │ ├── CMakeLists.txt │ └── main.cpp ├── ssl │ ├── CMakeLists.txt │ └── main.cpp └── tcp │ ├── CMakeLists.txt │ └── main.cpp ├── tools ├── ci.ps1 └── docs.ps1 ├── yasio.pc └── yasio ├── .clang-format ├── bindings ├── lua │ ├── CMakeLists.txt │ └── lua.hpp ├── luajit │ └── lua.hpp ├── lyasio.cpp ├── lyasio.hpp ├── yasio_axlua.cpp ├── yasio_axlua.hpp ├── yasio_jsb.cpp ├── yasio_jsb.hpp ├── yasio_jsb20.cpp ├── yasio_jsb20.hpp ├── yasio_ni.cpp └── yasio_sol.hpp ├── buffer_alloc.hpp ├── byte_buffer.hpp ├── compiler └── feature_test.hpp ├── config.hpp ├── endian_portable.hpp ├── errc.hpp ├── file.hpp ├── ibstream.hpp ├── impl ├── ares.hpp ├── char_traits.hpp ├── concurrent_queue.hpp ├── epoll_io_watcher.hpp ├── eventfd_select_interrupter.hpp ├── evport_io_watcher.hpp ├── fp16.hpp ├── ifaddrs.hpp ├── inet_ntop.hpp ├── kqueue_io_watcher.hpp ├── mbedtls.hpp ├── object_pool.hpp ├── openssl.hpp ├── pipe_select_interrupter.hpp ├── poll_io_watcher.hpp ├── select_interrupter.hpp ├── select_io_watcher.hpp ├── socket.hpp └── socket_select_interrupter.hpp ├── io_service.cpp ├── io_service.hpp ├── io_watcher.hpp ├── logging.hpp ├── memory.hpp ├── object_pool.hpp ├── object_pool_alloc.hpp ├── obstream.hpp ├── platform ├── java │ └── com │ │ └── simdsoft │ │ └── yasio │ │ └── AppGlobals.java ├── yasio_jni.cpp ├── yasio_jni.hpp ├── yasio_unreal.cpp └── yasio_unreal.hpp ├── pod_vector.hpp ├── ref_ptr.hpp ├── shared_mutex.hpp ├── singleton.hpp ├── split.hpp ├── ssl.hpp ├── strfmt.hpp ├── string.hpp ├── string_view.hpp ├── sz.hpp ├── thread_name.hpp ├── type_traits.hpp ├── utils.hpp ├── wtimer_hres.hpp ├── xxsocket.cpp ├── xxsocket.hpp ├── yasio.hpp ├── yasio.natvis └── yasio_fwd.hpp /.appveyor.yml: -------------------------------------------------------------------------------- 1 | image: 2 | - Visual Studio 2013 3 | 4 | version: 4.3.{build} 5 | 6 | environment: 7 | global: 8 | BUILD_TYPE: Release 9 | matrix: 10 | - BUILD_ARCH: x86 11 | - BUILD_ARCH: x64 12 | 13 | install: 14 | - git submodule update --init --recursive 15 | 16 | build_script: 17 | - ps: .\build.ps1 -p win32 -a $env:BUILD_ARCH -cc msvc-120 -xc '-DYASIO_SSL_BACKEND=2' 18 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | BasedOnStyle: LLVM 3 | 4 | # Allow double brackets such as std::vector>. 5 | Standard: Cpp11 6 | 7 | SortIncludes: false 8 | 9 | # Keep lines under 100 columns long. 10 | ColumnLimit: 100 11 | 12 | # Always break before braces 13 | BreakBeforeBraces: Custom 14 | BraceWrapping: 15 | AfterClass: false 16 | AfterControlStatement: true 17 | AfterEnum: true 18 | AfterFunction: true 19 | AfterNamespace: true 20 | AfterStruct: false 21 | AfterUnion: false 22 | BeforeCatch: true 23 | BeforeElse: true 24 | IndentBraces: false 25 | SplitEmptyFunction: false 26 | SplitEmptyRecord: false 27 | SplitEmptyNamespace: false 28 | 29 | # Keeps extern "C" blocks unindented. 30 | AfterExternBlock: false 31 | 32 | # Indent case labels. 33 | IndentCaseLabels: true 34 | 35 | # Right-align pointers and references 36 | PointerAlignment: Left 37 | 38 | # ANGLE likes to align things as much as possible. 39 | AlignOperands: true 40 | AlignConsecutiveAssignments: true 41 | 42 | # Use 2 space negative offset for access modifiers 43 | AccessModifierOffset: -2 44 | 45 | # TODO(jmadill): Decide if we want this on. Doesn't have an "all or none" mode. 46 | AllowShortCaseLabelsOnASingleLine: false 47 | 48 | # Useful for spacing out functions in classes 49 | KeepEmptyLinesAtTheStartOfBlocks: true 50 | 51 | # Indent nested PP directives. 52 | IndentPPDirectives: AfterHash 53 | 54 | AlwaysBreakTemplateDeclarations: Yes 55 | 56 | AlignEscapedNewlines: Left 57 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.c linguist-language=C++ 2 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "gitsubmodule" 4 | directory: "/" 5 | schedule: 6 | interval: "monthly" 7 | -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | # Number of days of inactivity before an issue becomes stale 2 | daysUntilStale: 60 3 | # Number of days of inactivity before a stale issue is closed 4 | daysUntilClose: 7 5 | # Issues with these labels will never be considered stale 6 | exemptLabels: 7 | - pinned 8 | - security 9 | # Label to use when marking an issue as stale 10 | staleLabel: wontfix 11 | # Comment to post when marking an issue as stale. Set to `false` to disable 12 | markComment: > 13 | This issue has been automatically marked as stale because it has not had 14 | recent activity. It will be closed if no further activity occurs. Thank you 15 | for your contributions. 16 | # Comment to post when closing a stale issue. Set to `false` to disable 17 | closeComment: false 18 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: codeql 13 | 14 | on: 15 | push: 16 | branches: dev 17 | 18 | jobs: 19 | analyze: 20 | name: Analyze 21 | runs-on: ubuntu-latest 22 | permissions: 23 | actions: read 24 | contents: read 25 | security-events: write 26 | 27 | strategy: 28 | fail-fast: false 29 | matrix: 30 | language: [ 'cpp' ] 31 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 32 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 33 | 34 | steps: 35 | - name: Checkout repository 36 | uses: actions/checkout@v4 37 | with: 38 | submodules: 'recursive' 39 | 40 | # Initializes the CodeQL tools for scanning. 41 | - name: Initialize CodeQL 42 | uses: github/codeql-action/init@v3 43 | with: 44 | languages: ${{ matrix.language }} 45 | # If you wish to specify custom queries, you can do so here or in a config file. 46 | # By default, queries listed here will override any specified in a config file. 47 | # Prefix the list here with "+" to use these queries and those in the config file. 48 | 49 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 50 | # queries: security-extended,security-and-quality 51 | 52 | 53 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 54 | # If this step fails, then you should remove it and run the build manually (see below) 55 | - name: Autobuild 56 | uses: github/codeql-action/autobuild@v3 57 | 58 | # ℹ️ Command-line programs to run using the OS shell. 59 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 60 | 61 | # If the Autobuild fails above, remove it and uncomment the following three lines. 62 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. 63 | 64 | # - run: | 65 | # echo "Run, Build Application using script" 66 | # ./location_of_script_within_repo/buildscript.sh 67 | 68 | - name: Perform CodeQL Analysis 69 | uses: github/codeql-action/analyze@v3 70 | with: 71 | category: "/language:${{matrix.language}}" 72 | upload: False 73 | output: sarif-results 74 | - name: filter-sarif 75 | uses: advanced-security/filter-sarif@main 76 | with: 77 | patterns: | 78 | +**/*.cpp 79 | -thirdparty/** 80 | input: sarif-results/cpp.sarif 81 | output: sarif-results/cpp.sarif 82 | 83 | - name: Upload SARIF 84 | uses: github/codeql-action/upload-sarif@v3 85 | with: 86 | sarif_file: sarif-results/cpp.sarif 87 | 88 | - name: Upload loc as a Build Artifact 89 | uses: actions/upload-artifact@v4 90 | with: 91 | name: sarif-results 92 | path: sarif-results 93 | retention-days: 1 94 | 95 | -------------------------------------------------------------------------------- /.github/workflows/docs.yml: -------------------------------------------------------------------------------- 1 | name: docs 2 | 3 | on: 4 | push: 5 | branches: dev 6 | pull_request: 7 | workflow_dispatch: 8 | # Inputs the workflow accepts. 9 | inputs: 10 | versions: 11 | description: 'Please specific active versions' 12 | # Default value if no value is explicitly provided 13 | default: '3.39.12:3.39.x' 14 | # Input has to be provided for the workflow to run 15 | required: true 16 | env: 17 | DOCS_CI: 1 18 | PYTHON_VERSION: '3.10' 19 | 20 | jobs: 21 | documentation: 22 | name: Build docs 23 | runs-on: ubuntu-latest 24 | steps: 25 | 26 | - name: Checkout repository 27 | uses: actions/checkout@v4 28 | 29 | - name: Set up Python runtime 30 | uses: actions/setup-python@v5 31 | with: 32 | python-version: ${{ env.PYTHON_VERSION }} 33 | 34 | - name: Install Python dependencies 35 | run: | 36 | pip install -r docs/requirements.txt 37 | - name: Install missing fonts 38 | run: | 39 | wget https://github.com/simdsoft/fontlist/releases/download/v1.0/fontlist.zip 40 | unzip fontlist.zip 41 | mkdir -p ~/.fonts/ 42 | cp fontlist/* ~/.fonts/ 43 | - name: Configure commiter 44 | run: | 45 | git config user.name "docs-bot" 46 | git config user.email "docs-bot@users.noreply.github.com" 47 | git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }} 48 | git fetch 49 | - name: Build docs & deploy 50 | env: 51 | ACTIVE_VERSIONS: ${{ github.event.inputs.versions }} 52 | shell: pwsh 53 | run: ./tools/docs.ps1 "$env:ACTIVE_VERSIONS" 54 | 55 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ignored 2 | ignored/*.* 3 | *.pdb 4 | *.idb 5 | *.log 6 | *.obj 7 | *.so 8 | *.o 9 | *.lastbuildstate 10 | *.sdf 11 | *.tlog 12 | *.opensdf 13 | *.ilk 14 | *.lib 15 | *.dll 16 | *.db 17 | *.cache 18 | *.pch 19 | *.opendb 20 | *.suo 21 | /.vs 22 | /.xs 23 | /build* 24 | /.vscode 25 | /**/.DS_Store 26 | /site 27 | /_site 28 | *.xsxproj 29 | /out* 30 | /tools/external 31 | cache -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "examples/ftp_server"] 2 | path = examples/ftp_server 3 | url = https://github.com/yasio/ftp_server 4 | [submodule "3rdparty/kcp"] 5 | path = 3rdparty/kcp 6 | url = https://github.com/skywind3000/kcp.git 7 | [submodule "3rdparty/lua"] 8 | path = 3rdparty/lua 9 | url = https://github.com/lua/lua.git 10 | [submodule "3rdparty/llhttp"] 11 | path = 3rdparty/llhttp 12 | url = https://github.com/nodejs/llhttp.git 13 | [submodule "3rdparty/wepoll"] 14 | path = 3rdparty/wepoll 15 | url = https://github.com/piscisaureus/wepoll.git 16 | -------------------------------------------------------------------------------- /.readthedocs.yml: -------------------------------------------------------------------------------- 1 | # .readthedocs.yml 2 | # Read the Docs configuration file 3 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 4 | 5 | # Required 6 | version: 2 7 | 8 | # Set the version of Python and other tools you might need libjpeg-dev 9 | build: 10 | os: ubuntu-20.04 11 | tools: 12 | python: "3.9" 13 | apt_packages: 14 | - libjpeg-dev 15 | - libopenjp2-7-dev 16 | 17 | # Build documentation in the docs/ directory with Sphinx 18 | #sphinx: 19 | # configuration: conf.py 20 | 21 | # Build documentation with MkDocs 22 | mkdocs: 23 | configuration: mkdocs.yml 24 | 25 | # Optionally build your docs in additional formats such as PDF and ePub 26 | formats: all 27 | 28 | # Optionally set the version of Python and requirements required to build your docs 29 | python: 30 | install: 31 | - requirements: docs/prerequisites.txt 32 | - requirements: docs/requirements.txt 33 | -------------------------------------------------------------------------------- /1k/dm/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | cmake_minimum_required(VERSION 3.23) 3 | 4 | project(dm) 5 | 6 | find_program(PWSH_PROG NAMES pwsh powershell NO_PACKAGE_ROOT_PATH NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH NO_CMAKE_SYSTEM_PATH NO_CMAKE_FIND_ROOT_PATH) 7 | 8 | message(STATUS "CMAKE_C_COMPILER=${CMAKE_C_COMPILER}") 9 | message(STATUS "CMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}") 10 | message(STATUS "CMAKE_C_FLAGS=${CMAKE_C_FLAGS}") 11 | message(STATUS "CMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS}") 12 | message(STATUS "CMAKE_SHARED_LINKER_FLAGS=${CMAKE_SHARED_LINKER_FLAGS}") 13 | message(STATUS "CMAKE_SYSROOT=${CMAKE_SYSROOT}") 14 | 15 | set(cross_flags "") 16 | if(ANDROID) 17 | message(STATUS "ANDROID_NATIVE_API_LEVEL=${ANDROID_NATIVE_API_LEVEL}") 18 | if(CMAKE_ANDROID_ARCH_ABI MATCHES "arm64-v8a") 19 | set(cross_flags "-target aarch64-none-linux-android${ANDROID_NATIVE_API_LEVEL}") 20 | elseif(CMAKE_ANDROID_ARCH_ABI MATCHES "x86_64") 21 | set(cross_flags "-target x86_64-none-linux-android${ANDROID_NATIVE_API_LEVEL}") 22 | elseif(CMAKE_ANDROID_ARCH_ABI MATCHES "x86") 23 | set(cross_flags "-target x86-none-linux-android${ANDROID_NATIVE_API_LEVEL}") 24 | else() 25 | set(cross_flags "-target arm-none-linux-android${ANDROID_NATIVE_API_LEVEL}") 26 | endif() 27 | elseif(APPLE) 28 | if(NOT CMAKE_OSX_ARCHITECTURES) 29 | set(CMAKE_OSX_ARCHITECTURES ${CMAKE_HOST_SYSTEM_PROCESSOR}) 30 | endif() 31 | if(CMAKE_OSX_ARCHITECTURES MATCHES "arm64") 32 | set(cross_flags "-arch arm64") 33 | elseif(CMAKE_OSX_ARCHITECTURES MATCHES "x86_64") 34 | set(cross_flags "-arch x86_64") 35 | endif() 36 | endif() 37 | 38 | if(NOT ${CMAKE_C_COMPILER} MATCHES ".*cl\.exe" OR "${MSVC_VERSION}" GREATER_EQUAL 1928) 39 | execute_process(COMMAND ${PWSH_PROG} "${CMAKE_CURRENT_SOURCE_DIR}/dm.ps1" "${CMAKE_C_COMPILER}" "${CMAKE_C_FLAGS} ${cross_flags}") 40 | endif() 41 | 42 | add_library(dm dm.c) -------------------------------------------------------------------------------- /1k/dm/dm.c: -------------------------------------------------------------------------------- 1 | long double dm2x(long double v) 2 | { 3 | return v * 10.33; 4 | } -------------------------------------------------------------------------------- /1k/dm/dm.ps1: -------------------------------------------------------------------------------- 1 | # need plan args to avoid powershell preprocess args unexpected behavior 2 | $cc = $args[0] 3 | $cflags = $args[1] 4 | 5 | $IsWin = $IsWindows -or ("$env:OS" -eq 'Windows_NT') 6 | 7 | echo "cflags=${cflags}" 8 | 9 | if($cflags) { $cflags = Invoke-Expression -Command "echo $cflags" } 10 | 11 | if($cc.EndsWith('cl.exe')) { 12 | # vs2019+ support: 13 | &$cc /EP /Zc:preprocessor /PD $cflags (Join-Path $PSScriptRoot 'dm.c') 14 | } else { 15 | Write-Host "dump command: <<$cc -E -dM $cflags ->>" 16 | echo ''| &$cc -E -dM $cflags - 17 | } 18 | -------------------------------------------------------------------------------- /1k/fsync.ps1: -------------------------------------------------------------------------------- 1 | # sync file or directory 2 | # .\fsync.ps1 -s srcPath -d destPath -l 1 3 | param( 4 | [Parameter(Mandatory=$true, ValueFromPipeline=$true)] 5 | [string]$srcPath, 6 | [Parameter(Mandatory=$true, ValueFromPipeline=$true)] 7 | [string]$destPath, 8 | [Parameter(Mandatory=$false, ValueFromPipeline=$true)] 9 | [PSDefaultValue(Value=$null)] 10 | $linkOnly 11 | ) 12 | 13 | 14 | function ParseBoolFuzzy($value) { 15 | $value = "$value".ToLower() 16 | return $value.startsWith('1') -or $value.StartsWith('t') -or $value.StartsWith('y') 17 | } 18 | 19 | $linkOnly = ParseBoolFuzzy($linkOnly) 20 | 21 | # 0: windows, 1: linux, 2: macos 22 | $IsWin = $IsWindows -or ("$env:OS" -eq 'Windows_NT') 23 | 24 | # convert to native path style 25 | if ($IsWin) { 26 | $srcPath = $srcPath.Replace('/', '\') 27 | $destPath = $destPath.Replace('/', '\') 28 | } else { 29 | $srcPath = $srcPath.Replace('\', '/') 30 | $destPath = $destPath.Replace('\', '/') 31 | } 32 | 33 | if(!$srcPath -or !(Test-Path $srcPath -PathType Any)) { 34 | throw "fsync.ps1: The source directory $srcPath not exist" 35 | } 36 | 37 | if (Test-Path $destPath -PathType Any) { # dest already exist 38 | if ($linkOnly) { # is symlink and dest exist 39 | $fileItem = (Get-Item $destPath) 40 | if ($fileItem.Target -eq $srcPath) { 41 | Write-Host "fsync.ps1: Symlink $destPath ===> $($fileItem.Target) exists" 42 | return 43 | } 44 | Write-Host "fsync.ps1: Removing old link target $($fileItem.Target)" 45 | # force delete if exist dest not symlink 46 | if ($fileItem.PSIsContainer -and !$fileItem.Target) { 47 | $fileItem.Delete($true) 48 | } else { 49 | $fileItem.Delete() 50 | } 51 | } 52 | } 53 | 54 | $destLoc = Split-Path $destPath -Parent 55 | if (!(Test-Path $destLoc -PathType Container)) { 56 | New-Item $destLoc -ItemType Directory 1>$null 57 | } 58 | 59 | if ($linkOnly) { 60 | Write-Host "fsync.ps1: Symlink $srcPath to $destPath ..." 61 | if ($IsWin -and (Test-Path $srcPath -PathType Container)) { 62 | cmd.exe /c mklink /J $destPath $srcPath 63 | } 64 | else { 65 | # ln -s $srcPath $destPath 66 | New-Item -ItemType SymbolicLink -Path $destPath -Target $srcPath 2>$null 67 | } 68 | } 69 | else { # copy 70 | Write-Host "fsync.ps1: Copying $srcPath to $destPath ..." 71 | if (Test-Path $srcPath -PathType Container) { 72 | if (!(Test-Path $destPath -PathType Container)) { 73 | Copy-Item $srcPath $destPath -Recurse -Force 74 | } else { 75 | Copy-Item $srcPath/* $destPath/ -Recurse -Force 76 | } 77 | } else { 78 | Copy-Item $srcPath $destPath -Force 79 | } 80 | } 81 | 82 | if(!$?) { # $Error array 83 | exit 1 84 | } 85 | -------------------------------------------------------------------------------- /1k/install-pwsh.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Install powershell 7 on macOS, Ubuntu, ArchLinux to system path 3 | # usage: ./install-pwsh [pwsh_ver] 4 | # 5 | 6 | HOST_OS=$(uname) 7 | 8 | myRoot=$(dirname "$0") 9 | 10 | cacheDir=~/.1kiss 11 | mkdir -p $cacheDir 12 | 13 | pwsh_ver=$1 14 | if [ "$pwsh_ver" = "" ] ; then 15 | pwsh_ver='7.4.6' 16 | fi 17 | 18 | pwsh_min_ver=$2 19 | if [ "$pwsh_min_ver" = "" ] ; then 20 | pwsh_min_ver='7.3.0' 21 | fi 22 | 23 | if [[ "$pwsh_ver" < "$pwsh_min_ver" ]] ; then 24 | pwsh_ver=$pwsh_min_ver 25 | fi 26 | 27 | function check_pwsh { 28 | min_ver=$1 29 | preferred_ver=$2 30 | if command -v pwsh >/dev/null ; then 31 | verx=$(pwsh --version) 32 | very="PowerShell $min_ver" 33 | if ([ "$preferred_ver" != "$min_ver" ] && ([[ "$verx" > "$very" ]] || [ "$verx" = "$very" ])) \ 34 | || ([ "$preferred_ver" = "$min_ver" ] && [ "$verx" = "$very" ]) ; then 35 | echo "1kiss: $verx installed." 36 | exit 0 37 | fi 38 | fi 39 | echo "Installing PowerShell $preferred_ver ..." 40 | } 41 | 42 | HOST_ARCH=$(uname -m) 43 | if [ "$HOST_ARCH" = 'x86_64' ] ; then 44 | HOST_ARCH=x64 45 | fi 46 | 47 | if [ $HOST_OS = 'Darwin' ] ; then 48 | check_pwsh $pwsh_min_ver $preferred_ver 49 | pwsh_pkg="powershell-$pwsh_ver-osx-$HOST_ARCH.pkg" 50 | pwsh_pkg_out="$cacheDir/$pwsh_pkg" 51 | if [ ! -f "$pwsh_pkg_out" ] ; then 52 | pwsh_url="https://github.com/PowerShell/PowerShell/releases/download/v$pwsh_ver/$pwsh_pkg" 53 | echo "Downloading $pwsh_url ..." 54 | curl -L "$pwsh_url" -o "$pwsh_pkg_out" 55 | fi 56 | sudo xattr -rd com.apple.quarantine "$pwsh_pkg_out" 57 | sudo installer -pkg "$pwsh_pkg_out" -target / 58 | elif [ $HOST_OS = 'Linux' ] ; then 59 | if command -v dpkg > /dev/null; then # Linux distro: deb (ubuntu) 60 | check_pwsh $pwsh_min_ver $preferred_ver 61 | pwsh_pkg="powershell_$pwsh_ver-1.deb_amd64.deb" 62 | pwsh_pkg_out="$cacheDir/$pwsh_pkg" 63 | if [ ! -f "$pwsh_pkg_out" ] ; then 64 | curl -L "https://github.com/PowerShell/PowerShell/releases/download/v$pwsh_ver/$pwsh_pkg" -o "$pwsh_pkg_out" 65 | fi 66 | sudo_cmd=$(which sudo) 67 | $sudo_cmd dpkg -i --ignore-depends=libicu72 "$pwsh_pkg_out" 68 | $sudo_cmd apt-get install -f powershell 69 | elif command -v pacman > /dev/null; then # Linux distro: Arch 70 | # refer: https://ephos.github.io/posts/2018-9-17-Pwsh-ArchLinux 71 | # available pwsh version, refer to: https://aur.archlinux.org/packages/powershell-bin 72 | check_pwsh $pwsh_min_ver 73 | git clone https://aur.archlinux.org/powershell-bin.git $cacheDir/powershell-bin 74 | cd $cacheDir/powershell-bin 75 | makepkg -si --needed --noconfirm 76 | cd - 77 | fi 78 | else 79 | echo "Unsupported HOST OS: $HOST_OS" 80 | exit 1 81 | fi 82 | 83 | if command -v pwsh >/dev/null ; then 84 | installed_pwsh_ver=$(pwsh --version) 85 | echo "Install PowerShell $installed_pwsh_ver succeed." 86 | else 87 | echo "Install PowerShell fail, try again" 88 | if [ -f "$pwsh_pkg_out" ] ; then 89 | rm -f "$pwsh_pkg_out" 90 | fi 91 | fi 92 | -------------------------------------------------------------------------------- /1k/manifest.ps1: -------------------------------------------------------------------------------- 1 | # Default manifest, refer in 1k/1kiss.ps1 2 | 3 | if ($IsWin) { 4 | $manifest['nasm'] = '2.16.03+' 5 | } else { 6 | $manifest['nasm'] = '2.15.05+' 7 | } 8 | 9 | $manifest['cmake'] = '3.23.0+' 10 | -------------------------------------------------------------------------------- /1k/platforms.cmake: -------------------------------------------------------------------------------- 1 | #Please use them everywhere 2 | #WINDOWS = Windows Desktop 3 | #ANDROID = Android 4 | #IOS = iOS 5 | #MACOSX = MacOS X 6 | #LINUX = Linux 7 | 8 | ############################# 9 | # cmake commands: 10 | # win32: cmake -B build -A x64 11 | # winrt: cmake -B build -A x64 -DCMAKE_SYSTEM_NAME=WindowsStore "-DCMAKE_SYSTEM_VERSION=10.0" 12 | # 13 | 14 | if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") 15 | set(WINDOWS TRUE) 16 | string(TOLOWER "${CMAKE_GENERATOR_PLATFORM}" _gp_lcase) 17 | if("${_gp_lcase}" MATCHES "win32") 18 | set(WIN32 TRUE) 19 | set(ARCH_ALIAS "x86") 20 | elseif("${_gp_lcase}" STREQUAL "arm64") 21 | set(WIN64 TRUE) 22 | set(ARCH_ALIAS "arm64") 23 | else() 24 | set(WIN64 TRUE) 25 | set(ARCH_ALIAS "x64") 26 | endif() 27 | set(PLATFORM_NAME win32) 28 | if (${CMAKE_SYSTEM_NAME} MATCHES "WindowsStore") 29 | set(WINRT TRUE CACHE BOOL "" FORCE) 30 | set(PLATFORM_NAME winrt) 31 | endif() 32 | elseif(${CMAKE_SYSTEM_NAME} MATCHES "Android") 33 | set(PLATFORM_NAME android) 34 | set(ARCH_ALIAS ${ANDROID_ABI}) 35 | 36 | # refer 37 | # - https://developer.android.com/about/versions/15/behavior-changes-all#16-kb 38 | # - https://developer.android.google.cn/about/versions/15/behavior-changes-all?hl=zh-cn#16-kb 39 | set(_16KPAGE_SIZE_LD_FLAGS "-Wl,-z,max-page-size=16384") 40 | elseif(${CMAKE_SYSTEM_NAME} MATCHES "Linux") 41 | set(LINUX TRUE) 42 | set(PLATFORM_NAME linux) 43 | elseif(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") 44 | set(WASM TRUE) 45 | set(EMSCRIPTEN TRUE) 46 | if ("${CMAKE_LIBRARY_ARCHITECTURE}" MATCHES "64") 47 | set(PLATFORM_NAME wasm64) 48 | else() 49 | set(PLATFORM_NAME wasm) 50 | endif() 51 | elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") 52 | set(APPLE TRUE) 53 | set(MACOSX TRUE) 54 | set(PLATFORM_NAME mac) 55 | elseif(${CMAKE_SYSTEM_NAME} MATCHES "iOS") 56 | set(APPLE TRUE) 57 | set(IOS TRUE) 58 | set(PLATFORM_NAME ios) 59 | elseif(${CMAKE_SYSTEM_NAME} MATCHES "tvOS") 60 | set(APPLE TRUE) 61 | set(IOS TRUE) 62 | set(TVOS TRUE) 63 | set(PLATFORM_NAME tvos) 64 | elseif(${CMAKE_SYSTEM_NAME} MATCHES "OHOS") 65 | set(OHOS TRUE) 66 | set(PLATFORM_NAME ohos) 67 | else() 68 | message(AUTHOR_WARNING "Unhandled platform: ${CMAKE_SYSTEM_NAME}") 69 | endif() 70 | 71 | if (NOT DEFINED WIN32) 72 | set(WIN32 FALSE) 73 | endif() 74 | 75 | # generators that are capable of organizing into a hierarchy of folders 76 | set_property(GLOBAL PROPERTY USE_FOLDERS ON) 77 | # simplify generator condition, please use them everywhere 78 | if(CMAKE_GENERATOR STREQUAL Xcode) 79 | set(XCODE TRUE) 80 | elseif(CMAKE_GENERATOR MATCHES Visual) 81 | set(VS TRUE) 82 | endif() 83 | 84 | # The global rpath settings 85 | if(LINUX OR APPLE) 86 | set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE CACHE BOOL "" FORCE) 87 | if(LINUX) 88 | set(CMAKE_INSTALL_RPATH ".:\$ORIGIN:\$ORIGIN/../lib:${CMAKE_BINARY_DIR}/lib") 89 | elseif(APPLE) 90 | set(CMAKE_SKIP_BUILD_RPATH TRUE CACHE BOOL "" FORCE) 91 | if(IOS) 92 | set(CMAKE_INSTALL_RPATH "/usr/lib/swift" "@executable_path/Frameworks") 93 | else() 94 | set(CMAKE_INSTALL_RPATH "@executable_path/../Frameworks") 95 | endif() 96 | endif() 97 | endif() 98 | 99 | function(_1k_deprecated_32bit project_name release_ver) 100 | if(("${ARCH_ALIAS}" STREQUAL "x86") OR ("${ARCH_ALIAS}" MATCHES "armeabi-v7a")) 101 | message(WARNING "Building 32-bit[${ARCH_ALIAS}] ${project_name} is deprecated, and will be removed in next release ${release_ver}") 102 | endif() 103 | endfunction() 104 | -------------------------------------------------------------------------------- /1k/resolv-url.ps1: -------------------------------------------------------------------------------- 1 | # resolve artifact url 2 | param( 3 | [Alias('artifact')] 4 | $name, 5 | $manifest, 6 | $target, 7 | $build_id, 8 | $branch, 9 | $out_var 10 | ) 11 | 12 | $artifact_url = $null 13 | 14 | if ($manifest -eq 'gcloud') { 15 | function Get-LatestGoodBuild { 16 | param ( 17 | [string]$branch, 18 | [string]$target 19 | ) 20 | 21 | $apiURL = "https://androidbuildinternal.googleapis.com/android/internal/build/v3/builds?branches=$([uri]::EscapeDataString($branch))&buildAttemptStatus=complete&buildType=submitted&maxResults=1&successful=true&target=$([uri]::EscapeDataString($target))" 22 | $body = Invoke-WebRequest -Uri $apiURL 23 | $buildData = $body | ConvertFrom-Json 24 | if ($buildData.builds.Count -eq 0) { 25 | throw "No build ID is found" 26 | } 27 | return $buildData.builds[0].buildId 28 | } 29 | 30 | # Validate input parameters 31 | $artifact = $name 32 | if (-not $target) { throw "Missing target." } 33 | if (-not $artifact) { throw "Missing artifact." } 34 | if (-not $build_id -and -not $branch) { throw "Missing build_id or branch." } 35 | if (-not $build_id -and $branch) { 36 | $build_id = Get-LatestGoodBuild -branch $branch -target $target 37 | } 38 | 39 | $artifact_url = "https://androidbuildinternal.googleapis.com/android/internal/build/v3/builds/$([uri]::EscapeDataString($build_id))/$([uri]::EscapeDataString($target))/attempts/latest/artifacts/$([uri]::EscapeDataString($artifact))/url" 40 | } 41 | else { 42 | if (Test-Path $manifest -PathType Leaf) { 43 | $mirror = if (!(Test-Path (Join-Path $PSScriptRoot '.gitee') -PathType Leaf)) { 'github' } else { 'gitee' } 44 | 45 | $manifest_map = ConvertFrom-Json (Get-Content $manifest -raw) 46 | $ver = $manifest_map.versions.PSObject.Properties[$name].Value 47 | $mirror_current = $manifest_map.mirrors.PSObject.Properties[$mirror].Value.PSObject.Properties 48 | $url_base = "https://$($mirror_current['host'].Value)/" 49 | $url_path = $mirror_current[$name].Value 50 | 51 | $artifact_url = "$url_base$url_path#$ver" 52 | } 53 | } 54 | 55 | if($artifact_url) { 56 | if(!$out_var) { 57 | Write-Host $artifact_url -NoNewline 58 | } else { 59 | Write-Information $artifact_url -InformationVariable $out_var 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /3rdparty/.gitignore: -------------------------------------------------------------------------------- 1 | /**/*.zip 2 | /**/*_x -------------------------------------------------------------------------------- /3rdparty/README.md: -------------------------------------------------------------------------------- 1 | # The 3rdparty of yasio 2 | 3 | If pass `-DYASIO_NO_DEPS=ON` to cmake, yasio will not use any dependent in this directory. 4 | -------------------------------------------------------------------------------- /3rdparty/c-ares/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | set(target_name c-ares) 3 | 4 | project(${target_name}) 5 | 6 | _1kfetch_dist(cares) 7 | 8 | if(WINDOWS) 9 | add_library(${target_name} SHARED IMPORTED GLOBAL) 10 | else() 11 | add_library(${target_name} STATIC IMPORTED GLOBAL) 12 | endif() 13 | 14 | set_target_properties(${target_name} PROPERTIES 15 | INTERFACE_INCLUDE_DIRECTORIES "${cares_INC_DIR}" 16 | INTERFACE_COMPILE_DEFINITIONS CARES_STATICLIB=1 17 | ) 18 | 19 | if (APPLE) 20 | set_target_properties(${target_name} PROPERTIES 21 | INTERFACE_LINK_LIBRARIES resolv 22 | ) 23 | endif() 24 | 25 | if(WINDOWS) 26 | set_target_properties(${target_name} PROPERTIES 27 | IMPORTED_IMPLIB "${cares_LIB_DIR}/cares.lib" 28 | ) 29 | elseif(APPLE) 30 | set_target_properties(${target_name} PROPERTIES 31 | IMPORTED_LOCATION "${cares_LIB_DIR}/cares.xcframework" 32 | ) 33 | else() 34 | set_target_properties(${target_name} PROPERTIES 35 | IMPORTED_LOCATION "${cares_LIB_DIR}/libcares.a" 36 | ) 37 | endif() 38 | 39 | set(CARES_INCLUDE_DIR "${cares_INC_DIR}" CACHE STRING "c-ares Include Directory" ) 40 | -------------------------------------------------------------------------------- /3rdparty/half/README.md: -------------------------------------------------------------------------------- 1 | # half.hpp 2 | 3 | Retrieves from half library: http://half.sourceforge.net/ 4 | 5 | ## See also 6 | 7 | https://github.com/Maratyszcza/FP16 8 | -------------------------------------------------------------------------------- /3rdparty/kaguya/README.md: -------------------------------------------------------------------------------- 1 | ## kaguya is a C++ library binding to Lua, require C++11 2 | see: https://github.com/satoren/kaguya 3 | 4 | **pitfall: kaguya can't handle unaligned pointer from ```lua_newuserdata``` will cause crash at ```apple clang``` release optimized mode.** 5 | * If you want use luabinding provided by yasio, we strong recommand upgrade your build system to c++14, then yasio will auto choose the mostly modern lua binding solution sol: https://github.com/ThePhD/sol2 6 | * Another reason you don't choose ```kaguya``` is it's lost maintain more than 3 years 7 | * From the reference: http://lua-users.org/lists/lua-l/2019-07/msg00197.html, if you still want use c++11, you must define compiler marco **```LUAI_USER_ALIGNMENT_T=max_align_t```** for lua_newuserdata can return properly aligned pointer 8 | -------------------------------------------------------------------------------- /3rdparty/moodycamel/README.md: -------------------------------------------------------------------------------- 1 | # A single-producer, single-consumer lock-free queue for C++ 2 | [![GitHub stars](https://img.shields.io/github/stars/cameron314/readerwriterqueue.svg?label=Stars)](https://github.com/cameron314/readerwriterqueue) 3 | see: https://github.com/cameron314/readerwriterqueue -------------------------------------------------------------------------------- /3rdparty/openssl/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | set(lib_name openssl) 3 | 4 | project(${lib_name}) 5 | 6 | _1kfetch_dist(openssl) 7 | 8 | set(OPENSSL_INCLUDE_DIR "${openssl_INC_DIR}" CACHE STRING "OpenSSL include dir" FORCE) 9 | 10 | # -----macro: set openssl sub target----- 11 | macro(set_openssl_sub_target sub_target_name sub_lib_name) 12 | 13 | if(WINDOWS) 14 | add_library(${sub_target_name} SHARED IMPORTED GLOBAL) 15 | else() 16 | add_library(${sub_target_name} STATIC IMPORTED GLOBAL) 17 | endif() 18 | 19 | set_target_properties(${sub_target_name} PROPERTIES 20 | INTERFACE_INCLUDE_DIRECTORIES "${openssl_INC_DIR}" 21 | ) 22 | 23 | if(WINDOWS) 24 | set(impl_lib_suffix "") 25 | if(WIN64) 26 | set(impl_lib_suffix "-${ARCH_ALIAS}") 27 | endif() 28 | set_target_properties(${sub_target_name} PROPERTIES 29 | IMPORTED_LOCATION "${openssl_LIB_DIR}/lib${sub_lib_name}-3${impl_lib_suffix}.dll" 30 | IMPORTED_IMPLIB "${openssl_LIB_DIR}/lib${sub_lib_name}.lib" 31 | ) 32 | elseif(APPLE) 33 | set_target_properties(${sub_target_name} PROPERTIES 34 | IMPORTED_LOCATION "${openssl_LIB_DIR}/ossl-${sub_lib_name}.xcframework" 35 | ) 36 | else() 37 | set_target_properties(${sub_target_name} PROPERTIES 38 | IMPORTED_LOCATION "${openssl_LIB_DIR}/lib${sub_lib_name}.a" 39 | ) 40 | endif() 41 | if(${sub_lib_name} STREQUAL "ssl") 42 | set(OPENSSL_ROOT_DIR "${openssl_LIB_DIR}" CACHE STRING "" FORCE) 43 | set(OPENSSL_SSL_LIBRARY "OpenSSL::SSL" CACHE STRING "" FORCE) 44 | else() 45 | set(OPENSSL_CRYPTO_LIBRARY "OpenSSL::Crypto" CACHE STRING "" FORCE) 46 | endif() 47 | endmacro() 48 | 49 | # -----sub target 1: ssl----- 50 | set(target_name OpenSSL::SSL ssl) 51 | set_openssl_sub_target(${target_name}) 52 | 53 | # -----sub target 2: crypto----- 54 | set(target_name OpenSSL::Crypto crypto) 55 | set_openssl_sub_target(${target_name}) 56 | -------------------------------------------------------------------------------- /3rdparty/sol/README.md: -------------------------------------------------------------------------------- 1 | ## sol(v3.3.0) is a C++ library binding to Lua, require C++17+. 2 | [![GitHub stars](https://img.shields.io/github/stars/ThePhD/sol2.svg?label=Stars)](https://github.com/ThePhD/sol2) 3 | see: https://github.com/ThePhD/sol2 4 | -------------------------------------------------------------------------------- /3rdparty/sol/config.hpp: -------------------------------------------------------------------------------- 1 | // The MIT License (MIT) 2 | 3 | // Copyright (c) 2013-2020 Rapptz, ThePhD and contributors 4 | 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | // this software and associated documentation files (the "Software"), to deal in 7 | // the Software without restriction, including without limitation the rights to 8 | // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | // the Software, and to permit persons to whom the Software is furnished to do so, 10 | // 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, FITNESS 17 | // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | 22 | // This file was generated with a script. 23 | // Generated 2022-06-25 08:14:19.336233 UTC 24 | // This header was generated with sol v3.3.0 (revision eba86625) 25 | // https://github.com/ThePhD/sol2 26 | 27 | #ifndef SOL_SINGLE_CONFIG_HPP 28 | #define SOL_SINGLE_CONFIG_HPP 29 | 30 | // beginning of sol/config.hpp 31 | 32 | /* Base, empty configuration file! 33 | 34 | To override, place a file in your include paths of the form: 35 | 36 | . (your include path here) 37 | | sol (directory, or equivalent) 38 | | config.hpp (your config.hpp file) 39 | 40 | So that when sol2 includes the file 41 | 42 | #include 43 | 44 | it gives you the configuration values you desire. Configuration values can be 45 | seen in the safety.rst of the doc/src, or at 46 | https://sol2.readthedocs.io/en/latest/safety.html ! You can also pass them through 47 | the build system, or the command line options of your compiler. 48 | 49 | */ 50 | 51 | // end of sol/config.hpp 52 | 53 | #endif // SOL_SINGLE_CONFIG_HPP 54 | -------------------------------------------------------------------------------- /3rdparty/sol2/README.md: -------------------------------------------------------------------------------- 1 | ## sol(v2.20.6) is a C++ library binding to Lua, require C++14. 2 | [![GitHub stars](https://img.shields.io/github/stars/ThePhD/sol2.svg?label=Stars)](https://github.com/ThePhD/sol2) 3 | see: https://github.com/ThePhD/sol2 4 | -------------------------------------------------------------------------------- /3rdparty/websocket-parser/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | set(lib_name websocket-parser) 3 | set(target_name ${lib_name}) 4 | 5 | project(${lib_name}) 6 | 7 | FILE(GLOB_RECURSE ${target_name}_src *.h;*.c) 8 | 9 | add_library(${target_name} STATIC 10 | ${${target_name}_src} 11 | ) 12 | 13 | target_include_directories(${target_name} PUBLIC "${CMAKE_CURRENT_LIST_DIR}") 14 | 15 | -------------------------------------------------------------------------------- /3rdparty/websocket-parser/websocket_parser.h: -------------------------------------------------------------------------------- 1 | #ifndef WEBSOCKET_PARSER_H 2 | #define WEBSOCKET_PARSER_H 3 | #ifdef __cplusplus 4 | extern "C" { 5 | #endif 6 | 7 | 8 | #include 9 | #if defined(_WIN32) && !defined(__MINGW32__) && \ 10 | (!defined(_MSC_VER) || _MSC_VER<1600) && !defined(__WINE__) 11 | #include 12 | #include 13 | typedef __int8 int8_t; 14 | typedef unsigned __int8 uint8_t; 15 | typedef __int16 int16_t; 16 | typedef unsigned __int16 uint16_t; 17 | typedef __int32 int32_t; 18 | typedef unsigned __int32 uint32_t; 19 | typedef __int64 int64_t; 20 | typedef unsigned __int64 uint64_t; 21 | #else 22 | #include 23 | #endif 24 | 25 | #define WEBSOCKET_UUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" 26 | 27 | typedef struct websocket_parser websocket_parser; 28 | typedef struct websocket_parser_settings websocket_parser_settings; 29 | 30 | typedef enum websocket_flags { 31 | // opcodes 32 | WS_OP_CONTINUE = 0x0, 33 | WS_OP_TEXT = 0x1, 34 | WS_OP_BINARY = 0x2, 35 | WS_OP_CLOSE = 0x8, 36 | WS_OP_PING = 0x9, 37 | WS_OP_PONG = 0xA, 38 | 39 | // marks 40 | WS_FINAL_FRAME = 0x10, 41 | WS_HAS_MASK = 0x20, 42 | } websocket_flags; 43 | 44 | #define WS_OP_MASK 0xF 45 | #define WS_FIN WS_FINAL_FRAME 46 | 47 | typedef int (*websocket_data_cb) (websocket_parser*, const char * at, size_t length); 48 | typedef int (*websocket_cb) (websocket_parser*); 49 | 50 | struct websocket_parser { 51 | uint32_t state; 52 | websocket_flags flags; 53 | 54 | char mask[4]; 55 | uint8_t mask_offset; 56 | 57 | size_t length; 58 | size_t require; 59 | size_t offset; 60 | 61 | void * data; 62 | }; 63 | 64 | struct websocket_parser_settings { 65 | websocket_cb on_frame_header; 66 | websocket_data_cb on_frame_body; 67 | websocket_cb on_frame_end; 68 | }; 69 | 70 | void websocket_parser_init(websocket_parser *parser); 71 | void websocket_parser_settings_init(websocket_parser_settings *settings); 72 | size_t websocket_parser_execute( 73 | websocket_parser * parser, 74 | const websocket_parser_settings *settings, 75 | const char * data, 76 | size_t len 77 | ); 78 | 79 | // Apply XOR mask (see https://tools.ietf.org/html/rfc6455#section-5.3) and store mask's offset 80 | void websocket_parser_decode(char * dst, const char * src, size_t len, websocket_parser * parser); 81 | 82 | // Apply XOR mask (see https://tools.ietf.org/html/rfc6455#section-5.3) and return mask's offset 83 | uint8_t websocket_decode(char * dst, const char * src, size_t len, const char mask[4], uint8_t mask_offset); 84 | #define websocket_encode(dst, src, len, mask, mask_offset) websocket_decode(dst, src, len, mask, mask_offset) 85 | 86 | // Calculate frame size using flags and data length 87 | size_t websocket_calc_frame_size(websocket_flags flags, size_t data_len); 88 | 89 | // Create string representation of frame 90 | size_t websocket_build_frame(char * frame, websocket_flags flags, const char mask[4], const char * data, size_t data_len); 91 | 92 | #define websocket_parser_get_opcode(p) (p->flags & WS_OP_MASK) 93 | #define websocket_parser_has_mask(p) (p->flags & WS_HAS_MASK) 94 | #define websocket_parser_has_final(p) (p->flags & WS_FIN) 95 | 96 | #ifdef __cplusplus 97 | } 98 | #endif 99 | #endif //WEBSOCKET_PARSER_H 100 | -------------------------------------------------------------------------------- /BSL_1_0.txt: -------------------------------------------------------------------------------- 1 | Boost Software License - Version 1.0 - August 17th, 2003 2 | 3 | Permission is hereby granted, free of charge, to any person or organization 4 | obtaining a copy of the software and accompanying documentation covered by 5 | this license (the "Software") to use, reproduce, display, distribute, 6 | execute, and transmit the Software, and to prepare derivative works of the 7 | Software, and to permit third-parties to whom the Software is furnished to 8 | do so, all subject to the following: 9 | 10 | The copyright notices in the Software and this entire statement, including 11 | the above license grant, this restriction and the following disclaimer, 12 | must be included in all copies of the Software, in whole or in part, and 13 | all derivative works of the Software, unless such copies or derivative 14 | works are solely in the form of machine-executable object code generated by 15 | a source language processor. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT 20 | SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE 21 | FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, 22 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /CMakePresets.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 3, 3 | "configurePresets": [ 4 | { 5 | "name": "windows-base", 6 | "hidden": true, 7 | "generator": "Ninja", 8 | "binaryDir": "${sourceDir}/out/build/${presetName}", 9 | "installDir": "${sourceDir}/out/install/${presetName}", 10 | "cacheVariables": { 11 | "CMAKE_C_COMPILER": "cl.exe", 12 | "CMAKE_CXX_COMPILER": "cl.exe" 13 | }, 14 | "condition": { 15 | "type": "equals", 16 | "lhs": "${hostSystemName}", 17 | "rhs": "Windows" 18 | } 19 | }, 20 | { 21 | "name": "x64-debug", 22 | "displayName": "x64 Debug", 23 | "inherits": "windows-base", 24 | "architecture": { 25 | "value": "x64", 26 | "strategy": "external" 27 | }, 28 | "cacheVariables": { 29 | "CMAKE_BUILD_TYPE": "Debug" 30 | } 31 | }, 32 | { 33 | "name": "x64-release", 34 | "displayName": "x64 Release", 35 | "inherits": "x64-debug", 36 | "cacheVariables": { 37 | "CMAKE_BUILD_TYPE": "Release" 38 | } 39 | }, 40 | { 41 | "name": "x86-debug", 42 | "displayName": "x86 Debug", 43 | "inherits": "windows-base", 44 | "architecture": { 45 | "value": "x86", 46 | "strategy": "external" 47 | }, 48 | "cacheVariables": { 49 | "CMAKE_BUILD_TYPE": "Debug" 50 | } 51 | }, 52 | { 53 | "name": "x86-release", 54 | "displayName": "x86 Release", 55 | "inherits": "x86-debug", 56 | "cacheVariables": { 57 | "CMAKE_BUILD_TYPE": "Release" 58 | } 59 | }, 60 | { 61 | "name": "linux-debug", 62 | "displayName": "Linux Debug", 63 | "generator": "Ninja", 64 | "binaryDir": "${sourceDir}/out/build/${presetName}", 65 | "installDir": "${sourceDir}/out/install/${presetName}", 66 | "cacheVariables": { 67 | "CMAKE_BUILD_TYPE": "Debug" 68 | }, 69 | "condition": { 70 | "type": "equals", 71 | "lhs": "${hostSystemName}", 72 | "rhs": "Linux" 73 | }, 74 | "vendor": { 75 | "microsoft.com/VisualStudioRemoteSettings/CMake/1.0": { 76 | "sourceDir": "$env{HOME}/.vs/$ms{projectDirName}" 77 | } 78 | } 79 | }, 80 | { 81 | "name": "macos-debug", 82 | "displayName": "macOS Debug", 83 | "generator": "Ninja", 84 | "binaryDir": "${sourceDir}/out/build/${presetName}", 85 | "installDir": "${sourceDir}/out/install/${presetName}", 86 | "cacheVariables": { 87 | "CMAKE_BUILD_TYPE": "Debug" 88 | }, 89 | "condition": { 90 | "type": "equals", 91 | "lhs": "${hostSystemName}", 92 | "rhs": "Darwin" 93 | }, 94 | "vendor": { 95 | "microsoft.com/VisualStudioRemoteSettings/CMake/1.0": { 96 | "sourceDir": "$env{HOME}/.vs/$ms{projectDirName}" 97 | } 98 | } 99 | } 100 | ] 101 | } 102 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2012-present HALX99 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 | 23 | ------------------------------------------------------------------------------ 24 | 25 | The Anti 996 License 26 | 27 | Copyright (c) 2019-present HALX99 28 | 29 | "Anti 996" License Version 1.0 (Draft) 30 | 31 | Permission is hereby granted to any individual or legal entity 32 | obtaining a copy of this licensed work (including the source code, 33 | documentation and/or related items, hereinafter collectively referred 34 | to as the "licensed work"), free of charge, to deal with the licensed 35 | work for any purpose, including without limitation, the rights to use, 36 | reproduce, modify, prepare derivative works of, distribute, publish 37 | and sublicense the licensed work, subject to the following conditions: 38 | 39 | 1. The individual or the legal entity must conspicuously display, 40 | without modification, this License and the notice on each redistributed 41 | or derivative copy of the Licensed Work. 42 | 43 | 2. The individual or the legal entity must strictly comply with all 44 | applicable laws, regulations, rules and standards of the jurisdiction 45 | relating to labor and employment where the individual is physically 46 | located or where the individual was born or naturalized; or where the 47 | legal entity is registered or is operating (whichever is stricter). In 48 | case that the jurisdiction has no such laws, regulations, rules and 49 | standards or its laws, regulations, rules and standards are 50 | unenforceable, the individual or the legal entity are required to 51 | comply with Core International Labor Standards. 52 | 53 | 3. The individual or the legal entity shall not induce, suggest or force 54 | its employee(s), whether full-time or part-time, or its independent 55 | contractor(s), in any methods, to agree in oral or written form, to 56 | directly or indirectly restrict, weaken or relinquish his or her 57 | rights or remedies under such laws, regulations, rules and standards 58 | relating to labor and employment as mentioned above, no matter whether 59 | such written or oral agreements are enforceable under the laws of the 60 | said jurisdiction, nor shall such individual or the legal entity 61 | limit, in any methods, the rights of its employee(s) or independent 62 | contractor(s) from reporting or complaining to the copyright holder or 63 | relevant authorities monitoring the compliance of the license about 64 | its violation(s) of the said license. 65 | 66 | THE LICENSED WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 67 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 68 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 69 | IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, 70 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 71 | OTHERWISE, ARISING FROM, OUT OF OR IN ANY WAY CONNECTION WITH THE 72 | LICENSED WORK OR THE USE OR OTHER DEALINGS IN THE LICENSED WORK. 73 | -------------------------------------------------------------------------------- /benchmark.md: -------------------------------------------------------------------------------- 1 | ## Devices: 2 | - Windows 10: Intel(R) Core(TM) i7-9700 CPU @ 3.00GHz / Windows 10(10.0.19041.264) 3 | - Linux: Intel(R) Xeon(R) Platinum 8163 CPU @ 2.50GHz / Ubuntu 20.04 (Single Core CPU) 4 | - macOS: Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz / macOS 10.15.4 5 | - Android: XIAOMI MIX2S (cocos2d-x game engine cpp-tests) 6 | 7 | ## Test Code: [speedtest](https://github.com/yasio/yasio/blob/master/tests/speed/main.cpp) 8 | 9 | ## Architecture: 10 | - PC: X64 11 | - Android: armv7a 12 | 13 | ## Compiling: 14 | - Windows: VS2019 MSVC 14.25.28610 15 | Optimize Flag: /O2 16 | Commands: 17 | - mkdir build/build_w64 18 | - cd build/build_w64 19 | - cmake ../../ 20 | - cmake --build . --config Release --target speedtest 21 | - Linux: gcc version 9.3.0 (Ubuntu 9.3.0-10ubuntu2) 22 | Optimize Flag: /O3 23 | Commands: 24 | - mkdir -p build/build_linux 25 | - cd build/build_linux 26 | - cmake ../../ -DCMAKE_BUILD_TYPE=Release 27 | - cmake --build . --config Release --target speedtest 28 | - macOS 10.15.4: Apple Clang 11.0.0 Release build 29 | 30 | ## Send Parameters: 31 | - Total Time: 10(s) 32 | - KCP Send Interval: 10(us) 33 | - Send Bytes Per Time: 62KB 34 | 35 | ## Results: 36 | - TCP speed: 37 | - Windows: 22.4Gbits/s+ 38 | - libuv: 22.4Gbits/s+ 39 | - macOS: 29.9Gbits/s 40 | - Ubuntu 20.04 On Aliyun: 18.4Gbits/s 41 | - Android 10(MI MIX2S): 480Mbits/s 42 | - UDP speed: 43 | - Windows: 22.4Gbits/s 44 | - macOS: send=35.5Gbits/s, recv=25.8Gbits/s, lost=9.7Gbits/s 45 | - Ubuntu 20.04 On Aliyun: 20.8Gbits/s 46 | - Android 10(MI MIX2S): 488Mbits/s 47 | - KCP speed: 48 | - Windows: 11.0Gbits/s 49 | - macOS: 21.0Gbits/s 50 | - Ubuntu 20.04 On Aliyun: 2.3~5.3Gbits/s, because it's Single Core CPU, so speed not stable 51 | - Android 10(MI MIX2S): 184Mbits/s (kcp.send.internval=1ms) 52 | 53 | ## 注意事项 54 | - 多核CPU,当 ```io_service``` 任务饱和时可将 ```wait_duration``` 设置为**0**,以便事件循环在下次tick立刻执行任务 55 | - 单核CPU,当 ```io_service``` 任务饱和时至少要给一定的 ```wait_duration``` 到```socket.select```,详见[提交记录](https://github.com/yasio/yasio/commit/0a549fdd558a17b75da3923d36e63c3c77904041),以防止占满CPU降低整体传输性能,例如阿里云**单核CPU**服务器,最早测试用例里将 ```kcp.interval``` 设置成了**0**,传输性能很低,只有**40Mbits/s**,后来保持 ```kcp.interval=10ms```,同时将发包间隔降低为**100us**,传输性能提高到**1.9Gbit/s** 56 | - Android CPU相对PC比较弱,因此UDP/TCP传输速率均在480Mbits/s左右 57 | -------------------------------------------------------------------------------- /certs/ca-cer.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDUTCCAjmgAwIBAgIUG/1CGFbrAp6p3Z3iGTNHewUWZaQwDQYJKoZIhvcNAQEM 3 | BQAwNzELMAkGA1UEBhMCQ04xDjAMBgNVBAoMBXlhc2lvMRgwFgYDVQQDDA95YXNp 4 | by5naXRodWIuaW8wIBcNMjQwMTI0MTAyMjA0WhgPMzAyNDAxMjQxMDIyMDRaMDcx 5 | CzAJBgNVBAYTAkNOMQ4wDAYDVQQKDAV5YXNpbzEYMBYGA1UEAwwPeWFzaW8uZ2l0 6 | aHViLmlvMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvA1w5yYen1Ua 7 | l4+J7HF/EEX7djEQFt0PRRRUurMkqQIbkmVxoV3w962BZyQtDm7b1l6qI1Z6iH36 8 | g0fp3mXVbs0ixOpsuyN0IaPySGYU+9vP7ur78UjqtxCiY5IMJQ73Ahu6HEUNkkec 9 | qEyRLDAJRVPYEmqJR8hm7OGQKO+9ptd5JUB+7fN/7Kq4fbJWsnnp1oxkcJASdJnR 10 | Vq9e/LR9xY/x9XawGgIbg7hFVYZmbvCiN6+op8l42uNspCcigiLJ/J9eUzVG333w 11 | +nlmL6rGwwprsbqJAH4Pt4+qgqgeoCTUiRjn9TQoHywxSqw5mga6g3INNvWtYqCR 12 | MNOaLYG62wIDAQABo1MwUTAdBgNVHQ4EFgQU+Hv0GUZ9e+cWQpuAFothk0nB2Dww 13 | HwYDVR0jBBgwFoAU+Hv0GUZ9e+cWQpuAFothk0nB2DwwDwYDVR0TAQH/BAUwAwEB 14 | /zANBgkqhkiG9w0BAQwFAAOCAQEAn8X6858TfO6GzGQdDiKXuTmtMrlTRJGvNfOE 15 | ZX7Z+XDHsc8nuxUmdzlrW3Aqm79spean2YQHaCee1lGU/VasxD/1FNWxUfy2o/Xr 16 | Kn9XqoMEFI+zJ77CTyOqVVotre90alwwvEvKaTGjg6VNMeTa0DyGen51yLI95YUM 17 | hzFQWSfae8p+G+qwhd3sEaFVkKg0QJXh/8dbCIfWffiXfAcEo8Zv87Jwwk9ZVQbo 18 | H+YSk+UC05BJCx8AvEZ95bgWw5CWeHEAecF8Svfkf8g//rn9OUs8V3v8saPvf8vN 19 | cLyDsPlWmrCnINgz8IGERV3sLYO18RGIMnZEpuPCW0lGS7AReg== 20 | -----END CERTIFICATE----- 21 | -------------------------------------------------------------------------------- /certs/ca-cer.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDUTCCAjmgAwIBAgIUG/1CGFbrAp6p3Z3iGTNHewUWZaQwDQYJKoZIhvcNAQEM 3 | BQAwNzELMAkGA1UEBhMCQ04xDjAMBgNVBAoMBXlhc2lvMRgwFgYDVQQDDA95YXNp 4 | by5naXRodWIuaW8wIBcNMjQwMTI0MTAyMjA0WhgPMzAyNDAxMjQxMDIyMDRaMDcx 5 | CzAJBgNVBAYTAkNOMQ4wDAYDVQQKDAV5YXNpbzEYMBYGA1UEAwwPeWFzaW8uZ2l0 6 | aHViLmlvMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvA1w5yYen1Ua 7 | l4+J7HF/EEX7djEQFt0PRRRUurMkqQIbkmVxoV3w962BZyQtDm7b1l6qI1Z6iH36 8 | g0fp3mXVbs0ixOpsuyN0IaPySGYU+9vP7ur78UjqtxCiY5IMJQ73Ahu6HEUNkkec 9 | qEyRLDAJRVPYEmqJR8hm7OGQKO+9ptd5JUB+7fN/7Kq4fbJWsnnp1oxkcJASdJnR 10 | Vq9e/LR9xY/x9XawGgIbg7hFVYZmbvCiN6+op8l42uNspCcigiLJ/J9eUzVG333w 11 | +nlmL6rGwwprsbqJAH4Pt4+qgqgeoCTUiRjn9TQoHywxSqw5mga6g3INNvWtYqCR 12 | MNOaLYG62wIDAQABo1MwUTAdBgNVHQ4EFgQU+Hv0GUZ9e+cWQpuAFothk0nB2Dww 13 | HwYDVR0jBBgwFoAU+Hv0GUZ9e+cWQpuAFothk0nB2DwwDwYDVR0TAQH/BAUwAwEB 14 | /zANBgkqhkiG9w0BAQwFAAOCAQEAn8X6858TfO6GzGQdDiKXuTmtMrlTRJGvNfOE 15 | ZX7Z+XDHsc8nuxUmdzlrW3Aqm79spean2YQHaCee1lGU/VasxD/1FNWxUfy2o/Xr 16 | Kn9XqoMEFI+zJ77CTyOqVVotre90alwwvEvKaTGjg6VNMeTa0DyGen51yLI95YUM 17 | hzFQWSfae8p+G+qwhd3sEaFVkKg0QJXh/8dbCIfWffiXfAcEo8Zv87Jwwk9ZVQbo 18 | H+YSk+UC05BJCx8AvEZ95bgWw5CWeHEAecF8Svfkf8g//rn9OUs8V3v8saPvf8vN 19 | cLyDsPlWmrCnINgz8IGERV3sLYO18RGIMnZEpuPCW0lGS7AReg== 20 | -----END CERTIFICATE----- 21 | -------------------------------------------------------------------------------- /certs/ca-prk.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC8DXDnJh6fVRqX 3 | j4nscX8QRft2MRAW3Q9FFFS6sySpAhuSZXGhXfD3rYFnJC0ObtvWXqojVnqIffqD 4 | R+neZdVuzSLE6my7I3Qho/JIZhT728/u6vvxSOq3EKJjkgwlDvcCG7ocRQ2SR5yo 5 | TJEsMAlFU9gSaolHyGbs4ZAo772m13klQH7t83/sqrh9slayeenWjGRwkBJ0mdFW 6 | r178tH3Fj/H1drAaAhuDuEVVhmZu8KI3r6inyXja42ykJyKCIsn8n15TNUbfffD6 7 | eWYvqsbDCmuxuokAfg+3j6qCqB6gJNSJGOf1NCgfLDFKrDmaBrqDcg029a1ioJEw 8 | 05otgbrbAgMBAAECggEBALX2r5QLb8AvQk77hrMy04e0n/Eq4m2tNBRc6uvJYqTj 9 | NDjBTmWdmAihbECYYbzAippw+WK+UEz40cnscSFRGmhfuNAgIlwmnz3Z/RwPIyjd 10 | 9uMxn95G909ymh+M95F4XI0+tSSbsNkl0DGN/T9rr9zUl5SiX/oEsYtva+YgrTvd 11 | Q3XG4LOlJYEpEfSR/X/orDeEjVrqLLMkN4gwhBD3PO3jEtYCPoAoLPR7FSf1nBh9 12 | XtoZBZpTa5qAYPUedye2tOItdlsSk14gBVqgczoWY0Cck+5KkQtDXQbyrw3j+EbW 13 | RaL5IqullftakN9qxK5DNp6ApSlYTemOx+Oj1/KyFmkCgYEA8ZfcoQKjHZvwILq5 14 | SGkbuu7r/UHJ8blXLXcIUWo11or78ZxQus7ZFNnrLfY8KJgvTaIB0FNonYGCMde0 15 | +ZsxqV3ll35isF73iyDPGVaNQJzehujfBvL+VqPyuujcbseuT3P9kMSGvYMiudt2 16 | d7c1NWzvpSEzRqic9cu2K+r3cE8CgYEAx0Q7ZzEd3JRmsYbMj5GXZMbFbARcMW5N 17 | GududGPgGbLaf7VDDdkzK5koJzJbMTkh76LV+iEQskctcD26S0WE2fA7vASzVRsA 18 | 4ze0op86TTylQ9Ji9fcFEpwZBawWNRegSamOf6YaCe8gU5tkKki+FSqAyw29ftLM 19 | QFEY2LDLvbUCgYAQFWcXxQAs+XOsCiJJos24zS0iyB10nT0jhrgkC2kYJlqNhDWP 20 | qjOjgrp4bdslbLRBe9aZEuR1D+kl/lFLCLzupJSjWEOjsD7UoVOIQU3YDll2K8yl 21 | PsoV5IZFUTlTmrGNEpC/8YVy2mcWbnjdkXHWY7E0khhCzPjeGDjBhbwBWwKBgQCn 22 | 5DNwxI92dIr59KuSI4c9X8SjOCE9fMP2cRw9cJE21d0HUQAIQQK+LzMHo4P2Oz7+ 23 | m2JSd12L+DCuqzO1jANdZO3Pgt5eTHw49Yx6oFINFZXhSPgcaV6ayW7DurSTUy64 24 | IeZwYtD5ocLI7to8TkHpr4AIlbEdlBqH7kxS9tMTKQKBgDFPSCrIZ5U0oVeOqGav 25 | IpXFRRXYc+dcsyUzrEgHSfwccI+X9OttjNblI/qvUwu/AATlXxIJbQp703bAOb/O 26 | ME5qipBJgW1OmYGyiX5Xhl80hURkJCEm8s5l6C3AWhhas4ZPr4fxfdCTgg1Qjd34 27 | yT+ctCe9OXNlKbWHjl23GdTz 28 | -----END PRIVATE KEY----- 29 | -------------------------------------------------------------------------------- /certs/gen.sh: -------------------------------------------------------------------------------- 1 | # refer to: 2 | # - https://www.baeldung.com/openssl-self-signed-cert 3 | # - https://gist.github.com/Barakat/675c041fd94435b270a25b5881987a30 4 | # - https://stackoverflow.com/questions/18233835/creating-an-x509-v3-user-certificate-by-signing-csr 5 | # - https://certificatetools.com/ 6 | # cert settings 7 | is_v1=$1 8 | 9 | key_bits=2048 10 | server_host="127.0.0.1" 11 | hash_alg=-sha384 12 | valid_years=1000 13 | 14 | # compute valid_days 15 | time_ts=`date +%s` 16 | date_year=`date +%Y` 17 | date_ts=`date -d @$time_ts --iso-8601=seconds` 18 | date_expire_year=`expr $date_year + $valid_years` 19 | date_expire_ts=${date_ts/$date_year/$date_expire_year} 20 | time_expire_ts=`date -d $date_expire_ts +%s` 21 | valid_days=$((($time_expire_ts - $time_ts) / 86400)) 22 | v3ext_file=`pwd`/v3.ext 23 | org_name=simdsoft 24 | 25 | issuer_cn="global.simdsoft.com" 26 | issuer_subj="/C=CN/O=$org_name/CN=$issuer_cn" 27 | 28 | # Create Self-Signed Root CA(Certificate Authority) 29 | if [ ! -f "ca-prk.pem" ] ; then 30 | if [ "$is_v1" != 'true' ] ; then 31 | openssl req -newkey rsa:$key_bits $hash_alg -nodes -keyout ca-prk.pem -x509 -days $valid_days -out ca-cer.pem -subj "$issuer_subj"; cp ca-cer.pem ca-cer.crt 32 | else 33 | openssl genrsa -out ca-prk.pem $key_bits 34 | openssl req -new $hash_alg -key ca-prk.pem -out ca-csr.pem -subj "$issuer_subj" 35 | openssl x509 -req -signkey ca-prk.pem -in ca-csr.pem -out ca-cer.pem -days $valid_days 36 | fi 37 | fi 38 | 39 | # Server 40 | 41 | # 1. Generate unencrypted 2048-bits RSA private key for the server (CA) & Generate CSR for the server 42 | 43 | openssl req -newkey rsa:$key_bits $hash_alg -nodes -keyout server-prk.pem -out server-csr.pem -subj "/C=CN/O=$org_name/CN=$server_host" 44 | 45 | # 2. Sign with our RootCA 46 | if [ "$is_v1" != 'true' ] ; then 47 | # subjectAltName in extfile is important for browser visit 48 | openssl x509 -req $hash_alg -in server-csr.pem -CA ca-cer.pem -CAkey ca-prk.pem -CAcreateserial -out server-cer.pem -days $valid_days -extfile $v3ext_file; cp server-cer.pem server-cer.crt 49 | else 50 | openssl x509 -req $hash_alg -in server-csr.pem -CA ca-cer.pem -CAkey ca-prk.pem -CAcreateserial -out server-cer.pem -days $valid_days; cp server-cer.pem server-cer.crt 51 | fi 52 | 53 | # Check if the certificate is signed properly 54 | openssl x509 -in server-cer.pem -noout -text 55 | -------------------------------------------------------------------------------- /certs/server-cer.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDVDCCAjygAwIBAgIUXtnDHamyOPTBGJ+ImVE9WWp8I30wDQYJKoZIhvcNAQEM 3 | BQAwNzELMAkGA1UEBhMCQ04xDjAMBgNVBAoMBXlhc2lvMRgwFgYDVQQDDA95YXNp 4 | by5naXRodWIuaW8wIBcNMjQwMTI0MTAyMjA0WhgPMzAyNDAxMjQxMDIyMDRaMDEx 5 | CzAJBgNVBAYTAkNOMQ4wDAYDVQQKDAV5YXNpbzESMBAGA1UEAwwJMTI3LjAuMC4x 6 | MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5z71I819Smf6FqQaINXK 7 | UjNiZnIvy1aH7kAease8C1WX0lgeGUMYyJFPj7lmOvXT4X5bdCEarxMKAbEc5x8J 8 | H3iwRvY+bgRaKowdC/Ql0DwocKlZE3qPzLp/nIZVET/QpcgToiu7w66lo0WtEn4F 9 | PEmDqBT/aYUXVZNm5kUUtrbCoEqDMFf6ANWayZUbCMze+9h8vTk0/beR1WuzwBWj 10 | WVufD6pt4lwh59t2HXCwwHCZP1JqKLJDg+KJnRe0wVsroo1AQO1WpjKGAMd5G1zW 11 | RkueUK889fyLXumNP3PGRTGD5Dnox+ND8E8IL0QqiiolleyPzCBgjdwW2if1lhLL 12 | ywIDAQABo1wwWjAfBgNVHSMEGDAWgBT4e/QZRn175xZCm4AWi2GTScHYPDAJBgNV 13 | HRMEAjAAMAsGA1UdDwQEAwIE8DAfBgNVHREEGDAWggkxMjcuMC4wLjGCCWxvY2Fs 14 | aG9zdDANBgkqhkiG9w0BAQwFAAOCAQEAncJluamf9E8SBJK2OeTPhnpRBlceZKIR 15 | WJ6rUyi8bvhGv6YA8OuPHckxK75uLIySN4zklpFisGHh+FOihJu2dlyimo+BEXCR 16 | rvVM9Pt5xqmy9rE/7tWpKssqiqT5F8xk/kWmww+NIKmDib0f1d0VU/VIn2MvDCf0 17 | ixmTKNG7UFhj4X4rKzzhrrV+Rt8julVOC5SPUHXdJJWdYHt2sEPMAdHO+zwqzma4 18 | +Ml+qtne5K7DjX+Uui1Kzs27Xq+WM5VT3WNHCIvUOkPLIE8vEsGKwODajJgdmBr7 19 | Awt1otolnkP0UbgRhaBrpjVSzke3NKFA3SgL1YmOgngu3EiuYmFtPw== 20 | -----END CERTIFICATE----- 21 | -------------------------------------------------------------------------------- /certs/server-cer.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDVDCCAjygAwIBAgIUXtnDHamyOPTBGJ+ImVE9WWp8I30wDQYJKoZIhvcNAQEM 3 | BQAwNzELMAkGA1UEBhMCQ04xDjAMBgNVBAoMBXlhc2lvMRgwFgYDVQQDDA95YXNp 4 | by5naXRodWIuaW8wIBcNMjQwMTI0MTAyMjA0WhgPMzAyNDAxMjQxMDIyMDRaMDEx 5 | CzAJBgNVBAYTAkNOMQ4wDAYDVQQKDAV5YXNpbzESMBAGA1UEAwwJMTI3LjAuMC4x 6 | MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5z71I819Smf6FqQaINXK 7 | UjNiZnIvy1aH7kAease8C1WX0lgeGUMYyJFPj7lmOvXT4X5bdCEarxMKAbEc5x8J 8 | H3iwRvY+bgRaKowdC/Ql0DwocKlZE3qPzLp/nIZVET/QpcgToiu7w66lo0WtEn4F 9 | PEmDqBT/aYUXVZNm5kUUtrbCoEqDMFf6ANWayZUbCMze+9h8vTk0/beR1WuzwBWj 10 | WVufD6pt4lwh59t2HXCwwHCZP1JqKLJDg+KJnRe0wVsroo1AQO1WpjKGAMd5G1zW 11 | RkueUK889fyLXumNP3PGRTGD5Dnox+ND8E8IL0QqiiolleyPzCBgjdwW2if1lhLL 12 | ywIDAQABo1wwWjAfBgNVHSMEGDAWgBT4e/QZRn175xZCm4AWi2GTScHYPDAJBgNV 13 | HRMEAjAAMAsGA1UdDwQEAwIE8DAfBgNVHREEGDAWggkxMjcuMC4wLjGCCWxvY2Fs 14 | aG9zdDANBgkqhkiG9w0BAQwFAAOCAQEAncJluamf9E8SBJK2OeTPhnpRBlceZKIR 15 | WJ6rUyi8bvhGv6YA8OuPHckxK75uLIySN4zklpFisGHh+FOihJu2dlyimo+BEXCR 16 | rvVM9Pt5xqmy9rE/7tWpKssqiqT5F8xk/kWmww+NIKmDib0f1d0VU/VIn2MvDCf0 17 | ixmTKNG7UFhj4X4rKzzhrrV+Rt8julVOC5SPUHXdJJWdYHt2sEPMAdHO+zwqzma4 18 | +Ml+qtne5K7DjX+Uui1Kzs27Xq+WM5VT3WNHCIvUOkPLIE8vEsGKwODajJgdmBr7 19 | Awt1otolnkP0UbgRhaBrpjVSzke3NKFA3SgL1YmOgngu3EiuYmFtPw== 20 | -----END CERTIFICATE----- 21 | -------------------------------------------------------------------------------- /certs/server-csr.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE REQUEST----- 2 | MIICdjCCAV4CAQAwMTELMAkGA1UEBhMCQ04xDjAMBgNVBAoMBXlhc2lvMRIwEAYD 3 | VQQDDAkxMjcuMC4wLjEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDn 4 | PvUjzX1KZ/oWpBog1cpSM2Jmci/LVofuQB5qx7wLVZfSWB4ZQxjIkU+PuWY69dPh 5 | flt0IRqvEwoBsRznHwkfeLBG9j5uBFoqjB0L9CXQPChwqVkTeo/Mun+chlURP9Cl 6 | yBOiK7vDrqWjRa0SfgU8SYOoFP9phRdVk2bmRRS2tsKgSoMwV/oA1ZrJlRsIzN77 7 | 2Hy9OTT9t5HVa7PAFaNZW58Pqm3iXCHn23YdcLDAcJk/UmooskOD4omdF7TBWyui 8 | jUBA7VamMoYAx3kbXNZGS55Qrzz1/Ite6Y0/c8ZFMYPkOejH40PwTwgvRCqKKiWV 9 | 7I/MIGCN3BbaJ/WWEsvLAgMBAAGgADANBgkqhkiG9w0BAQwFAAOCAQEAG68bdd7o 10 | s3RGmDUZ9QUNOHLbPtbYFJlHPHWFEJ+c3WmYle2MhCbzgAm/F50r5U+tf6GYZT6t 11 | 1a2X1kqfGgTXZ2W9e+I8UVHB4eNvbJlrQMG4s8/bqVROeGOd8iqv4S3rt0cwh7gg 12 | EsRZJqXwxzW+2hkUqxIqnn2XxNi5NhwMtp5XPqpXyM1UwC38agqv1nKkoYZduY2m 13 | s0GEUTHhHv4F44TmxS1R6QrwgrS3YzHw1siSgUV9RqUmgmdNNafI/4vJE/fBMDAB 14 | iARqVyIcadcPKyN+nXAPmYBho5ycwnS/Cx++h2YCvFX6V4nLhnRp1H48xKnK8H53 15 | JBqCPZqbWc2gCQ== 16 | -----END CERTIFICATE REQUEST----- 17 | -------------------------------------------------------------------------------- /certs/server-prk.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDnPvUjzX1KZ/oW 3 | pBog1cpSM2Jmci/LVofuQB5qx7wLVZfSWB4ZQxjIkU+PuWY69dPhflt0IRqvEwoB 4 | sRznHwkfeLBG9j5uBFoqjB0L9CXQPChwqVkTeo/Mun+chlURP9ClyBOiK7vDrqWj 5 | Ra0SfgU8SYOoFP9phRdVk2bmRRS2tsKgSoMwV/oA1ZrJlRsIzN772Hy9OTT9t5HV 6 | a7PAFaNZW58Pqm3iXCHn23YdcLDAcJk/UmooskOD4omdF7TBWyuijUBA7VamMoYA 7 | x3kbXNZGS55Qrzz1/Ite6Y0/c8ZFMYPkOejH40PwTwgvRCqKKiWV7I/MIGCN3Bba 8 | J/WWEsvLAgMBAAECggEAZLTRU2dBQi8oBcYvrs8MTmIcX1spH1eu2P5JgN09Mn5z 9 | IOLJMN08pNRLnt7x+4llXdWGhHuKQGZ9PCFi4fBtK6yGsFC6/XSdw9vDJpqMATTB 10 | s9a8eTQt/c3Wl1cVIu70sc4BZuW+3shnUESey+ff5dJqKMAEP3L7p4QLEwtQqwT2 11 | qrTY4mxX5Aw8ypmDy8G6MwBbWbPurtSfKCahwNTn9L/SutdtMNQNvdFHDWSGpOYE 12 | XWWv8ZA5gZRd7kf6g95lNIU7y+rkIELo6nR/sfesX1Id0JzfjQIxFvhH7bti8WJh 13 | CL9tGoLoaTGIBrfhTsKwlVpk6lo8Rdr5QmLymxwfCQKBgQD2kTRfYU7VUP3FD/JG 14 | r1BcpxXyIRy+wQ7qdjJbGLrzaRZzrSqWVjOP+LmzJv3wESpyF3fuJw54X+vktEey 15 | XcDscLROR7bj0KzdBjztMFZh3uneZArYHjG+Sifa38GzsdNXoY4R1sV9EwEcZ3ze 16 | l5/pkFStatd5ia/A0La3ggw+nQKBgQDwF7Oc7l+P58j5SCsglFAegumJtA6uYSc2 17 | 3CUVvuS2b4OlptiRibCNZYw47Jp8ylH9is4addRz5Tj6eR/d+VvmGdT+6kpHpPFU 18 | ONuhRThAJ/+jt7Kb8/MuX1N/bTgG2sDu0V9pUQlfLO/EAdSNrfV0EnuVPDQK5xUs 19 | +JYydk6zhwKBgQDWIQZdqvE+mia5A/9A2bGttUF+1LjVBG6CugFDUbfR+jqQXRu2 20 | EciXyMbkygEQgqfdC3qQ7YRIj+0Z4mK9iWQpMju0G929/RSSon848ZijSGbMRw+P 21 | 3rEOc/Imx9m9x7olyVzLKzy5QU7erxUnboBm43xWWookt6lVhyyXM66UlQKBgQDt 22 | Z1JYU7C0mAm2zLCwZ1cNxH7uhdeagECJU4dsCDUZXAz9qIwu5MpqFkZgJzzfNiN6 23 | pF0F9wsbikYcDdb/48kGLvbZFYxbaXKjyBEMV2i2r5ZtKYB4CvGkIehrcPDcfkQW 24 | IXvJpLKypLl0xCaL7b5uhrQircP8H+FldWz2+tr5UwKBgQCR05VPH9M5eSouE++Y 25 | F2K8F9naor9e6vfmhOzDfn4RFr3dZicCsfr/c73dThsvO83Asiz1D9EemCnEGTDf 26 | KKaJwXtus4odvtebESQhdMRzAaImr4WWpOhwQ1ZviGroYnikJCr7n+YCt4EiyLfw 27 | EkIkyfuFIeWkMMTrpnCyrUYLkQ== 28 | -----END PRIVATE KEY----- 29 | -------------------------------------------------------------------------------- /certs/sslcerts.hpp.in: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // the cacert.pem in certs/ is download from https://curl.se/ca/cacert.pem and append content of server.crt to it 4 | #define SSLTEST_CACERT R"(@SSLTEST_CACERT@)" 5 | #define SSLTEST_CERT R"(@SSLTEST_CERT@)" 6 | #define SSLTEST_PKEY R"(@SSLTEST_PKEY@)" 7 | -------------------------------------------------------------------------------- /certs/v3.ext: -------------------------------------------------------------------------------- 1 | authorityKeyIdentifier=keyid,issuer 2 | basicConstraints=CA:FALSE 3 | keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment 4 | subjectAltName = @alt_names 5 | [alt_names] 6 | DNS.1 = 127.0.0.1 7 | DNS.2 = localhost -------------------------------------------------------------------------------- /docs/api/reference/io_channel-class.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "yasio::inet::io_channel Class" 3 | date: "1/5/2021" 4 | f1_keywords: ["io_channel", "yasio/io_channel", ] 5 | helpviewer_keywords: [] 6 | --- 7 | 8 | # io_channel Class 9 | 10 | 负责管理 TCP/SSL/UDP/KCP 连接和传输会话。 11 | 12 | 13 | ## 语法 14 | 15 | ```cpp 16 | namespace yasio { inline namespace inet { class io_channel; } } 17 | ``` 18 | 19 | ## 成员 20 | 21 | ### 公共方法 22 | 23 | |Name|Description| 24 | |----------|-----------------| 25 | |[io_channel::get_service](#get_service)|获取管理信道的io_service| 26 | |[io_channel::index](#index)|获取信道索引| 27 | |[io_channel::remote_port](#remote_port)|获取信道远程端口| 28 | |[io_channel::bytes_transferred](#bytes_transferred)|获取传输字节数| 29 | |[io_channel::connect_id](#bytes_transferred)|获取连接ID| 30 | 31 | ## 要求 32 | 33 | **头文件:** yasio/yasio.hpp 34 | 35 | ## 注意 36 | 37 | 当io_service对象构造后,最大信道数量不可改变,
38 | 信道句柄可通过 `io_service::channel_at` 获取。 39 | 40 | 41 | ## io_channel::get_service 42 | 43 | 获取管理信道的io_service对象。 44 | 45 | ```cpp 46 | io_service& get_service() 47 | ``` 48 | 49 | ## io_channel::index 50 | 51 | 获取信道索引。 52 | 53 | ```cpp 54 | int index() const 55 | ``` 56 | 57 | ## io_channel::remote_port 58 | 59 | 获取信道远程端口. 60 | 61 | ```cpp 62 | u_short remote_port() const; 63 | ``` 64 | 65 | ### 返回值 66 | 67 | 返回信道远程端口号 68 | 69 | - 对于客户端信道表示通信的远端端口 70 | - 对于服务端信道表示监听端口 71 | 72 | ## io_channel::bytes_transferred 73 | 74 | 获取客户端接收总字节数 75 | 76 | ```cpp 77 | long long bytes_transferred() const; 78 | ``` 79 | 80 | ### 返回值 81 | 82 | 从连接建立开始到当前,接收总字节数,用于统计客户端接收流量 83 | 84 | ## io_channel::connect_id 85 | 86 | 获取客户端信道递增的实时连接id 87 | 88 | ```cpp 89 | unsigned int connect_id() const; 90 | ``` 91 | 92 | ### 返回值 93 | 94 | 客户端信道当前连接id 95 | 96 | 97 | ## 请参阅 98 | 99 | [io_service Class](./io_service-class.md) 100 | 101 | [io_event Class](./io_event-class.md) 102 | -------------------------------------------------------------------------------- /docs/api/reference/io_event-class.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "yasio::inet::io_event Class" 3 | date: "1/5/2021" 4 | f1_keywords: ["io_event", "yasio/io_event", ] 5 | helpviewer_keywords: [] 6 | --- 7 | 8 | # io_event Class 9 | 10 | 网络事件由 io_service 线程产生。 11 | 12 | 13 | ## 语法 14 | 15 | ```cpp 16 | namespace yasio { inline namespace inet { class io_event; } } 17 | ``` 18 | 19 | ## 成员 20 | 21 | ### 公共方法 22 | 23 | |Name|Description| 24 | |----------|-----------------| 25 | |[io_event::kind](#kind)|获取事件类型| 26 | |[io_event::status](#status)|获取事件状态| 27 | |[io_event::passive](#passive)|检查是否是被动事件| 28 | |[io_event::packet](#packet)|获取事件消息包| 29 | |[io_event::packet_view](#packet_view)|获取事件消息包view| 30 | |[io_event::timestamp](#timestamp)|获取事件时间戳| 31 | |[io_event::transport](#transport)|获取事件传输会话| 32 | |[io_event::transport_id](#transport_id)|获取事件传输会话ID| 33 | |[io_event::transport_ud](#transport_ud)|设置或获取事件传输会话用户数据| 34 | 35 | ## 要求 36 | 37 | **头文件:** yasio/yasio.hpp 38 | 39 | 40 | ## io_event::kind 41 | 42 | 获取事件类型。 43 | 44 | ```cpp 45 | int kind() const; 46 | ``` 47 | 48 | ### 返回值 49 | 50 | 事件类型,可以是以下值: 51 | 52 | * `YEK_ON_PACKET`: 消息事件 53 | * `YEK_ON_OPEN`: 打开事件,对于客户端信道,代表连接响应 54 | * `YEK_ON_CLOSE`: 关闭事件,对于客户端信道,代表连接丢失 55 | 56 | ## io_event::status 57 | 58 | 获取事件状态。 59 | 60 | ```cpp 61 | int status() const; 62 | ``` 63 | 64 | ### 返回值 65 | 66 | - 0: 正常 67 | - 非0: 出错, 用户只需要简单打印即可。 68 | 69 | ## io_event::passive 70 | 71 | 检查是否是被动事件 72 | 73 | ```cpp 74 | int passive() const 75 | ``` 76 | 77 | ### 返回值 78 | 79 | - 0: 非被动事件,包括客户端信道的连接打开、关闭事件和传输会话的消息事件。 80 | - 1: open或close服务器信道时产生,仅当打开编译配置`YASIO_ENABLE_PASSIVE_EVENT`才会产生。 81 | 且为保持兼容,此行为默认是关闭的。 82 | 83 | ## io_event::packet 84 | 85 | 获取事件携带的消息包 86 | 87 | ```cpp 88 | yasio::sbyte_buffer& packet() 89 | ``` 90 | 91 | ## 返回值 92 | 93 | 消息数据的view。 94 | 95 | ## io_event::packet_view 96 | 97 | 获取事件携带的消息数据view,仅当io_service设置`YOPT_S_FORWARD_PACKET`时有效。此数据在事件回调结束后会失效,业务应及时保存。 98 | 99 | ```cpp 100 | packet_view_t packet_view() 101 | ``` 102 | 103 | ## 返回值 104 | 105 | 消息包的引用, 用户可以使用`std::move`无GC方式从事件取走消息包。 106 | 107 | ## io_event::timestamp 108 | 109 | 获取事件产生的微秒级时间戳。 110 | 111 | ```cpp 112 | highp_time_t timestamp() const; 113 | ``` 114 | 115 | ### 返回值 116 | 117 | 和系统时间无关的微秒级时间戳。 118 | 119 | ## io_event::transport 120 | 121 | 获取事件的传输会话句柄。 122 | 123 | ```cpp 124 | transport_handle_t transport() const; 125 | ``` 126 | 127 | ### 返回值 128 | 129 | 返回句柄,当收到断开事件时,传输会话句柄已失效,仅可用作地址值比较。 130 | 131 | ## io_event::transport_id 132 | 133 | 获取事件的传输会话ID。 134 | 135 | ```cpp 136 | unsigned int transport_id() const; 137 | ``` 138 | 139 | ### 返回值 140 | 141 | 32位无符号整数范围内的唯一ID。 142 | 143 | ## io_event::transport_ud 144 | 145 | 设置或获取传输会话用户数据。 146 | 147 | ```cpp 148 | template 149 | _Uty io_event::transport_ud(); 150 | 151 | template 152 | void io_event::transport_ud(_Uty uservalue); 153 | ``` 154 | 155 | ### 注意 156 | 157 | 用户需要自己管理 userdata 的内存, 例如: 158 | 159 | * 收到连接建立成功事件时存储userdata 160 | * 收到连接丢失事件时清理userdata 161 | 162 | ## 请参阅 163 | 164 | [io_service Class](./io_service-class.md) 165 | 166 | [io_channel Class](./io_channel-class.md) 167 | -------------------------------------------------------------------------------- /docs/api/reference/object_pool-class.md: -------------------------------------------------------------------------------- 1 | # object_pool Class template 2 | 3 | 对象池类模板。 4 | 5 | 6 | ## 语法 7 | 8 | ```cpp 9 | namespace yasio { 10 | template 11 | class object_pool; 12 | } 13 | ``` 14 | 15 | ## 成员 16 | 17 | ### 公共构造函数 18 | 19 | |Name|Description| 20 | |----------|-----------------| 21 | |[object_pool::object_pool](#object_pool)|构造1个`object_pool` 对象| 22 | 23 | ### 公共方法 24 | 25 | |Name|Description| 26 | |----------|-----------------| 27 | |[object_pool::create](#create)|从对象池创建1个对象| 28 | |[object_pool::destroy](#destroy)|销毁对象并回收到对象池| 29 | 30 | ## 要求 31 | 32 | **头文件:** yasio/yasio.hpp 33 | 34 | ## object_pool::object_pool 35 | 36 | 构造 `object_pool` 对象。 37 | 38 | ```cpp 39 | object_pool(size_t _ElemCount = 128); 40 | ``` 41 | 42 | ### 参数 43 | 44 | *_ElemCount*
45 | 单个chunk允许分配最大对象数量。 46 | 47 | ## object_pool::create 48 | 49 | 创建1个对象。 50 | 51 | ```cpp 52 | template 53 | _Ty* create(_Types&&... args); 54 | ``` 55 | 56 | ### 参数 57 | 58 | *args*
59 | 构造对象所需参数,必须和对象类型构造函数匹配,否则编译报错。 60 | 61 | ## object_pool::destroy 62 | 63 | 销毁对象,并将对象的内存块放回对象池中。 64 | 65 | ```cpp 66 | void destroy(void* _Ptr); 67 | ``` 68 | 69 | ### 参数 70 | 71 | *_Ptr*
72 | 要销毁的对象地址。 73 | 74 | ## 示例 75 | 76 | ```cpp 77 | #include "yasio/object_pool.hpp" 78 | 79 | int main() { 80 | // 非线程安全版本 81 | yasio::object_pool pool(128); 82 | auto value1 = pool.create(2023); 83 | auto value2 = pool.create(2024); 84 | auto value3 = pool.create(2025); 85 | pool.destroy(value3); 86 | pool.destroy(value1); 87 | pool.destroy(value2); 88 | 89 | // 线程安全版本 90 | yasio::object_pool tsf_pool(128); 91 | value1 = tsf_pool.create(2023); 92 | value2 = tsf_pool.create(2024); 93 | value3 = tsf_pool.create(2025); 94 | tsf_pool.destroy(value3); 95 | tsf_pool.destroy(value1); 96 | tsf_pool.destroy(value2); 97 | 98 | return 0; 99 | } 100 | ``` 101 | -------------------------------------------------------------------------------- /docs/api/reference/singleton-class.md: -------------------------------------------------------------------------------- 1 | # singleton Class template 2 | 3 | 单例类模板。 4 | 5 | 6 | ## 语法 7 | 8 | ```cpp 9 | namespace yasio { 10 | template 11 | class singleton; 12 | } 13 | ``` 14 | 15 | ## 成员 16 | 17 | ### 静态方法 18 | 19 | |Name|Description| 20 | |----------|-----------------| 21 | |[singleton::instance](#instance)|获取单例指针| 22 | |[singleton::instance1](#instance1)|获取单例指针| 23 | |[singleton::destroy](#destroy)|销毁单例| 24 | 25 | ## 要求 26 | 27 | **头文件:** yasio/yasio.hpp 28 | 29 | ## singleton::instance 30 | 31 | 创建或获取单例对象。 32 | 33 | ```cpp 34 | template 35 | static pointer instance(_Types&&... args); 36 | ``` 37 | 38 | ### 参数 39 | 40 | *args*
41 | 构造单例对象所需参数。 42 | 43 | ## singleton::instance1 44 | 45 | 创建或获取单例对象,使用二段式构造模式。 46 | 47 | ```cpp 48 | template 49 | static pointer instance1(_Types&&... args); 50 | ``` 51 | 52 | ### 参数 53 | 54 | *args*
55 | 构造单例对象所需参数。 56 | 57 | ## singleton::destroy 58 | 59 | 销毁单例对象。 60 | 61 | ```cpp 62 | static void destroy(void); 63 | ``` 64 | 65 | ## 示例 66 | 67 | ```cpp 68 | #include "yasio/singleton.hpp" 69 | 70 | class FruitManager { 71 | public: 72 | FruitManager(int maxCount) : _maxCount(maxCount) { 73 | } 74 | 75 | void print() { 76 | printf("FruitManager: maxCount=%d\n", _maxCount); 77 | } 78 | 79 | private: 80 | int _maxCount; 81 | }; 82 | 83 | class FruitManager1 { 84 | public: 85 | void init(int maxCount){ 86 | _maxCount = maxCount; 87 | } 88 | 89 | void print() { 90 | printf("FruitManager1: maxCount=%d\n", _maxCount); 91 | } 92 | 93 | private: 94 | int _maxCount; 95 | }; 96 | 97 | int main() { 98 | yasio::singleton::instance(100)->print(); 99 | yasio::singleton::instance1(&FruitManager1::init, 100)->print(); 100 | 101 | yasio::singleton::destroy(); 102 | yasio::singleton::destroy(); 103 | return 0; 104 | } 105 | 106 | ``` 107 | -------------------------------------------------------------------------------- /docs/assets/images/framework.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simdsoft/yasio/492fa064f2e7f63cc19fd424b2fce54d89a7e7b5/docs/assets/images/framework.png -------------------------------------------------------------------------------- /docs/assets/images/framework_en.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simdsoft/yasio/492fa064f2e7f63cc19fd424b2fce54d89a7e7b5/docs/assets/images/framework_en.png -------------------------------------------------------------------------------- /docs/assets/images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simdsoft/yasio/492fa064f2e7f63cc19fd424b2fce54d89a7e7b5/docs/assets/images/logo.png -------------------------------------------------------------------------------- /docs/assets/stylesheets/extra.css: -------------------------------------------------------------------------------- 1 | @page { 2 | size: a4 portrait; 3 | margin: 25mm 10mm 25mm 10mm; 4 | counter-increment: page; 5 | font-family: "Microsoft YaHei", "Hiragino Sans GB", "WenQuanYi Micro Hei Mono", "Material Icons", "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif; 6 | white-space: pre; 7 | color: grey; 8 | @top-left { 9 | content: '© 2021 yasio.org'; 10 | } 11 | } 12 | 13 | body,input{ 14 | font-family: "Microsoft YaHei", "Hiragino Sans GB", "WenQuanYi Micro Hei Mono", "Material Icons", "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif; 15 | } 16 | -------------------------------------------------------------------------------- /docs/interop.md: -------------------------------------------------------------------------------- 1 | # yasio Interop 2 | 为了支持Unity C#, yasio提供了C语言接口导出,详见: https://github.com/yasio/yasio/blob/dev/yasio/bindings/yasio_ni.cpp 3 | 完整demo,请查看: https://github.com/yasio/yasio_unity 4 | -------------------------------------------------------------------------------- /docs/preprocessor.md: -------------------------------------------------------------------------------- 1 | # yasio 宏定义 2 | 3 | 以下宏定义可以控制 `yasio` 库的某些行为,可以在 [yasio/config.hpp](https://github.com/yasio/yasio/blob/dev/yasio/config.hpp) 定义或者在编译器预处理器定义 4 | 5 | |Name|Description| 6 | |----------|-----------------| 7 | |*YASIO_HEADER_ONLY*|是否以仅头文件的方式使用yasio核心组件,默认关闭。| 8 | |*YASIO_SSL_BACKEND*|选择SSL库以支持SSL客户端,需要软件编译系统包含OpenSSL/MbedTLS库,
3.36.0新增(同时移除YASIO_HAVE_SSL),此宏只能取值 `1`(使用OpenSSL) 或者 `2` (使用mbedtls)。| 9 | |*YASIO_ENABLE_UDS*|是否启用unix domain socket支持,目前仅类unix系统和win10 RS5+支持,默认关闭。| 10 | |*YASIO_USE_CARES*|是否启用c-ares异步域名解析库,
当编译系统包含c-ares时可启用,有效避免每次解析域名都新开线程。
yasio有DNS缓存机制,超时时间默认10分钟,
因此无c-ares也不会造成太大的性能损耗。| 11 | |*YASIO_VERBOSE_LOG*|是否打印详细日志,默认关闭。| 12 | |*YASIO_NT_COMPAT_GAI*|是否启用Windows XP系统下使用 `getaddrinfo` API支持。| 13 | |*YASIO_USE_SPSC_QUEUE*|是否使用SPSC(单生产者单消费者)队列,
仅当只有一个线程调用io_service::write时放可启用,默认关闭。| 14 | |*YASIO_USE_SHARED_PACKET*|是否使用 `std::shared_ptr` 包装网络包,使其能在多线程之间共享,默认关闭。| 15 | |*YASIO_ENABLE_HALF_FLOAT*|是否启用半精度浮点数支持,依赖 [half.hpp](https://github.com/yasio/thirdparty/blob/master/half/half.hpp)。| 16 | |*YASIO_DISABLE_OBJECT_POOL*|是否禁用对象池的使用,默认启用。| 17 | |*YASIO_DISABLE_CONCURRENT_SINGLETON*|是否禁用并发单利类模板。| 18 | |*YASIO_ENABLE_PASSIVE_EVENT*|是否启用服务端信道open/close事件产生,默认关闭。| 19 | |*YASIO_DISABLE_POLL*|是否禁用`poll`,默认启用。自3.39.6,底层多路io复用模型使用`poll`,如需继续使用`select`模型,定义此预处理器即可| 20 | |*YASIO_ENABLE_HPERF_IO*|是否启用各平台高性能io服用模型(epoll,kqueue...),默认禁用| 21 | -------------------------------------------------------------------------------- /docs/prerequisites.txt: -------------------------------------------------------------------------------- 1 | setuptools==69.* 2 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | mkdocs-material==9.* 2 | cffi==1.16.0 3 | pytest-runner==6.0.1 4 | WeasyPrint==60.2 5 | pydyf==0.10.0 6 | mkdocs-pdf-export-plugin==0.5.10 7 | mkdocs-minify-plugin==0.8.0 8 | mike>=2.0.0 9 | Pillow==10.3.0 10 | mkdocs-git-revision-date-localized-plugin 11 | mkdocs-redirects>=1.2.1 12 | jieba>=0.42.1 13 | -------------------------------------------------------------------------------- /docs/unpacking.md: -------------------------------------------------------------------------------- 1 | # yasio 粘包处理 2 | 3 | yasio的粘包处理不仅针对TCP,对于UDP,如果发送端有组包发送机制,也是以相同的方式处理。整体来讲有两种方式:
4 | 5 | - 通过io_service选项 [YOPT_C_UNPACK_PARAMS](#lfbfd_params) 设置信道参数。 6 | - 通过io_service选项 `YOPT_C_UNPACK_FN` 设置自定义包长度解码函数 [decode_len_fn_t](#decode_len_fn_t) 。 7 | 8 | !!! attention "注意" 9 | 10 | 自定义解码包长度函数实现时,当从字节流中读取int值时,一定不要使用指针强转,否则可能触发ARM芯片字节对齐问题 `SIGBUS` 异常闪退。可以参考内置解码包长度函数实现 `io_channel::__builtin_decode_len`。 11 | 12 | ## YOPT_C_UNPACK_PARAMS 13 | 14 | 设置信道拆包参数。 15 | 16 | ### 参数 17 | 18 | *max_frame_length*
19 | 最大包长度,超过将视为异常包。 20 | 21 | *length_field_offset*
22 | 包长度字段相对于消息包数据首字节偏移。 23 | 24 | *length_field_length*
25 | 包长度字段大小,支持1~4字节整数(`uint8_t,uint16_t,uint24_t,int32_t`)。 26 | 27 | *length_adjustment*
28 | 包长度调整值。通常应用层二进制协议都会设计消息头和消息体,当长度字段值包含消息头时,则此值为 `0`,否则为 `消息头长度`。 29 | 30 | ### 注意 31 | 32 | 消息包长度字段必须使用网络字节序编码。请查看内置解码包长度实现: 33 | 34 | ```cpp 35 | int io_channel::__builtin_decode_len(void* d, int n) 36 | { 37 | int loffset = uparams_.length_field_offset; 38 | int lsize = uparams_.length_field_length; 39 | if (loffset >= 0) 40 | { 41 | int len = 0; 42 | if (n >= (loffset + lsize)) 43 | { 44 | ::memcpy(&len, (uint8_t*)d + loffset, lsize); 45 | len = yasio::network_to_host(len, lsize); 46 | len += uparams_.length_adjustment; 47 | if (len > uparams_.max_frame_length) 48 | len = -1; 49 | } 50 | return len; 51 | } 52 | return n; 53 | } 54 | ``` 55 | 56 | ## decode_len_fn_t 57 | 58 | 信道解码消息包长度函数原型。 59 | 60 | ```cpp 61 | typedef std::function decode_len_fn_t; 62 | ``` 63 | 64 | ### 参数 65 | 66 | *d*
67 | 待解包数据首字节地址。 68 | 69 | *n*
70 | 待解包数据长度。 71 | 72 | ### 返回值 73 | 74 | 返回消息包数据实际长度。 75 | 76 | - `> 0`: 解码包长度成功。 77 | - `== 0`: 接收数据不足以解码消息包实际长度,yasio底层会继续接收数据,一旦收到新数据,会再次调用此函数。 78 | - `< 0`: 解码包长度异常,会触发当前传输会话断开。 79 | 80 | ## 注意 81 | 82 | 解码消息包长度函数必须是线程安全的,例如对于Lua则不支持设置自定义解码消息包长度函数。 83 | -------------------------------------------------------------------------------- /examples/lua/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(target_name example_lua) 2 | 3 | set (EXAMPLE_LUA_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | 5 | set (EXAMPLE_LUA_SRC ${EXAMPLE_LUA_SRC_DIR}/main.cpp) 6 | 7 | if (NOT MSVC) 8 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fpermissive") 9 | endif() 10 | 11 | set (EXAMPLE_LUA_INC_DIR ${EXAMPLE_LUA_SRC_DIR}/../../) 12 | 13 | include_directories ( 14 | "${EXAMPLE_LUA_SRC_DIR}" 15 | "${EXAMPLE_LUA_INC_DIR}" 16 | ${LUA_SRC_PATH} 17 | ) 18 | 19 | add_executable (${target_name} 20 | ${EXAMPLE_LUA_SRC} 21 | ${LUA_SRC_FILES} 22 | ) 23 | 24 | if (MSVC) 25 | set_target_properties(${target_name} PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY "$") 26 | endif () 27 | 28 | add_custom_command(TARGET ${target_name} 29 | COMMAND ${CMAKE_COMMAND} -E copy_directory 30 | ${CMAKE_CURRENT_SOURCE_DIR}/scripts 31 | $/scripts/ 32 | ) 33 | 34 | if(MSVC) 35 | add_custom_command(TARGET ${target_name} 36 | COMMAND ${CMAKE_COMMAND} -E copy 37 | ${CMAKE_CURRENT_SOURCE_DIR}/example_lua.xsxproj 38 | $/example_lua.xsxproj 39 | ) 40 | endif() 41 | 42 | yasio_config_app_depends(${target_name}) 43 | -------------------------------------------------------------------------------- /examples/lua/example_lua.xsxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | example_lua.exe 12 | . 13 | 14 | 15 | . 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /examples/lua/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "yasio/bindings/lyasio.hpp" 3 | #include "yasio/string_view.hpp" 4 | #if YASIO__HAS_CXX14 5 | # if YASIO__HAS_CXX17 // use sol2-3.x 6 | # include "sol/sol.hpp" 7 | # else 8 | # include "sol2/sol.hpp" // use sol2-2.x 9 | # endif 10 | #else 11 | # include "kaguya/kaguya.hpp" 12 | #endif 13 | 14 | #if defined(_WIN32) 15 | # include 16 | # include "yasio/wtimer_hres.hpp" 17 | #endif 18 | 19 | int main(int argc, char** argv) 20 | { 21 | #if defined(_WIN32) 22 | SetConsoleOutputCP(CP_UTF8); 23 | #endif 24 | 25 | #if defined(_WIN32) 26 | yasio::wtimer_hres whres; 27 | #endif 28 | 29 | #if YASIO__HAS_CXX14 30 | sol::state s; 31 | s.open_libraries(); 32 | luaregister_yasio(s.lua_state()); 33 | 34 | cxx17::string_view path = argv[0]; 35 | auto pos = path.find_last_of("/\\"); 36 | if (pos != cxx17::string_view::npos) 37 | path.remove_suffix(path.size() - pos - 1); 38 | std::string package_path = s["package"]["path"]; 39 | package_path.push_back(';'); 40 | package_path.append(path.data(), path.length()); 41 | package_path.append("scripts/?.lua;./scripts/?.lua"); 42 | s["package"]["path"] = package_path; 43 | 44 | std::string new_package_path = s["package"]["path"]; 45 | 46 | sol::function function = s.script_file("scripts/example.lua"); 47 | 48 | do 49 | { 50 | std::this_thread::sleep_for(std::chrono::milliseconds(16)); 51 | } while (!function.call(50.0 / 1000)); 52 | #else 53 | kaguya::State s; 54 | s.openlibs(); 55 | luaregister_yasio(s.state()); 56 | 57 | cxx17::string_view path = argv[0]; 58 | auto pos = path.find_last_of("/\\"); 59 | if (pos != cxx17::string_view::npos) 60 | path.remove_suffix(path.size() - pos - 1); 61 | std::string package_path = s["package"]["path"]; 62 | package_path.push_back(';'); 63 | package_path.append(path.data(), path.length()); 64 | package_path.append("scripts/?.lua;./scripts/?.lua"); 65 | s["package"]["path"] = package_path; 66 | 67 | auto function = s.loadfile("scripts/example.lua"); 68 | auto update = function(); 69 | do 70 | { 71 | std::this_thread::sleep_for(std::chrono::milliseconds(50)); 72 | } while (!update(50.0 / 1000)); 73 | #endif 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /examples/lua/scripts/protocol_base.lua: -------------------------------------------------------------------------------- 1 | -- This file is generated by x-studio 10.0.9000.1 © 2020, All rights reserved. 2 | -- Module: protocol_base, 3 | -- Author: halx99 4 | -- Create Date: [2020-01-02 22:50:31] 5 | local proto = require 'protocol_enums' 6 | local yasio = require 'yasio' 7 | local obstream = yasio.obstream 8 | 9 | proto.begin_encode = function (id) 10 | local obs = obstream.new() 11 | local where = obs:push32() -- alloc length field 12 | obs:write_u16(id) -- command_id 13 | obs:write_u16(1) -- version 14 | obs:write_i32(0) -- reserved 15 | obs:write_i32(0) -- reserved2 low 16 | obs:write_i32(0) -- reserved2 high 17 | return obs,where 18 | end 19 | 20 | proto.begin_decode = function(ibs) 21 | ibs:seek(4, yasio.SEEK_CUR) -- skip length 22 | local msg = { 23 | header = { 24 | command_id = ibs:read_u16(), 25 | version = ibs:read_u16(), 26 | reserved = ibs:read_i32(), 27 | reserved2_low = ibs:read_i32(), 28 | reserved2_high = ibs:read_i32() 29 | } 30 | } 31 | return msg 32 | end 33 | 34 | return proto 35 | -------------------------------------------------------------------------------- /examples/lua/scripts/protocol_dec.lua: -------------------------------------------------------------------------------- 1 | -- This file is generated by pcode_autog-1.19.5 2 | -- Copyright(c) Lake.Deal, ALL RIGHTS RESERVED. 3 | -- 4 | -- Purpose: contains all protocol message definiations and codec function 5 | -- implementations 6 | -- 7 | -- 8 | -- Implement all pure lua protocol decode functions. 9 | local proto = require 'protocol_base' 10 | 11 | proto.d101 = function(ibs) 12 | local msg = proto.begin_decode(ibs); 13 | 14 | msg.id = ibs:read_i8(); 15 | msg.value1 = ibs:read_u16(); 16 | msg.value2 = ibs:read_ix(); 17 | msg.value3 = ibs:read_bool(); 18 | msg.value4 = ibs:read_f(); 19 | msg.value6 = ibs:read_lf(); 20 | msg.uname = ibs:read_v(); 21 | msg.passwd = ibs:read_v(); 22 | 23 | return msg; 24 | end 25 | 26 | return proto 27 | -------------------------------------------------------------------------------- /examples/lua/scripts/protocol_enc.lua: -------------------------------------------------------------------------------- 1 | -- This file is generated by pcode_autog-1.19.5 2 | -- Copyright(c) Lake.Deal, ALL RIGHTS RESERVED. 3 | -- 4 | -- Purpose: contains all protocol message definiations and codec function 5 | -- implementations 6 | -- 7 | -- 8 | -- Implement all pure lua protocol encode functions. 9 | local proto = require 'protocol_dec' 10 | 11 | proto.e101 = function(msg) 12 | -- begin message encode. 13 | local obs,len_pos = proto.begin_encode(proto.numbers.CID_SIMPLE1); 14 | 15 | -- encode message fields. 16 | obs:write_i8(msg.id); 17 | obs:write_u16(msg.value1); 18 | obs:write_ix(msg.value2); 19 | obs:write_bool(msg.value3); 20 | obs:write_f(msg.value4); 21 | obs:write_lf(msg.value6); 22 | obs:write_v(msg.uname); 23 | obs:write_v(msg.passwd); 24 | 25 | -- finish message encode. 26 | obs:pop32(len_pos, obs:length()); -- finish encode 27 | 28 | return obs; 29 | end 30 | 31 | return proto 32 | -------------------------------------------------------------------------------- /examples/lua/scripts/protocol_enums.lua: -------------------------------------------------------------------------------- 1 | -- This file is generated by pcode_autog-1.19.5 2 | -- Copyright(c) Lake.Deal, ALL RIGHTS RESERVED. 3 | -- 4 | -- Purpose: contains some constants defininations 5 | -- 6 | -- 7 | local proto = {} 8 | 9 | proto.numbers = { 10 | CID_SIMPLE1 = 101, 11 | } 12 | 13 | return proto 14 | -------------------------------------------------------------------------------- /extensions/yasio_http/.clang-format: -------------------------------------------------------------------------------- 1 | # This file is copy from https://github.com/google/angle with some modifications 2 | # Defines the AXIS style for automatic reformatting. 3 | # https://code.google.com/p/angleproject/wiki/CodingStandard 4 | # See Clang docs: http://clang.llvm.org/docs/ClangFormatStyleOptions.html 5 | BasedOnStyle: Chromium 6 | 7 | # Allow double brackets such as std::vector>. 8 | Standard: Cpp11 9 | 10 | # Indent 4 spaces at a time. 11 | IndentWidth: 4 12 | 13 | # Keep lines under 120 columns long. 14 | ColumnLimit: 120 15 | 16 | SortIncludes: false 17 | 18 | # Always break before braces 19 | BreakBeforeBraces: Custom 20 | BraceWrapping: 21 | AfterCaseLabel: true 22 | AfterClass: true 23 | AfterControlStatement: true 24 | AfterEnum: true 25 | AfterFunction: true 26 | AfterNamespace: true 27 | AfterStruct: true 28 | AfterUnion: true 29 | BeforeCatch: true 30 | BeforeElse: true 31 | IndentBraces: false 32 | SplitEmptyFunction: false 33 | SplitEmptyRecord: false 34 | SplitEmptyNamespace: false 35 | 36 | # Keeps extern "C" blocks unindented. 37 | AfterExternBlock: false 38 | 39 | # Indent case labels. 40 | IndentCaseLabels: false 41 | 42 | # Left-align pointers and references 43 | PointerAlignment: Left 44 | 45 | # ANGLE likes to align things as much as possible. 46 | AlignOperands: true 47 | AlignConsecutiveAssignments: true 48 | 49 | # Use 0 space negative offset for access modifiers 50 | AccessModifierOffset: -4 51 | 52 | # TODO(jmadill): Decide if we want this on. Doesn't have an "all or none" mode. 53 | AllowShortCaseLabelsOnASingleLine: false 54 | 55 | # Useful for spacing out functions in classes 56 | KeepEmptyLinesAtTheStartOfBlocks: true 57 | 58 | # Indent nested PP directives. 59 | IndentPPDirectives: AfterHash 60 | 61 | # Include blocks style 62 | IncludeBlocks: Preserve 63 | UseTab: Never 64 | BreakConstructorInitializers: BeforeComma -------------------------------------------------------------------------------- /extensions/yasio_http/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | set(target_name yasio_http) 3 | 4 | FILE(GLOB_RECURSE YASIO_HTTP_SOURCES *.h;*.cpp;*.c) 5 | 6 | add_library(${target_name} STATIC ${YASIO_HTTP_SOURCES}) 7 | 8 | yasio_config_lib_depends(${target_name}) 9 | 10 | target_include_directories(${target_name} 11 | PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}" 12 | PUBLIC "${YASIO_ROOT}/thirdparty/llhttp/include" 13 | ) 14 | -------------------------------------------------------------------------------- /extensions/yasio_http/HttpCookie.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | Copyright (c) 2013-2016 Chukong Technologies Inc. 3 | Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. 4 | Copyright (c) 2019-present Axmol Engine contributors. 5 | 6 | https://axmolengine.github.io/ 7 | 8 | Permission is hereby granted, free of charge, to any person obtaining a copy 9 | of this software and associated documentation files (the "Software"), to deal 10 | in the Software without restriction, including without limitation the rights 11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | copies of the Software, and to permit persons to whom the Software is 13 | furnished to do so, subject to the following conditions: 14 | 15 | The above copyright notice and this permission notice shall be included in 16 | all copies or substantial portions of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | THE SOFTWARE. 25 | ****************************************************************************/ 26 | 27 | #ifndef YASIO_EXT_HTTP_COOKIE_H 28 | #define YASIO_EXT_HTTP_COOKIE_H 29 | /// @cond DO_NOT_SHOW 30 | 31 | #include 32 | #include 33 | #include 34 | 35 | #include "yasio/string_view.hpp" 36 | 37 | namespace yasio_ext 38 | { 39 | 40 | namespace network 41 | { 42 | #if YASIO__HAS_CXX14 43 | using namespace cxx17::string_view_literals; 44 | # define _mksv(a) a ""_sv 45 | #else 46 | template 47 | inline cxx17::string_view _mksv(const char (&str)[_Size]) 48 | { 49 | return cxx17::string_view{str, _Size - 1}; 50 | } 51 | #endif 52 | 53 | class Uri; 54 | struct CookieInfo 55 | { 56 | CookieInfo() = default; 57 | CookieInfo(const CookieInfo&) = default; 58 | CookieInfo(CookieInfo&& rhs) 59 | : domain(std::move(rhs.domain)) 60 | , tailmatch(rhs.tailmatch) 61 | , path(std::move(rhs.path)) 62 | , secure(rhs.secure) 63 | , name(std::move(rhs.name)) 64 | , value(std::move(rhs.value)) 65 | , expires(rhs.expires) 66 | {} 67 | 68 | CookieInfo& operator=(CookieInfo&& rhs) 69 | { 70 | domain = std::move(rhs.domain); 71 | tailmatch = rhs.tailmatch; 72 | path = std::move(rhs.path); 73 | secure = rhs.secure; 74 | name = std::move(rhs.name); 75 | value = std::move(rhs.value); 76 | expires = rhs.expires; 77 | return *this; 78 | } 79 | 80 | bool isSame(const CookieInfo& rhs) { return name == rhs.name && domain == rhs.domain; } 81 | 82 | void updateValue(const CookieInfo& rhs) 83 | { 84 | value = rhs.value; 85 | expires = rhs.expires; 86 | path = rhs.path; 87 | } 88 | 89 | std::string domain; 90 | bool tailmatch = true; 91 | std::string path; 92 | bool secure = false; 93 | std::string name; 94 | std::string value; 95 | time_t expires = 0; 96 | }; 97 | 98 | class HttpCookie 99 | { 100 | public: 101 | void readFile(); 102 | 103 | void writeFile(); 104 | void setCookieFileName(cxx17::string_view fileName); 105 | 106 | const std::vector* getCookies() const; 107 | const CookieInfo* getMatchCookie(const Uri& uri) const; 108 | void updateOrAddCookie(CookieInfo* cookie); 109 | 110 | // Check match cookies for http request 111 | std::string checkAndGetFormatedMatchCookies(const Uri& uri); 112 | bool updateOrAddCookie(const cxx17::string_view& cookie, const Uri& uri); 113 | 114 | private: 115 | std::string _cookieFileName; 116 | std::vector _cookies; 117 | }; 118 | 119 | } // namespace network 120 | } // namespace yasio_ext 121 | 122 | /// @endcond 123 | #endif /* HTTP_COOKIE_H */ 124 | -------------------------------------------------------------------------------- /extensions/yasio_http/yasio_http.cpp: -------------------------------------------------------------------------------- 1 | #include "yasio/config.hpp" 2 | 3 | #if defined(YASIO_INSIDE_UNREAL) 4 | 5 | #include "Modules/ModuleManager.h" 6 | 7 | class yasio_http_unreal_module : public IModuleInterface 8 | { 9 | public: 10 | /** IModuleInterface implementation */ 11 | void StartupModule() override {} 12 | void ShutdownModule() override {} 13 | }; 14 | IMPLEMENT_MODULE(yasio_http_unreal_module, yasio_http) 15 | 16 | #endif 17 | -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "versions": { 3 | "1kdist": "v99" 4 | }, 5 | "mirrors": { 6 | "github": { 7 | "host": "github.com", 8 | "1kdist": "simdsoft/1kiss/releases/download" 9 | }, 10 | "gitee": 11 | { 12 | "host": "gitee.com", 13 | "1kdist": "simdsoft/1kiss/releases/download" 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | docs_dir: docs 2 | site_name: yasio 3 | repo_url: https://github.com/yasio/yasio 4 | repo_name: yasio/yasio 5 | edit_uri: edit/dev/docs 6 | copyright: Copyright © 2012-present HALX99. 7 | theme: 8 | name: material 9 | language: zh 10 | logo: assets/images/logo.png 11 | favicon: assets/images/logo.png 12 | features: 13 | - content.action.edit 14 | - content.action.view 15 | - content.code.copy 16 | - navigation.footer 17 | icon: 18 | edit: material/pencil 19 | view: material/eye 20 | repo: fontawesome/brands/github 21 | palette: 22 | # Palette toggle for light mode 23 | - media: "(prefers-color-scheme: light)" 24 | scheme: default 25 | toggle: 26 | icon: material/brightness-7 27 | name: Switch to dark mode 28 | 29 | # Palette toggle for dark mode 30 | - media: "(prefers-color-scheme: dark)" 31 | scheme: slate 32 | toggle: 33 | icon: material/brightness-4 34 | name: Switch to light mode 35 | nav: 36 | - 主页: index.md 37 | - API 参考: 38 | - io_service类: api/reference/io_service-class.md 39 | - io_channel类: api/reference/io_channel-class.md 40 | - io_event类: api/reference/io_event-class.md 41 | - obstream类: api/reference/obstream-class.md 42 | - ibstream类: api/reference/ibstream-class.md 43 | - xxsocket类: api/reference/xxsocket-class.md 44 | - endpoint类: api/reference/endpoint-class.md 45 | - object_pool类: api/reference/object_pool-class.md 46 | - singleton类: api/reference/singleton-class.md 47 | - io_service选项: api/reference/io_service-options.md 48 | - 其他常用API: api/reference/others.md 49 | - 预处理器: preprocessor.md 50 | - 粘包处理: unpacking.md 51 | - Interop: interop.md 52 | - 常见问题: faq.md 53 | 54 | # Extensions 55 | markdown_extensions: 56 | - abbr 57 | - admonition 58 | - attr_list 59 | - def_list 60 | - footnotes 61 | - md_in_html 62 | - toc: 63 | permalink: true 64 | - pymdownx.arithmatex: 65 | generic: true 66 | - pymdownx.betterem: 67 | smart_enable: all 68 | - pymdownx.caret 69 | - pymdownx.details 70 | - pymdownx.emoji: 71 | emoji_generator: !!python/name:material.extensions.emoji.to_svg 72 | emoji_index: !!python/name:material.extensions.emoji.twemoji 73 | - pymdownx.highlight: 74 | anchor_linenums: true 75 | line_spans: __span 76 | pygments_lang_class: true 77 | - pymdownx.inlinehilite 78 | - pymdownx.keys 79 | - pymdownx.magiclink: 80 | repo_url_shorthand: true 81 | user: yasio 82 | repo: yasio 83 | - pymdownx.mark 84 | - pymdownx.smartsymbols 85 | - pymdownx.superfences: 86 | custom_fences: 87 | - name: mermaid 88 | class: mermaid 89 | format: !!python/name:pymdownx.superfences.fence_code_format 90 | - pymdownx.tabbed: 91 | alternate_style: true 92 | - pymdownx.tasklist: 93 | custom_checkbox: true 94 | - pymdownx.tilde 95 | plugins: 96 | - search: 97 | separator: '[\s\-,:!=\[\]()"`/]+|\.(?!\d)|&[lg]t;|(?!\b)(?=[A-Z][a-z])' 98 | - pdf-export: 99 | verbose: false 100 | media_type: print 101 | combined: true 102 | combined_output_path: pdf/yasio-latest.pdf 103 | enabled_if_env: DOCS_CI 104 | - minify: 105 | minify_html: true 106 | - git-revision-date-localized: 107 | enable_creation_date: true 108 | extra_css: 109 | - 'assets/stylesheets/extra.css' 110 | extra: 111 | analytics: 112 | provider: google 113 | property: G-DHR2DGTKEB 114 | feedback: 115 | title: Was this page helpful? 116 | ratings: 117 | - icon: material/emoticon-happy-outline 118 | name: This page was helpful 119 | data: 1 120 | note: >- 121 | Thanks for your feedback! 122 | - icon: material/emoticon-sad-outline 123 | name: This page could be improved 124 | data: 0 125 | note: >- 126 | Thanks for your feedback! Help us improve this page by 127 | using our feedback form. 128 | 129 | alternate: 130 | # Switch to Chinese Simplfied 131 | - name: 简体中文 132 | link: https://global.simdsoft.com/yasio/ 133 | lang: zh 134 | 135 | # Switch to English 136 | - name: English 137 | link: https://global.simdsoft.com/yasio/ 138 | lang: en 139 | version: 140 | provider: mike 141 | -------------------------------------------------------------------------------- /tests/echo_client/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(target_name echo_client) 2 | 3 | set (ECHO_CLIENT_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (ECHO_CLIENT_INC_DIR ${ECHO_CLIENT_SRC_DIR}/../../) 5 | 6 | set (ECHO_CLIENT_SRC ${ECHO_CLIENT_SRC_DIR}/main.cpp) 7 | 8 | 9 | include_directories ("${ECHO_CLIENT_SRC_DIR}") 10 | include_directories ("${ECHO_CLIENT_INC_DIR}") 11 | 12 | add_executable (${target_name} ${ECHO_CLIENT_SRC}) 13 | 14 | yasio_config_app_depends(${target_name}) 15 | -------------------------------------------------------------------------------- /tests/echo_client/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #include "yasio/yasio.hpp" 7 | 8 | using namespace yasio; 9 | 10 | static highp_time_t s_last_send_time[3] = {0}; 11 | static const highp_time_t s_send_interval = 2000; // (ms) 12 | 13 | void run_echo_client(const char* ip, int port, const char* protocol) 14 | { 15 | yasio::inet::io_hostent endpoints[] = { 16 | {ip, static_cast(port)}, // tcp client 17 | }; 18 | 19 | io_service service(endpoints, YASIO_ARRAYSIZE(endpoints)); 20 | 21 | std::vector transports; 22 | 23 | deadline_timer send_timer(service); 24 | int total_bytes_transferred = 0; 25 | 26 | int max_request_count = 10; 27 | 28 | service.start([&](event_ptr&& event) { 29 | switch (event->kind()) 30 | { 31 | case YEK_PACKET: { 32 | auto index = event->cindex(); 33 | auto diff = highp_clock() - s_last_send_time[index]; 34 | 35 | auto packet = std::move(event->packet()); 36 | total_bytes_transferred += static_cast(packet.size()); 37 | printf("[latency: %lf(ms), bytes=%zu]", diff / 1000.0, packet.size()); 38 | fwrite(packet.data(), packet.size(), 1, stdout); 39 | printf("\n"); 40 | fflush(stdout); 41 | break; 42 | } 43 | case YEK_CONNECT_RESPONSE: 44 | if (event->status() == 0) 45 | { 46 | auto transport = event->transport(); 47 | auto index = event->cindex(); 48 | if (index == 0) 49 | { 50 | send_timer.expires_from_now(std::chrono::milliseconds(s_send_interval)); 51 | send_timer.async_wait([transport, index, protocol](io_service& service) -> bool { 52 | obstream obs; 53 | obs.write_byte('['); 54 | obs.write_bytes(protocol, static_cast(strlen(protocol))); 55 | obs.write_bytes("] Hello, "); 56 | auto n = 4096 - static_cast(obs.length()); 57 | obs.fill_bytes(n, 'a'); 58 | auto bytes_transferred = service.write(transport, std::move(obs.buffer())); 59 | printf("sent %d bytes ...\n", bytes_transferred); 60 | s_last_send_time[index] = highp_clock(); 61 | return false; 62 | }); 63 | } 64 | 65 | transports.push_back(transport); 66 | } 67 | break; 68 | case YEK_CONNECTION_LOST: 69 | printf("The connection is lost, %d bytes transferred\n", total_bytes_transferred); 70 | break; 71 | } 72 | }); 73 | 74 | std::this_thread::sleep_for(std::chrono::seconds(1)); 75 | 76 | printf("[%s] connecting %s:%u ...\n", protocol, ip, port); 77 | if (cxx20::ic::iequals(protocol, "udp")) 78 | { 79 | service.open(0, YCK_UDP_CLIENT); 80 | } 81 | else if (cxx20::ic::iequals(protocol, "kcp")) 82 | { 83 | service.open(0, YCK_KCP_CLIENT); 84 | } 85 | else 86 | { 87 | /* 88 | ** If after 5 seconds no data interaction at application layer, 89 | ** send a heartbeat per 10 seconds when no response, try 2 times 90 | ** if no response, then he connection will shutdown by driver. 91 | ** At windows will close with error: 10054 92 | */ 93 | service.set_option(YOPT_S_TCP_KEEPALIVE, 5, 10, 2); 94 | service.open(0, YCK_TCP_CLIENT); 95 | } 96 | 97 | time_t duration = 0; 98 | while (service.is_running()) 99 | { 100 | if (duration >= 6000000) 101 | { 102 | for (auto transport : transports) 103 | service.close(transport); 104 | break; 105 | } 106 | duration += 50; 107 | std::this_thread::sleep_for(std::chrono::milliseconds(50)); 108 | } 109 | } 110 | 111 | int main(int argc, char** argv) 112 | { 113 | if (argc > 3) 114 | run_echo_client(argv[1], atoi(argv[2]), argv[3]); 115 | 116 | return 0; 117 | } 118 | -------------------------------------------------------------------------------- /tests/echo_server/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(target_name echo_server) 2 | 3 | set (ECHO_SERVER_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (ECHO_SERVER_INC_DIR ${ECHO_SERVER_SRC_DIR}/../../) 5 | 6 | set (ECHO_SERVER_SRC ${ECHO_SERVER_SRC_DIR}/main.cpp) 7 | 8 | include_directories ("${ECHO_SERVER_SRC_DIR}") 9 | include_directories ("${ECHO_SERVER_INC_DIR}") 10 | 11 | add_executable (${target_name} ${ECHO_SERVER_SRC}) 12 | 13 | yasio_config_app_depends(${target_name}) 14 | -------------------------------------------------------------------------------- /tests/echo_server/main.cpp: -------------------------------------------------------------------------------- 1 | #include "yasio/yasio.hpp" 2 | #include 3 | 4 | using namespace yasio; 5 | 6 | io_service* gservice = nullptr; // the weak pointer 7 | void handle_signal(int sig) 8 | { 9 | if (gservice && sig == 2) 10 | { 11 | gservice->close(0); 12 | } 13 | } 14 | 15 | // 6: TCP server, 10: UDP server, 26: KCP server 16 | void run_echo_server(const char* ip, u_short port, const char* protocol) 17 | { 18 | io_hostent endpoints[] = {{ip, port}}; 19 | io_service server(endpoints, 1); 20 | gservice = &server; 21 | server.set_option(YOPT_S_NO_NEW_THREAD, 1); 22 | server.set_option(YOPT_C_MOD_FLAGS, 0, YCF_REUSEADDR, 0); 23 | 24 | signal(SIGINT, handle_signal); 25 | 26 | // !important, because we set YOPT_S_NO_NEW_THREAD, so need a timer to start server 27 | deadline_timer timer(server); 28 | timer.expires_from_now(std::chrono::seconds(1)); 29 | timer.async_wait_once([=](io_service& server) { 30 | server.set_option(YOPT_C_UNPACK_PARAMS, 0, 65536, -1, 0, 0); 31 | printf("[%s] open server %s:%u ...\n", protocol, ip, port); 32 | if (cxx20::ic::iequals(protocol, "udp")) 33 | server.open(0, YCK_UDP_SERVER); 34 | else if (cxx20::ic::iequals(protocol, "kcp")) 35 | server.open(0, YCK_KCP_SERVER); 36 | else 37 | server.open(0, YCK_TCP_SERVER); 38 | }); 39 | server.start([&](event_ptr ev) { 40 | switch (ev->kind()) 41 | { 42 | case YEK_ON_OPEN: 43 | if (ev->passive()) 44 | { 45 | if (ev->status() == 0) 46 | { 47 | printf("[%lld] start server ok, status=%d\n", ev->timestamp(), ev->status()); 48 | } 49 | else 50 | { 51 | printf("[%lld] start server failed, status=%d\n", ev->timestamp(), ev->status()); 52 | } 53 | return; 54 | } 55 | printf("[%lld] A client is income, status=%d\n", ev->timestamp(), ev->status()); 56 | case YEK_ON_PACKET: 57 | if (!ev->packet().empty()) 58 | server.write(ev->transport(), std::move(ev->packet())); 59 | 60 | // kick out after 3(s) if no new packet income 61 | { 62 | timer.expires_from_now(std::chrono::seconds(3)); 63 | auto transport = ev->transport(); 64 | timer.async_wait_once([transport](io_service& server) { server.close(transport); }); 65 | } 66 | break; 67 | case YEK_ON_CLOSE: 68 | if (ev->passive()) 69 | { 70 | printf("[%lld] stop server done, status=%d\n", ev->timestamp(), ev->status()); 71 | server.stop(); // stop could call self thread 72 | gservice = nullptr; // service will stop, clear gservice weak pointer 73 | } 74 | break; 75 | } 76 | }); 77 | } 78 | 79 | int main(int argc, char** argv) 80 | { 81 | if (argc > 3) 82 | run_echo_server(argv[1], atoi(argv[2]), argv[3]); 83 | else 84 | printf("usage: ip port protocol(udp,kcp,tcp)\n"); 85 | return 0; 86 | } 87 | -------------------------------------------------------------------------------- /tests/http/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set (target_name httptest) 2 | 3 | set (HTTPTEST_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (HTTPTEST_INC_DIR ${HTTPTEST_SRC_DIR}/../../) 5 | 6 | set (HTTPTEST_SRC ${HTTPTEST_SRC_DIR}/main.cpp) 7 | 8 | include_directories ("${HTTPTEST_SRC_DIR}") 9 | include_directories ("${HTTPTEST_INC_DIR}") 10 | 11 | add_executable (${target_name} ${HTTPTEST_SRC}) 12 | yasio_config_http_app_depends(${target_name}) 13 | 14 | -------------------------------------------------------------------------------- /tests/http/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "yasio_http/HttpClient.h" 6 | #include "yasio/yasio.hpp" 7 | 8 | #include 9 | 10 | using namespace yasio; 11 | using namespace yasio_ext::network; 12 | 13 | #define CHROME_UA "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" 14 | 15 | void yasioTest() 16 | { 17 | auto httpClient = HttpClient::getInstance(); 18 | httpClient->setDispatchOnWorkThread(true); 19 | 20 | auto request = new HttpRequest(); 21 | 22 | request->setHeaders(std::vector{CHROME_UA}); 23 | request->setUrl("https://github.com/yasio"); 24 | request->setRequestType(HttpRequest::Type::Get); 25 | 26 | auto response = httpClient->sendSync(request); 27 | request->release(); 28 | 29 | if (response) 30 | { 31 | if (response->getResponseCode() == 200) 32 | { 33 | auto responseData = response->getResponseData(); 34 | // fwrite(responseData->data(), responseData->size(), 1, stdout); 35 | printf("===>request succeed\n"); 36 | } 37 | else 38 | printf("===>request failed with %d\n", response->getResponseCode()); 39 | printf("%s", "===>response headers:\n"); 40 | for (auto& header : response->getResponseHeaders()) 41 | printf("\t%s: %s\n", header.first.c_str(), header.second.c_str()); 42 | response->release(); 43 | } 44 | HttpClient::destroyInstance(); 45 | } 46 | 47 | int main(int, char**) 48 | { 49 | #if defined(_WIN32) 50 | SetConsoleOutputCP(CP_UTF8); 51 | #endif 52 | 53 | yasioTest(); 54 | 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /tests/icmp/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(target_name icmptest) 2 | 3 | set (ICMPTEST_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (ICMPTEST_INC_DIR ${ICMPTEST_SRC_DIR}/../../) 5 | 6 | set (ICMPTEST_SRC ${ICMPTEST_SRC_DIR}/main.cpp) 7 | 8 | 9 | include_directories ("${ICMPTEST_SRC_DIR}") 10 | include_directories ("${ICMPTEST_INC_DIR}") 11 | 12 | add_executable (${target_name} ${ICMPTEST_SRC}) 13 | 14 | yasio_config_app_depends(${target_name}) 15 | -------------------------------------------------------------------------------- /tests/issue166/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set (target_name issue166) 2 | 3 | set (ISSUE166_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (ISSUE166_INC_DIR ${ISSUE166_SRC_DIR}/../../) 5 | 6 | set (ISSUE166_SRC ${ISSUE166_SRC_DIR}/main.cpp) 7 | 8 | include_directories ("${ISSUE166_SRC_DIR}") 9 | include_directories ("${ISSUE166_INC_DIR}") 10 | 11 | add_executable (${target_name} ${ISSUE166_SRC}) 12 | 13 | yasio_config_app_depends(${target_name}) 14 | -------------------------------------------------------------------------------- /tests/issue166/main.cpp: -------------------------------------------------------------------------------- 1 | #include "yasio/yasio.hpp" 2 | 3 | using namespace yasio; 4 | 5 | int main() 6 | { 7 | yasio::inet::io_hostent endpoints[] = { 8 | {"127.0.0.1", 12345} // tcp client 9 | }; 10 | io_service service(endpoints, 1); 11 | int retry_count = 0; 12 | int total_bytes_transferred = 0; 13 | service.start([&](event_ptr event) { 14 | switch (event->kind()) 15 | { 16 | case YEK_PACKET: { 17 | auto packet = std::move(event->packet()); 18 | total_bytes_transferred += static_cast(packet.size()); 19 | fwrite(packet.data(), packet.size(), 1, stdout); 20 | fflush(stdout); 21 | break; 22 | } 23 | case YEK_CONNECT_RESPONSE: { 24 | printf("The connection is YEK_CONNECT_RESPONSE, status=%d, %lld\n", event->status(), event->timestamp()); 25 | 26 | auto transport = event->transport(); 27 | if (event->cindex() == 0) 28 | { 29 | obstream obs; 30 | auto where = obs.push(); 31 | obs.write_bytes("hello world"); 32 | obs.pop(where); 33 | // 000xxxxhelloworld 34 | ip::endpoint ep{"127.0.0.1", 12345}; 35 | service.write_to(transport, std::move(obs.buffer()), ep); 36 | } 37 | if (event->status() != 0) 38 | { 39 | if (retry_count++ < 2) 40 | { 41 | service.set_option(YOPT_C_REMOTE_ENDPOINT, 0, "127.0.0.1", 12345); 42 | service.open(0, YCK_UDP_CLIENT); // open udp client 43 | } 44 | else 45 | exit(-1); 46 | } 47 | break; 48 | } 49 | } 50 | }); 51 | service.set_option(YOPT_S_CONNECT_TIMEOUT, 5); 52 | service.set_option(YOPT_C_UNPACK_PARAMS, 0, 65535, 3, 4, 7); 53 | service.set_option(YOPT_C_LFBFD_IBTS, 0, 7); // Sets initial bytes to strip 54 | service.open(0, YCK_UDP_CLIENT); // open udp client 55 | 56 | getchar(); 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /tests/issue178/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set (target_name issue178) 2 | 3 | set (ISSUE178_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (ISSUE178_INC_DIR ${ISSUE178_SRC_DIR}/../../) 5 | 6 | set (ISSUE178_SRC ${ISSUE178_SRC_DIR}/main.cpp) 7 | 8 | include_directories ("${ISSUE178_SRC_DIR}") 9 | include_directories ("${ISSUE178_INC_DIR}") 10 | 11 | add_executable (${target_name} ${ISSUE178_SRC}) 12 | 13 | yasio_config_app_depends(${target_name}) 14 | -------------------------------------------------------------------------------- /tests/issue178/main.cpp: -------------------------------------------------------------------------------- 1 | #include "yasio/yasio.hpp" 2 | 3 | using namespace yasio; 4 | 5 | int main() 6 | { 7 | yasio::inet::io_hostent endpoints[] = { 8 | {"0.0.0.0", 8010}, // tcp server 9 | {"127.0.0.1", 8010} // tcp client 10 | }; 11 | io_service service(endpoints, YASIO_ARRAYSIZE(endpoints)); 12 | deadline_timer delay_timer(service); 13 | service.start([&](event_ptr event) { 14 | switch (event->kind()) 15 | { 16 | case YEK_PACKET: 17 | if (event->cindex() == 1) 18 | printf("Got a packet from server, size=%d\n", (int)event->packet().size()); 19 | break; 20 | case YEK_CONNECT_RESPONSE: { 21 | if (event->cindex() == 0) 22 | { 23 | printf("A client is income, status=%d, %lld, combine 2 packet and send to client!\n", event->status(), event->timestamp()); 24 | 25 | // send 2 packet 26 | obstream obs1; 27 | auto where = obs1.push(); 28 | for (auto i = 0; i < 119 - 4; ++i) 29 | obs1.write_byte(i + 1); 30 | obs1.pop(where, static_cast(obs1.length())); 31 | 32 | obstream obs2; 33 | where = obs2.push(); 34 | for (auto i = 0; i < 104 - 4; ++i) 35 | obs2.write_byte(i + 1); 36 | obs2.pop(where, static_cast(obs2.length())); 37 | 38 | // merge 2 packets 39 | obs1.write_bytes(obs2.data(), static_cast(obs2.length())); 40 | service.write(event->transport(), std::move(obs1.buffer())); 41 | } 42 | 43 | break; 44 | } 45 | } 46 | }); 47 | service.set_option(YOPT_S_CONNECT_TIMEOUT, 5); 48 | service.set_option(YOPT_C_UNPACK_PARAMS, 1, 65535, 0, 4, 0); 49 | service.set_option(YOPT_C_LFBFD_IBTS, 1, 4); // Sets initial bytes to strip 50 | service.open(0, YCK_TCP_SERVER); // open server 51 | 52 | delay_timer.expires_from_now(std::chrono::seconds(1)); 53 | delay_timer.async_wait_once([](io_service& service) { service.open(1, YCK_TCP_CLIENT); }); 54 | 55 | getchar(); 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /tests/issue201/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set (target_name issue201) 2 | 3 | set (ISSUE201_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (ISSUE201_INC_DIR ${ISSUE201_SRC_DIR}/../../) 5 | 6 | set (ISSUE201_SRC ${ISSUE201_SRC_DIR}/main.cpp) 7 | 8 | include_directories ("${ISSUE201_SRC_DIR}") 9 | include_directories ("${ISSUE201_INC_DIR}") 10 | 11 | add_executable (${target_name} ${ISSUE201_SRC}) 12 | 13 | yasio_config_app_depends(${target_name}) 14 | -------------------------------------------------------------------------------- /tests/issue201/main.cpp: -------------------------------------------------------------------------------- 1 | #include "yasio/utils.hpp" 2 | #include "yasio/yasio.hpp" 3 | 4 | using namespace yasio; 5 | 6 | int main() 7 | { 8 | xxsocket sock; 9 | const char* addrip = "114.114.114.114"; 10 | u_short port = 9099; 11 | YASIO_LOG("connecting %s:%u...", addrip, port); 12 | auto start = yasio::highp_clock(); 13 | if (sock.xpconnect_n(addrip, port, std::chrono::seconds(3)) != 0) 14 | YASIO_LOG("connect %s failed, the timeout should be approximately equal to 3(s), real: " 15 | "%lf(s); but when the host network adapter isn't connected, it may be approximately " 16 | "equal to 0(s)\n", 17 | addrip, (yasio::highp_clock() - start) / (double)std::micro::den); 18 | else 19 | YASIO_LOG("Aha connect %s succeed, cost: %lf(s)\n", addrip, 20 | (yasio::highp_clock() - start) / (double)std::micro::den); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /tests/issue208/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set (target_name issue208) 2 | 3 | set (ISSUE208_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (ISSUE208_INC_DIR ${ISSUE208_SRC_DIR}/../../) 5 | 6 | set (ISSUE208_SRC ${ISSUE208_SRC_DIR}/main.cpp) 7 | 8 | include_directories ("${ISSUE208_SRC_DIR}") 9 | include_directories ("${ISSUE208_INC_DIR}") 10 | 11 | add_executable (${target_name} ${ISSUE208_SRC}) 12 | 13 | yasio_config_app_depends(${target_name}) 14 | -------------------------------------------------------------------------------- /tests/issue208/main.cpp: -------------------------------------------------------------------------------- 1 | #include "yasio/yasio.hpp" 2 | 3 | using namespace yasio; 4 | deadline_timer_ptr udpHeartTimer = nullptr; 5 | 6 | void start_exprie_timer(); 7 | timer_cb_t create_timer_cb(); 8 | 9 | io_service& get_service() { return *yasio_shared_service(); } 10 | 11 | static yasio::highp_time_t getTimeStamp() 12 | { 13 | return yasio::highp_clock() / 1000; 14 | } 15 | 16 | void start_exprie_timer() 17 | { 18 | if (udpHeartTimer) 19 | { 20 | udpHeartTimer->expires_from_now(); 21 | udpHeartTimer->async_wait(create_timer_cb()); 22 | } 23 | else 24 | { 25 | udpHeartTimer = get_service().schedule(std::chrono::seconds(4), create_timer_cb()); 26 | } 27 | } 28 | 29 | timer_cb_t create_timer_cb() 30 | { 31 | return [](io_service& s) { 32 | if (udpHeartTimer->expired()) 33 | { 34 | printf("udp timer %lld\n", getTimeStamp()); 35 | start_exprie_timer(); 36 | } 37 | else 38 | { 39 | printf("create_timer_cb start_exprie_timer\n"); 40 | } 41 | return true; 42 | }; 43 | } 44 | 45 | int main() 46 | { 47 | auto& service = get_service(); 48 | service.set_option(YOPT_S_HRES_TIMER, 1); 49 | service.set_option(YOPT_C_REMOTE_ENDPOINT, 0, "www.ip138.com", 80); 50 | service.start([&](event_ptr&& ev) { 51 | switch (ev->kind()) 52 | { 53 | case YEK_PACKET: { 54 | auto packet = std::move(ev->packet()); 55 | fwrite(packet.data(), packet.size(), 1, stdout); 56 | fflush(stdout); 57 | break; 58 | } 59 | case YEK_CONNECT_RESPONSE: 60 | if (ev->status() == 0) 61 | { 62 | start_exprie_timer(); 63 | 64 | auto transport = ev->transport(); 65 | if (ev->cindex() == 0) 66 | { 67 | obstream obs; 68 | obs.write_bytes("GET /index.htm HTTP/1.1\r\n"); 69 | 70 | obs.write_bytes("Host: www.ip138.com\r\n"); 71 | 72 | obs.write_bytes("User-Agent: Mozilla/5.0 (Windows NT 10.0; " 73 | "WOW64) AppleWebKit/537.36 (KHTML, like Gecko) " 74 | "Chrome/79.0.3945.117 Safari/537.36\r\n"); 75 | obs.write_bytes("Accept: */*;q=0.8\r\n"); 76 | obs.write_bytes("Connection: Close\r\n\r\n"); 77 | 78 | service.write(transport, std::move(obs.buffer())); 79 | } 80 | } 81 | break; 82 | case YEK_CONNECTION_LOST: 83 | printf("The connection is lost.\n"); 84 | break; 85 | } 86 | }); 87 | // open channel 0 as tcp client 88 | service.open(0, YCK_TCP_CLIENT); 89 | 90 | std::this_thread::sleep_for(std::chrono::microseconds(1000 * 1000)); 91 | printf("tmp timer call at %lld\n", getTimeStamp()); 92 | service.schedule(std::chrono::milliseconds(1), [](io_service&) { 93 | printf("tmp timer start at %lld\n", getTimeStamp()); 94 | return false; 95 | }); 96 | 97 | getchar(); 98 | } 99 | -------------------------------------------------------------------------------- /tests/issue245/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set (target_name issue245) 2 | 3 | set (ISSUE245_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (ISSUE245_INC_DIR ${ISSUE245_SRC_DIR}/../../) 5 | 6 | set (ISSUE245_SRC ${ISSUE245_SRC_DIR}/main.cpp) 7 | 8 | include_directories ("${ISSUE245_SRC_DIR}") 9 | include_directories ("${ISSUE245_INC_DIR}") 10 | 11 | add_executable (${target_name} ${ISSUE245_SRC}) 12 | 13 | yasio_config_app_depends(${target_name}) 14 | -------------------------------------------------------------------------------- /tests/issue245/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "yasio/yasio.hpp" 3 | 4 | #ifndef _WIN32 5 | # include 6 | #endif 7 | 8 | using namespace yasio; 9 | 10 | static int count = 0; 11 | 12 | #ifndef _WIN32 13 | static struct itimerval oldtv; 14 | void set_timer() 15 | { 16 | struct itimerval itv; 17 | itv.it_interval.tv_sec = 0; 18 | itv.it_interval.tv_usec = 100; 19 | itv.it_value.tv_sec = 0; 20 | itv.it_value.tv_usec = 100; 21 | setitimer(ITIMER_REAL, &itv, &oldtv); 22 | } 23 | 24 | void signal_handler(int m) { count++; } 25 | #endif 26 | 27 | int main() 28 | { 29 | #ifndef _WIN32 30 | signal(SIGALRM, signal_handler); 31 | set_timer(); 32 | #endif 33 | printf("connecting...\n"); 34 | xxsocket sock; 35 | if (0 != sock.pconnect_n("www.ip138.com", 80, std::chrono::milliseconds(5000))) 36 | { 37 | printf("connect error!\n"); 38 | return -2; 39 | } 40 | 41 | obstream obs; 42 | obs.write_bytes("GET /index.htm HTTP/1.1\r\n"); 43 | 44 | obs.write_bytes("Host: www.ip138.com\r\n"); 45 | 46 | obs.write_bytes("User-Agent: Mozilla/5.0 (Windows NT 10.0; " 47 | "WOW64) AppleWebKit/537.36 (KHTML, like Gecko) " 48 | "Chrome/79.0.3945.117 Safari/537.36\r\n"); 49 | obs.write_bytes("Accept: */*;q=0.8\r\n"); 50 | obs.write_bytes("Connection: Close\r\n\r\n"); 51 | auto k = obs.data(); 52 | printf("sending...\n"); 53 | int n = static_cast(obs.length()); 54 | if (n != sock.send(obs.data(), n)) 55 | { 56 | printf("send error!\n"); 57 | return -4; 58 | } 59 | 60 | printf("send success."); 61 | getchar(); 62 | 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /tests/issue256/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set (target_name issue256) 2 | 3 | set (ISSUE256_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (ISSUE256_INC_DIR ${ISSUE256_SRC_DIR}/../../) 5 | 6 | set (ISSUE256_SRC ${ISSUE256_SRC_DIR}/main.cpp) 7 | 8 | include_directories ("${ISSUE256_SRC_DIR}") 9 | include_directories ("${ISSUE256_INC_DIR}") 10 | 11 | add_executable (${target_name} ${ISSUE256_SRC}) 12 | 13 | yasio_config_app_depends(${target_name}) 14 | -------------------------------------------------------------------------------- /tests/issue256/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "yasio/yasio.hpp" 6 | 7 | using namespace yasio; 8 | 9 | void yasioTest() 10 | { 11 | yasio::inet::io_hostent endpoints[] = {{"x-studio.com", 443}}; 12 | 13 | 14 | int total_bytes_transferred = 0; 15 | 16 | int max_request_count = 10; 17 | 18 | 19 | for (;;) 20 | { 21 | io_service service(endpoints, 1); 22 | 23 | service.start([&](event_ptr&& event) { 24 | switch (event->kind()) 25 | { 26 | case YEK_PACKET: { 27 | auto packet = std::move(event->packet()); 28 | total_bytes_transferred += static_cast(packet.size()); 29 | fwrite(packet.data(), packet.size(), 1, stdout); 30 | fflush(stdout); 31 | break; 32 | } 33 | case YEK_CONNECT_RESPONSE: 34 | if (event->status() == 0) 35 | { 36 | auto transport = event->transport(); 37 | if (event->cindex() == 0) 38 | { 39 | obstream obs; 40 | obs.write_bytes("GET / HTTP/1.1\r\n"); 41 | 42 | obs.write_bytes("Host: github.com\r\n"); 43 | 44 | obs.write_bytes("User-Agent: Mozilla/5.0 (Windows NT 10.0; " 45 | "WOW64) AppleWebKit/537.36 (KHTML, like Gecko) " 46 | "Chrome/78.0.3904.108 Safari/537.36\r\n"); 47 | obs.write_bytes("Accept: */*;q=0.8\r\n"); 48 | obs.write_bytes("Connection: Close\r\n\r\n"); 49 | 50 | service.write(transport, std::move(obs.buffer())); 51 | } 52 | } 53 | break; 54 | case YEK_CONNECTION_LOST: 55 | printf("The connection is lost, %d bytes transferred\n", total_bytes_transferred); 56 | break; 57 | } 58 | }); 59 | 60 | /* 61 | ** If after 5 seconds no data interaction at application layer, 62 | ** send a heartbeat per 10 seconds when no response, try 2 times 63 | ** if no response, then he connection will shutdown by driver. 64 | ** At windows will close with error: 10054 65 | */ 66 | service.set_option(YOPT_S_TCP_KEEPALIVE, 5, 10, 2); 67 | 68 | // std::this_thread::sleep_for(std::chrono::seconds(1)); 69 | service.open(0, YCK_SSL_CLIENT); // open https client 70 | 71 | std::this_thread::sleep_for(std::chrono::milliseconds(7)); 72 | 73 | service.stop(); 74 | } 75 | } 76 | 77 | int main(int, char**) 78 | { 79 | yasioTest(); 80 | 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /tests/issue377/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(target_name issue377) 2 | 3 | set (ISSUE377_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (ISSUE377_INC_DIR ${ISSUE377_SRC_DIR}/../../) 5 | 6 | set (ISSUE377_SRC ${ISSUE377_SRC_DIR}/main.cpp) 7 | 8 | 9 | include_directories ("${ISSUE377_SRC_DIR}") 10 | include_directories ("${ISSUE377_INC_DIR}") 11 | 12 | add_executable (${target_name} ${ISSUE377_SRC}) 13 | 14 | yasio_config_app_depends(${target_name}) 15 | -------------------------------------------------------------------------------- /tests/issue377/main.cpp: -------------------------------------------------------------------------------- 1 | #include "yasio/yasio.hpp" 2 | #include 3 | 4 | using namespace yasio; 5 | using namespace yasio::inet; 6 | 7 | int main() 8 | { 9 | 10 | yasio::io_service server = {}; 11 | deadline_timer timer = {server}; 12 | server.set_option(YOPT_S_NO_DISPATCH, 1); 13 | server.set_option(YOPT_C_REMOTE_HOST, 0, "127.0.0.1"); 14 | server.set_option(YOPT_C_REMOTE_PORT, 0, 7899); 15 | server.set_option(YOPT_C_MOD_FLAGS, 0, YCF_REUSEADDR, 1); 16 | server.open(0, YCK_TCP_SERVER); 17 | server.start([&](event_ptr&& ev) { 18 | switch (ev->kind()) 19 | { 20 | case YEK_CONNECT_RESPONSE: 21 | std::cout << "connected.And the connection is disconnected after 3 seconds." << std::endl; 22 | timer.expires_from_now(std::chrono::seconds(3)); 23 | timer.async_wait_once([](io_service& server) { server.close(0); }); 24 | break; 25 | default: 26 | break; 27 | } 28 | }); 29 | 30 | yasio::io_service client = {}; 31 | client.set_option(YOPT_S_NO_DISPATCH, 1); 32 | client.set_option(YOPT_C_REMOTE_HOST, 0, "127.0.0.1"); 33 | client.set_option(YOPT_C_REMOTE_PORT, 0, 7899); 34 | client.open(0, YCK_TCP_CLIENT); 35 | client.start([](event_ptr&& ev) { 36 | switch (ev->kind()) 37 | { 38 | case YEK_CONNECTION_LOST: 39 | 40 | std::cout << "connection lost." << std::endl; 41 | break; 42 | default: 43 | break; 44 | } 45 | }); 46 | 47 | while (true) 48 | { 49 | server.dispatch(); 50 | client.dispatch(); 51 | std::this_thread::sleep_for(std::chrono::milliseconds(20)); 52 | } 53 | return 0; 54 | } -------------------------------------------------------------------------------- /tests/issue384/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(target_name issue384) 2 | 3 | set (ISSUE384_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (ISSUE384_INC_DIR ${ISSUE384_SRC_DIR}/../../) 5 | 6 | set (ISSUE384_SRC ${ISSUE384_SRC_DIR}/main.cpp) 7 | 8 | 9 | include_directories ("${ISSUE384_SRC_DIR}") 10 | include_directories ("${ISSUE384_INC_DIR}") 11 | 12 | add_executable (${target_name} ${ISSUE384_SRC}) 13 | 14 | yasio_config_app_depends(${target_name}) 15 | -------------------------------------------------------------------------------- /tests/issue384/main.cpp: -------------------------------------------------------------------------------- 1 | #include "yasio/yasio.hpp" 2 | #include 3 | 4 | #if !defined(_WIN32) 5 | # include 6 | #endif 7 | 8 | using namespace yasio; 9 | using namespace yasio::inet; 10 | 11 | int main() 12 | { 13 | #if !defined(_WIN32) 14 | static const int required_fd_limit = 4096; 15 | struct rlimit rlim {}; 16 | int ret = getrlimit(RLIMIT_NOFILE, &rlim); 17 | if (ret == 0) 18 | { 19 | printf("===> The file descriptor limits: rlim_cur=%d, rlim_max=%d\n", (int)rlim.rlim_cur, (int)rlim.rlim_max); 20 | 21 | if (rlim.rlim_cur < required_fd_limit) 22 | { 23 | rlim.rlim_cur = required_fd_limit; 24 | ret = setrlimit(RLIMIT_NOFILE, &rlim); 25 | if (ret == 0) 26 | { 27 | printf("===> Enlarge file descriptor limit current to to %d succeed\n\n", (int)rlim.rlim_cur); 28 | } 29 | } 30 | } 31 | #endif 32 | 33 | static const int reserve_socks_count = 1024; 34 | // reserve 1024 socket.fds for test io service when fd greater than 1024 35 | std::vector socks; 36 | socks.resize(reserve_socks_count); 37 | for (auto& sock : socks) 38 | sock.open(); 39 | 40 | 41 | yasio::io_service service = {}; 42 | deadline_timer timer = {service}; 43 | service.set_option(YOPT_S_NO_NEW_THREAD, 1); 44 | timer.expires_from_now(std::chrono::seconds(3)); 45 | timer.async_wait_once([](io_service& svc) { svc.stop(); }); 46 | printf("%s", "===>The service will stop after 3 seconds ...\n\n"); 47 | service.start([](event_ptr&& ev) {}); 48 | printf("%s", "\n===>The service stopped.\n"); 49 | 50 | // cleanup reserved socket.fds 51 | for (auto& sock : socks) 52 | sock.close(); 53 | socks.clear(); 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /tests/mcast/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set (target_name mcasttest) 2 | 3 | set (MCASTTEST_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (MCASTTEST_INC_DIR ${MCASTTEST_SRC_DIR}/../../) 5 | 6 | set (MCASTTEST_SRC ${MCASTTEST_SRC_DIR}/main.cpp) 7 | 8 | include_directories ("${MCASTTEST_SRC_DIR}") 9 | include_directories ("${MCASTTEST_INC_DIR}") 10 | 11 | add_executable (${target_name} ${MCASTTEST_SRC}) 12 | 13 | yasio_config_app_depends(${target_name}) 14 | -------------------------------------------------------------------------------- /tests/mcast2/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set (target_name mcasttest2) 2 | 3 | set (MCASTTEST2_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (MCASTTEST2_INC_DIR ${MCASTTEST2_SRC_DIR}/../../) 5 | 6 | set (MCASTTEST2_SRC ${MCASTTEST2_SRC_DIR}/main.cpp) 7 | 8 | include_directories ("${MCASTTEST2_SRC_DIR}") 9 | include_directories ("${MCASTTEST2_INC_DIR}") 10 | 11 | add_executable (${target_name} ${MCASTTEST2_SRC}) 12 | 13 | yasio_config_app_depends(${target_name}) 14 | -------------------------------------------------------------------------------- /tests/mtu/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(target_name mtutest) 2 | 3 | set (MTUTEST_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (MTUTEST_INC_DIR ${MTUTEST_SRC_DIR}/../../) 5 | 6 | set (TCPTEST_SRC ${MTUTEST_SRC_DIR}/main.cpp) 7 | 8 | 9 | include_directories ("${MTUTEST_SRC_DIR}") 10 | include_directories ("${MTUTEST_INC_DIR}") 11 | 12 | add_executable (${target_name} ${TCPTEST_SRC}) 13 | 14 | yasio_config_app_depends(${target_name}) 15 | -------------------------------------------------------------------------------- /tests/mtu/main.cpp: -------------------------------------------------------------------------------- 1 | #include "yasio/xxsocket.hpp" 2 | #include "yasio/byte_buffer.hpp" 3 | 4 | int main() 5 | { 6 | using namespace yasio; 7 | printf("Testing udp mtu ...\n"); 8 | 9 | xxsocket s; 10 | s.open(AF_INET, SOCK_DGRAM, 0); 11 | 12 | std::vector endpoints; 13 | xxsocket::resolve(endpoints, "github.com", 51122); 14 | if (endpoints.empty()) 15 | { 16 | printf("%s", "resolve host fail\n"); 17 | return ENOENT; 18 | } 19 | 20 | yasio::byte_buffer data; 21 | data.resize(65535, '1'); 22 | 23 | // set sndbuf match with data size, while, linux kenerl will double it 24 | int os_sndbuf_size = s.get_optval(SOL_SOCKET, SO_SNDBUF); 25 | printf("old sndbuf=%d\n", os_sndbuf_size); 26 | int iret = s.set_optval(SOL_SOCKET, SO_SNDBUF, data.size()); 27 | if (iret == 0) 28 | { 29 | os_sndbuf_size = s.get_optval(SOL_SOCKET, SO_SNDBUF); 30 | printf("set sockopt SNDBUF succed, sndbuf=%d\n", os_sndbuf_size); 31 | } 32 | else 33 | { 34 | auto error = xxsocket::get_last_errno(); 35 | printf("set sockopt SNDBUF fail: ec: %d, detail: %s\n", error, xxsocket::strerror(error)); 36 | } 37 | 38 | int error = 0; 39 | int nret = 0; 40 | int tries = 0; // try increase sndbuf size 41 | do 42 | { 43 | nret = s.sendto(data.data(), static_cast(data.size()), endpoints[0]); 44 | error = xxsocket::get_last_errno(); 45 | os_sndbuf_size = s.get_optval(SOL_SOCKET, SO_SNDBUF); 46 | if (nret == data.size()) 47 | { 48 | printf("[%d] send data succeed, sndbuf=%d, %zu bytes transferred\n", tries + 1, os_sndbuf_size, data.size()); 49 | #if !defined(__linux__) 50 | s.set_optval(SOL_SOCKET, SO_SNDBUF, 9216); 51 | #else 52 | s.set_optval(SOL_SOCKET, SO_SNDBUF, 9216 / 2); 53 | #endif 54 | ++tries; 55 | } 56 | else 57 | { 58 | printf("[%d] sendto data %zu fail, sndbuf=%d: ec: %d, detail: %s\n", tries + 1, data.size(), s.get_optval(SOL_SOCKET, SO_SNDBUF), error, 59 | xxsocket::strerror(error)); 60 | ++tries; 61 | if (tries == 1) 62 | { 63 | if (os_sndbuf_size <= data.size()) 64 | { 65 | s.set_optval(SOL_SOCKET, SO_SNDBUF, os_sndbuf_size + 28); 66 | } 67 | else 68 | { 69 | printf("linux kernel sndbuf %d, greater than data size: %zu\n", os_sndbuf_size, data.size()); 70 | } 71 | } 72 | else if (tries == 2) 73 | { 74 | s.set_optval(SOL_SOCKET, SO_SNDBUF, 65535); 75 | data.resize(data.size() - 28); // decrease ip and udp header size 76 | } 77 | else if (tries == 3) 78 | { 79 | data.resize(os_sndbuf_size); 80 | } 81 | else if (tries == 4) 82 | { 83 | data.resize(os_sndbuf_size - 28); 84 | } 85 | } 86 | } while (tries < 5); 87 | 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /tests/speed/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set (target_name speedtest) 2 | set (SPEEDTEST_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 3 | 4 | set (SPEEDTEST_SRC 5 | ${SPEEDTEST_SRC_DIR}/main.cpp 6 | ) 7 | 8 | set (SPEEDTEST_INC_DIR ${SPEEDTEST_SRC_DIR}/../../) 9 | 10 | include_directories ("${SPEEDTEST_SRC_DIR}") 11 | include_directories ("${SPEEDTEST_INC_DIR}") 12 | 13 | add_executable (${target_name} ${SPEEDTEST_SRC}) 14 | 15 | yasio_config_app_depends(${target_name}) 16 | -------------------------------------------------------------------------------- /tests/ssl/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(target_name ssltest) 2 | 3 | set (SSLTEST_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (SSLTEST_INC_DIR ${SSLTEST_SRC_DIR}/../../) 5 | 6 | set (SSLTEST_SRC ${SSLTEST_SRC_DIR}/main.cpp) 7 | 8 | include_directories ("${SSLTEST_SRC_DIR}") 9 | include_directories ("${SSLTEST_INC_DIR}") 10 | 11 | add_executable (${target_name} ${SSLTEST_SRC}) 12 | 13 | # link ssl stubs 14 | yasio_config_app_depends(${target_name}) 15 | -------------------------------------------------------------------------------- /tests/tcp/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(target_name tcptest) 2 | 3 | set (TCPTEST_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}) 4 | set (TCPTEST_INC_DIR ${TCPTEST_SRC_DIR}/../../) 5 | 6 | set (TCPTEST_SRC ${TCPTEST_SRC_DIR}/main.cpp) 7 | 8 | 9 | include_directories ("${TCPTEST_SRC_DIR}") 10 | include_directories ("${TCPTEST_INC_DIR}") 11 | 12 | add_executable (${target_name} ${TCPTEST_SRC}) 13 | 14 | yasio_config_app_depends(${target_name}) 15 | -------------------------------------------------------------------------------- /tools/ci.ps1: -------------------------------------------------------------------------------- 1 | # This script is only for github action ci 2 | 3 | $build_script = (Resolve-Path $PSScriptRoot/../build.ps1).Path 4 | 5 | . $build_script @args -xc '-DYASIO_ENABLE_NI=ON' -xb '--verbose' 6 | 7 | if (!$configOnly) { 8 | Write-Host "buildResult: $env:buildResult" 9 | $buildResult = ConvertFrom-Json $env:buildResult 10 | 11 | if ($buildResult.isHostTarget) { # run tests 12 | $targetOS = $buildResult.targetOS 13 | $buildDir = $buildResult.buildDir 14 | # run tests 15 | $testTable = @{ 16 | 'win32' = { 17 | $buildDir = $args[0] 18 | if ($buildResult.compilerID -ne 'gcc') { 19 | Write-Host "run icmptest on windows ..." 20 | & "$buildDir\tests\icmp\Release\icmptest.exe" $env:PING_HOST 21 | Write-Host "run mtu on windows ..." 22 | & "$buildDir\tests\mtu\Release\mtutest.exe" 23 | } 24 | }; 25 | 'linux' = { 26 | $buildDir = $args[0] 27 | Write-Host "run issue201 on linux..." 28 | & "$buildDir/tests/issue201/issue201" 29 | 30 | Write-Host "run httptest on linux..." 31 | & "$buildDir/tests/http/httptest" 32 | 33 | Write-Host "run ssltest on linux..." 34 | & "$buildDir/tests/ssl/ssltest" 35 | 36 | Write-Host "run icmp test on linux..." 37 | & "$buildDir/tests/icmp/icmptest" $env:PING_HOST 38 | 39 | Write-Host "run mtu on linux ..." 40 | & "$buildDir/tests/mtu/mtutest" 41 | }; 42 | 'osx' = { 43 | $buildDir = $args[0] 44 | if ($buildResult.targetCPU -eq $buildResult.hostCPU) { 45 | Write-Host "run test tcptest on osx ..." 46 | & "$buildDir/tests/tcp/Release/tcptest" 47 | 48 | Write-Host "run test issue384 on osx ..." 49 | & "$buildDir/tests/issue384/Release/issue384" 50 | 51 | Write-Host "run test icmp on osx ..." 52 | & "$buildDir/tests/icmp/Release/icmptest" $env:PING_HOST 53 | 54 | Write-Host "run mtu on osx ..." 55 | & "$buildDir/tests/mtu/Release/mtutest" 56 | } 57 | }; 58 | } 59 | 60 | # run test 61 | $run_test = $testTable[$targetOS] 62 | if ($run_test) { 63 | & $run_test $buildDir 64 | } 65 | } 66 | } 67 | 68 | -------------------------------------------------------------------------------- /tools/docs.ps1: -------------------------------------------------------------------------------- 1 | # gen docs, requires python3.x and install dependencies: 2 | # pip install -r docs/requirements.tx 3 | # usage: ./scripts/docs.ps1 '3.39.11:v3.39.11,3.39.12:3.39.x' 4 | $rel_str = $args[0] 5 | 6 | mkdocs --version 7 | mike --version 8 | mike delete --all 9 | 10 | Write-Host "Active versions: $rel_str" 11 | 12 | $docs_ver = $null 13 | if ($rel_str) { 14 | $rel_arr = ($rel_str -split ',') 15 | foreach($rel in $rel_arr) { 16 | # ver:tag 17 | $info = ($rel -split ':') 18 | $docs_ver = $info[0] 19 | $docs_tag = if ($info.Count -ge 2) { $info[1] } else { "v$($info[0])" } 20 | git checkout "$docs_tag" 21 | mike deploy $docs_ver 22 | } 23 | } 24 | 25 | git checkout dev 26 | mike deploy latest 27 | mike list 28 | 29 | if ($docs_ver -and ($env:GITHUB_ACTIONS -eq 'true')) { 30 | mike set-default $docs_ver --push 31 | } 32 | -------------------------------------------------------------------------------- /yasio.pc: -------------------------------------------------------------------------------- 1 | prefix=/usr/local 2 | exec_prefix=${prefix} 3 | libdir=${exec_prefix}/lib 4 | includedir=${exec_prefix}/include 5 | 6 | Name: yasio 7 | Description: A multi-platform support c++11 library with focus on asio (asynchronous socket I/O) for any client application. 8 | Version: 4.3.2 9 | Libs: -L${libdir} 10 | Cflags: -I${includedir}/yasio 11 | -------------------------------------------------------------------------------- /yasio/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | BasedOnStyle: LLVM 3 | 4 | # Allow double brackets such as std::vector>. 5 | Standard: Cpp11 6 | 7 | SortIncludes: false 8 | 9 | # Keep lines under 160 columns long. 10 | ColumnLimit: 160 11 | 12 | # Always break before braces 13 | BreakBeforeBraces: Custom 14 | BraceWrapping: 15 | AfterClass: false 16 | AfterControlStatement: true 17 | AfterEnum: true 18 | AfterFunction: true 19 | AfterNamespace: true 20 | AfterStruct: false 21 | AfterUnion: false 22 | BeforeCatch: true 23 | BeforeElse: true 24 | IndentBraces: false 25 | SplitEmptyFunction: false 26 | SplitEmptyRecord: false 27 | SplitEmptyNamespace: false 28 | 29 | # Keeps extern "C" blocks unindented. 30 | AfterExternBlock: false 31 | 32 | # Indent case labels. 33 | IndentCaseLabels: true 34 | 35 | # Right-align pointers and references 36 | PointerAlignment: Left 37 | 38 | # ANGLE likes to align things as much as possible. 39 | AlignOperands: true 40 | AlignConsecutiveAssignments: true 41 | 42 | # Use 2 space negative offset for access modifiers 43 | AccessModifierOffset: -2 44 | 45 | # TODO(jmadill): Decide if we want this on. Doesn't have an "all or none" mode. 46 | AllowShortCaseLabelsOnASingleLine: false 47 | 48 | # Useful for spacing out functions in classes 49 | KeepEmptyLinesAtTheStartOfBlocks: true 50 | 51 | # Indent nested PP directives. 52 | IndentPPDirectives: AfterHash 53 | 54 | AlwaysBreakTemplateDeclarations: Yes 55 | 56 | AlignEscapedNewlines: Left 57 | -------------------------------------------------------------------------------- /yasio/bindings/lua/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(target_name plainlua) 2 | 3 | get_filename_component(LUA_SRC_PATH ../../../3rdparty/lua ABSOLUTE) 4 | message(STATUS "LUA_SRC_PATH=${LUA_SRC_PATH}") 5 | 6 | file(GLOB LUA_SRC_FILES 7 | "${LUA_SRC_PATH}/*.c") 8 | 9 | list(REMOVE_ITEM LUA_SRC_FILES "${LUA_SRC_PATH}/lua.c") 10 | list(REMOVE_ITEM LUA_SRC_FILES "${LUA_SRC_PATH}/onelua.c") 11 | 12 | add_library(${target_name} ${LUA_SRC_FILES}) 13 | 14 | # fix default lua_newuserdata can't return aligned pointer properly 15 | # MSVC max_align_t=double, lua already handle properly 16 | if (NOT MSVC) 17 | # see also: https://github.com/llvm/llvm-project/blob/master/clang/lib/Headers/__stddef_max_align_t.h 18 | if(APPLE) 19 | target_compile_definitions (${target_name} PUBLIC "LUAI_USER_ALIGNMENT_T=long double") 20 | else() 21 | target_compile_definitions (${target_name} PUBLIC LUAI_USER_ALIGNMENT_T=max_align_t) 22 | endif() 23 | endif() 24 | 25 | if(MSVC AND BUILD_SHARED_LIBS) 26 | target_compile_definitions(${target_name} 27 | PUBLIC LUA_BUILD_AS_DLL=1 28 | # PUBLIC LUA_CORE=1 29 | ) 30 | endif() 31 | 32 | target_include_directories(${target_name} 33 | INTERFACE ${LUA_SRC_PATH} 34 | INTERFACE ${CMAKE_CURRENT_SOURCE_DIR} 35 | ) 36 | -------------------------------------------------------------------------------- /yasio/bindings/lua/lua.hpp: -------------------------------------------------------------------------------- 1 | // lua.hpp 2 | // Lua header files for C++ 3 | // <> not supplied automatically because Lua also compiles as C++ 4 | 5 | extern "C" { 6 | #include "lua.h" 7 | #include "lualib.h" 8 | #include "lauxlib.h" 9 | } 10 | -------------------------------------------------------------------------------- /yasio/bindings/luajit/lua.hpp: -------------------------------------------------------------------------------- 1 | // C++ wrapper for LuaJIT header files. 2 | 3 | extern "C" { 4 | #include "lua.h" 5 | #include "lauxlib.h" 6 | #include "lualib.h" 7 | #include "luajit.h" 8 | } 9 | 10 | -------------------------------------------------------------------------------- /yasio/bindings/lyasio.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | #ifndef YASIO__LUA_HPP 29 | #define YASIO__LUA_HPP 30 | 31 | #if !defined(YASIO_LUA_ENABLE_GLOBAL) 32 | # define YASIO_LUA_ENABLE_GLOBAL 0 33 | #endif 34 | 35 | #if defined(_WINDLL) 36 | # if defined(LUA_LIB) 37 | # define YASIO_LUA_API __declspec(dllexport) 38 | # else 39 | # define YASIO_LUA_API __declspec(dllimport) 40 | # endif 41 | #else 42 | # define YASIO_LUA_API 43 | #endif 44 | 45 | #if defined(__cplusplus) 46 | extern "C" { 47 | #endif 48 | #if !defined(NS_SLUA) 49 | struct lua_State; 50 | #endif 51 | YASIO_LUA_API int luaopen_yasio(lua_State* L); 52 | YASIO_LUA_API void luaregister_yasio(lua_State* L); // register yasio to package.preload 53 | #if defined(__cplusplus) 54 | } 55 | #endif 56 | 57 | #endif 58 | -------------------------------------------------------------------------------- /yasio/bindings/yasio_axlua.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | #ifndef YASIO__CCLUA_HPP 29 | #define YASIO__CCLUA_HPP 30 | #include "lyasio.hpp" 31 | 32 | #if defined(__cplusplus) 33 | extern "C" { 34 | #endif 35 | YASIO_LUA_API int luaopen_yasio_axlua(lua_State* L); 36 | #if defined(__cplusplus) 37 | } 38 | 39 | namespace lyasio 40 | { 41 | namespace stimer 42 | { 43 | // !IMPORTANT: You should call function this when you want restart script Virtual Machine for some 44 | // purpose. 45 | YASIO_LUA_API void clear(); 46 | } // namespace stimer 47 | } // namespace lyasio 48 | 49 | #endif 50 | 51 | #endif 52 | -------------------------------------------------------------------------------- /yasio/bindings/yasio_jsb.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | #ifndef YASIO__JSB_HPP 29 | #define YASIO__JSB_HPP 30 | #include "jsapi.h" 31 | 32 | void jsb_register_yasio(JSContext* cx, JS::HandleObject global); 33 | 34 | namespace yasio_jsb 35 | { 36 | namespace stimer 37 | { 38 | // !IMPORTANT: You should call this function when you want restart script Virtual Machine for some 39 | // purpose. 40 | void clear(); 41 | } // namespace stimer 42 | } // namespace yasio_jsb 43 | 44 | #endif 45 | -------------------------------------------------------------------------------- /yasio/bindings/yasio_jsb20.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | #ifndef YASIO__JSB20_HPP 29 | #define YASIO__JSB20_HPP 30 | namespace se 31 | { 32 | class Object; 33 | } 34 | 35 | bool jsb_register_yasio(se::Object* obj); 36 | 37 | namespace yasio_jsb 38 | { 39 | namespace stimer 40 | { 41 | // !IMPORTANT: You should call this function when you want restart script Virtual Machine for some 42 | // purpose. 43 | void clear(); 44 | } // namespace stimer 45 | } // namespace yasio_jsb 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /yasio/bindings/yasio_sol.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | Copyright (c) 2012-2025 HALX99 8 | Permission is hereby granted, free of charge, to any person obtaining a copy 9 | of this software and associated documentation files (the "Software"), to deal 10 | in the Software without restriction, including without limitation the rights 11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | copies of the Software, and to permit persons to whom the Software is 13 | furnished to do so, subject to the following conditions: 14 | The above copyright notice and this permission notice shall be included in all 15 | copies or substantial portions of the Software. 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | */ 24 | #ifndef YASIO__SOL_HPP 25 | #define YASIO__SOL_HPP 26 | #include "yasio/impl/fp16.hpp" 27 | 28 | #if YASIO__HAS_CXX17 29 | # include "sol/sol.hpp" // sol2-3.x 30 | #else 31 | # include "sol2/sol.hpp" // sol2-2.x 32 | #endif 33 | 34 | // use cxx17::string_view workaround with std::string_view 35 | #if !YASIO__HAS_CXX17 36 | namespace sol 37 | { 38 | namespace stack 39 | { 40 | template <> 41 | struct pusher { 42 | static int push(lua_State* L, const cxx17::string_view& str) 43 | { 44 | lua_pushlstring(L, !str.empty() ? str.c_str() : "", str.length()); 45 | return 1; 46 | } 47 | }; 48 | template <> 49 | struct getter { 50 | static cxx17::string_view get(lua_State* L, int index, record& tracking) 51 | { 52 | tracking.use(1); // THIS IS THE ONLY BIT THAT CHANGES 53 | size_t len = 0; 54 | const char* s = lua_tolstring(L, index, &len); 55 | return cxx17::string_view(s, len); 56 | } 57 | }; 58 | } // namespace stack 59 | template <> 60 | struct lua_type_of : std::integral_constant {}; 61 | } // namespace sol 62 | #endif 63 | 64 | #if defined(YASIO_ENABLE_HALF_FLOAT) 65 | namespace sol 66 | { 67 | namespace stack 68 | { 69 | # if YASIO__HAS_CXX17 // sol2-3.x pusher/getter 70 | template <> 71 | struct unqualified_pusher { 72 | static int push(lua_State* L, const fp16_t& value) 73 | { 74 | lua_pushnumber(L, static_cast(value)); 75 | return 1; 76 | } 77 | }; 78 | template <> 79 | struct unqualified_getter { 80 | static fp16_t get(lua_State* L, int index, record& tracking) 81 | { 82 | tracking.use(1); // THIS IS THE ONLY BIT THAT CHANGES 83 | return fp16_t{static_cast(lua_tonumber(L, index))}; 84 | } 85 | }; 86 | # else // sol2-2.x pusher/getter 87 | template <> 88 | struct pusher { 89 | static int push(lua_State* L, const fp16_t& value) 90 | { 91 | lua_pushnumber(L, static_cast(value)); 92 | return 1; 93 | } 94 | }; 95 | template <> 96 | struct getter { 97 | static fp16_t get(lua_State* L, int index, record& tracking) 98 | { 99 | tracking.use(1); // THIS IS THE ONLY BIT THAT CHANGES 100 | return fp16_t{static_cast(lua_tonumber(L, index))}; 101 | } 102 | }; 103 | # endif // YASIO__HAS_CXX17 104 | } // namespace stack 105 | template <> 106 | struct lua_type_of : std::integral_constant {}; 107 | } // namespace sol 108 | #endif // YASIO_ENABLE_HALF_FLOAT 109 | 110 | #endif // YASIO__SOL_HPP 111 | -------------------------------------------------------------------------------- /yasio/byte_buffer.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | #ifndef YASIO__BYTE_BUFFER_HPP 29 | #define YASIO__BYTE_BUFFER_HPP 30 | #include "yasio/pod_vector.hpp" 31 | 32 | namespace yasio 33 | { 34 | 35 | template , enable_if_t::value, int> = 0> 36 | using basic_byte_buffer = array_buffer<_Ty, _Alloc>; 37 | 38 | using sbyte_buffer = basic_byte_buffer; 39 | using byte_buffer = basic_byte_buffer; 40 | 41 | } // namespace yasio 42 | #endif 43 | -------------------------------------------------------------------------------- /yasio/errc.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | The above copyright notice and this permission notice shall be included in all 17 | copies or substantial portions of the Software. 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | SOFTWARE. 25 | */ 26 | #ifndef YAISO__ERRC_HPP 27 | #define YAISO__ERRC_HPP 28 | 29 | namespace yasio 30 | { 31 | namespace errc 32 | { 33 | enum 34 | { 35 | no_error = 0, // No error. 36 | read_timeout = -28, // The remote host did not respond after a period of time. 37 | invalid_packet = -27, // Invalid packet. 38 | resolve_host_failed = -26, // Resolve host failed. 39 | no_available_address = -25, // No available address to connect. 40 | shutdown_by_localhost = -24, // Local shutdown the connection. 41 | ssl_handshake_failed = -23, // SSL handshake failed. 42 | ssl_write_failed = -22, // SSL write failed. 43 | ssl_read_failed = -21, // SSL read failed. 44 | eof = -20, // end of file. 45 | }; 46 | } 47 | } // namespace yasio 48 | 49 | #endif 50 | -------------------------------------------------------------------------------- /yasio/file.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | 29 | #pragma once 30 | 31 | #include "yasio/string.hpp" 32 | #include "yasio/string_view.hpp" 33 | #include 34 | 35 | namespace yasio 36 | { 37 | inline yasio::string read_text_file(cxx17::string_view file_path) 38 | { 39 | std::ifstream fin(file_path.data(), std::ios_base::binary); 40 | if (fin.is_open()) 41 | { 42 | fin.seekg(std::ios_base::end); 43 | auto n = static_cast(fin.tellg()); 44 | if (n > 0) 45 | { 46 | yasio::string ret; 47 | ret.resize_and_overwrite(n, [&fin](char* out, size_t outlen) { 48 | fin.seekg(std::ios_base::beg); 49 | fin.read(out, outlen); 50 | return outlen; 51 | }); 52 | return ret; 53 | } 54 | } 55 | return yasio::string{}; 56 | } 57 | } // namespace yasio 58 | -------------------------------------------------------------------------------- /yasio/impl/ares.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | #ifndef YASIO__ARES_HPP 29 | #define YASIO__ARES_HPP 30 | 31 | extern "C" { 32 | #include "ares.h" 33 | extern void (*ares_free)(void* ptr); 34 | } 35 | 36 | #if defined(__ANDROID__) 37 | # include "yasio/platform/yasio_jni.hpp" 38 | #endif 39 | 40 | #endif 41 | -------------------------------------------------------------------------------- /yasio/impl/fp16.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | The above copyright notice and this permission notice shall be included in all 17 | copies or substantial portions of the Software. 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | SOFTWARE. 25 | */ 26 | #ifndef YASIO__FP16_HPP 27 | #define YASIO__FP16_HPP 28 | #include "yasio/config.hpp" 29 | 30 | #if defined(YASIO_ENABLE_HALF_FLOAT) 31 | // Includes IEEE 754 16-bit half-precision floating-point library 32 | # include "half/half.hpp" 33 | typedef half_float::half fp16_t; 34 | #endif 35 | 36 | #endif 37 | -------------------------------------------------------------------------------- /yasio/impl/pipe_select_interrupter.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | // 6 | // 7 | // Copyright (c) 2012-2025 HALX99 (halx99 at live dot com) 8 | // Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com) 9 | // Copyright (c) 2008 Roelof Naude (roelof.naude at gmail dot com) 10 | // 11 | // Distributed under the Boost Software License, Version 1.0. (See accompanying 12 | // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 13 | // 14 | // see also: https://github.com/chriskohlhoff/asio 15 | // 16 | #ifndef YASIO__PIPE_SELECT_INTERRUPTER_HPP 17 | #define YASIO__PIPE_SELECT_INTERRUPTER_HPP 18 | 19 | #include "yasio/compiler/feature_test.hpp" 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | namespace yasio 27 | { 28 | YASIO__NS_INLINE 29 | namespace inet 30 | { 31 | class pipe_select_interrupter { 32 | public: 33 | // Constructor. 34 | inline pipe_select_interrupter() { open_descriptors(); } 35 | 36 | // Destructor. 37 | inline ~pipe_select_interrupter() { close_descriptors(); } 38 | 39 | // Recreate the interrupter's descriptors. Used after a fork. 40 | inline void recreate() 41 | { 42 | close_descriptors(); 43 | 44 | write_descriptor_ = -1; 45 | read_descriptor_ = -1; 46 | 47 | open_descriptors(); 48 | } 49 | 50 | // Interrupt the select call. 51 | inline void interrupt() 52 | { 53 | char byte = 0; 54 | auto result = ::write(write_descriptor_, &byte, 1); 55 | (void)result; 56 | } 57 | 58 | // Reset the select interrupter. Returns true if the reset was successful. 59 | inline bool reset() 60 | { 61 | char data[1024]; 62 | for (;;) 63 | { 64 | // Clear all data from the pipe. 65 | int bytes_read = static_cast(::read(read_descriptor_, data, sizeof(data))); 66 | if (bytes_read == sizeof(data)) 67 | continue; 68 | if (bytes_read > 0) 69 | return true; 70 | if (bytes_read == 0) 71 | return false; 72 | int ec = errno; 73 | if (ec == EINTR) 74 | continue; 75 | return (ec == EWOULDBLOCK || ec == EAGAIN); 76 | } 77 | } 78 | 79 | // Get the read descriptor to be passed to select. 80 | int read_descriptor() const { return read_descriptor_; } 81 | 82 | private: 83 | // Open the descriptors. Throws on error. 84 | inline void open_descriptors() 85 | { 86 | int pipe_fds[2]; 87 | if (pipe(pipe_fds) == 0) 88 | { 89 | read_descriptor_ = pipe_fds[0]; 90 | ::fcntl(read_descriptor_, F_SETFL, O_NONBLOCK); 91 | write_descriptor_ = pipe_fds[1]; 92 | ::fcntl(write_descriptor_, F_SETFL, O_NONBLOCK); 93 | 94 | #if defined(FD_CLOEXEC) 95 | ::fcntl(read_descriptor_, F_SETFD, FD_CLOEXEC); 96 | ::fcntl(write_descriptor_, F_SETFD, FD_CLOEXEC); 97 | #endif // defined(FD_CLOEXEC) 98 | } 99 | else 100 | yasio__throw_error(errno, "pipe_select_interrupter"); 101 | } 102 | 103 | // Close the descriptors. 104 | inline void close_descriptors() 105 | { 106 | if (read_descriptor_ != -1) 107 | ::close(read_descriptor_); 108 | if (write_descriptor_ != -1) 109 | ::close(write_descriptor_); 110 | } 111 | 112 | // The read end of a connection used to interrupt the select call. This file 113 | // descriptor is passed to select such that when it is time to stop, a single 114 | // byte will be written on the other end of the connection and this 115 | // descriptor will become readable. 116 | int read_descriptor_; 117 | 118 | // The write end of a connection used to interrupt the select call. A single 119 | // byte may be written to this to wake up the select which is waiting for the 120 | // other end to become readable. 121 | int write_descriptor_; 122 | }; 123 | 124 | } // namespace inet 125 | } // namespace yasio 126 | 127 | #endif // YASIO__PIPE_SELECT_INTERRUPTER_HPP 128 | -------------------------------------------------------------------------------- /yasio/impl/poll_io_watcher.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | // 6 | // Copyright (c) 2012-2025 HALX99 (halx99 at live dot com) 7 | #ifndef YASIO__POLL_IO_WATCHER_HPP 8 | #define YASIO__POLL_IO_WATCHER_HPP 9 | #include "yasio/pod_vector.hpp" 10 | #include "yasio/impl/socket.hpp" 11 | #include "yasio/impl/select_interrupter.hpp" 12 | 13 | namespace yasio 14 | { 15 | YASIO__NS_INLINE 16 | namespace inet 17 | { 18 | class poll_io_watcher { 19 | public: 20 | poll_io_watcher() { this->mod_event(interrupter_.read_descriptor(), socket_event::read, 0); } 21 | 22 | void mod_event(socket_native_type fd, int add_events, int remove_events) 23 | { 24 | pollfd_mod(this->events_, fd, to_underlying_events(add_events), to_underlying_events(remove_events)); 25 | } 26 | 27 | int poll_io(int64_t waitd_us) 28 | { 29 | revents_ = this->events_; 30 | #if YASIO__HAS_PPOLL 31 | timespec timeout = {(decltype(timespec::tv_sec))(waitd_us / std::micro::den), 32 | (decltype(timespec::tv_nsec))((waitd_us % std::micro::den) * std::milli::den)}; 33 | int num_events = ::ppoll(this->revents_.data(), static_cast(this->revents_.size()), &timeout, nullptr); 34 | #else 35 | int num_events = ::poll(this->revents_.data(), static_cast(this->revents_.size()), static_cast(waitd_us / std::milli::den)); 36 | #endif 37 | if (num_events > 0 && is_ready(this->interrupter_.read_descriptor(), socket_event::read)) 38 | { 39 | if (!interrupter_.reset()) 40 | interrupter_.recreate(); 41 | --num_events; 42 | } 43 | return num_events; 44 | } 45 | 46 | void wakeup() { interrupter_.interrupt(); } 47 | 48 | int is_ready(socket_native_type fd, int events) const 49 | { 50 | int underlying_events = 0; 51 | if (events & socket_event::read) 52 | underlying_events |= POLLIN; 53 | if (events & socket_event::write) 54 | underlying_events |= POLLOUT; 55 | if (events & socket_event::error) 56 | underlying_events |= (POLLERR | POLLHUP | POLLNVAL); 57 | auto it = std::find_if(this->revents_.begin(), this->revents_.end(), [fd](const pollfd& pfd) { return pfd.fd == fd; }); 58 | return it != this->revents_.end() ? (it->revents & underlying_events) : 0; 59 | } 60 | 61 | int max_descriptor() const { return -1; } 62 | 63 | protected: 64 | int to_underlying_events(int events) 65 | { 66 | int underlying_events = 0; 67 | if (events) 68 | { 69 | if (yasio__testbits(events, socket_event::read)) 70 | underlying_events |= POLLIN; 71 | 72 | if (yasio__testbits(events, socket_event::write)) 73 | underlying_events |= POLLOUT; 74 | 75 | if (yasio__testbits(events, socket_event::error)) 76 | underlying_events |= POLLERR; 77 | } 78 | return underlying_events; 79 | } 80 | static void pollfd_mod(yasio::pod_vector& fdset, socket_native_type fd, int add_events, int remove_events) 81 | { 82 | auto it = std::find_if(fdset.begin(), fdset.end(), [fd](const pollfd& pfd) { return pfd.fd == fd; }); 83 | if (it != fdset.end()) 84 | { 85 | it->events |= add_events; 86 | it->events &= ~remove_events; 87 | if (it->events == 0) 88 | fdset.erase(it); 89 | } 90 | else 91 | { 92 | auto events = add_events & ~remove_events; 93 | if (events) 94 | fdset.emplace_back(fd, static_cast(events), static_cast(0)); 95 | } 96 | } 97 | 98 | protected: 99 | yasio::pod_vector events_; 100 | yasio::pod_vector revents_; 101 | 102 | select_interrupter interrupter_; 103 | }; 104 | } // namespace inet 105 | } // namespace yasio 106 | #endif 107 | -------------------------------------------------------------------------------- /yasio/impl/select_interrupter.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | // 6 | // Copyright (c) 2012-2025 HALX99 (halx99 at live dot com) 7 | // Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com) 8 | // 9 | // Distributed under the Boost Software License, Version 1.0. (See accompanying 10 | // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 11 | // 12 | // see also: https://github.com/chriskohlhoff/asio 13 | // 14 | #ifndef YASIO__SELECT_INTERRUPTER_HPP 15 | #define YASIO__SELECT_INTERRUPTER_HPP 16 | 17 | #include "yasio/compiler/feature_test.hpp" 18 | 19 | #if defined(_WIN32) 20 | # include "yasio/impl/socket_select_interrupter.hpp" 21 | #elif defined(__linux__) 22 | # include "yasio/impl/eventfd_select_interrupter.hpp" 23 | #else 24 | # include "yasio/impl/pipe_select_interrupter.hpp" 25 | #endif 26 | 27 | namespace yasio 28 | { 29 | YASIO__NS_INLINE 30 | namespace inet 31 | { 32 | 33 | #if defined(_WIN32) 34 | typedef socket_select_interrupter select_interrupter; 35 | #elif defined(__linux__) 36 | typedef eventfd_select_interrupter select_interrupter; 37 | #else 38 | typedef pipe_select_interrupter select_interrupter; 39 | #endif 40 | 41 | } // namespace inet 42 | } // namespace yasio 43 | 44 | #endif // YASIO__SELECT_INTERRUPTER_HPP 45 | -------------------------------------------------------------------------------- /yasio/impl/select_io_watcher.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | // 6 | // Copyright (c) 2012-2025 HALX99 (halx99 at live dot com) 7 | #ifndef YASIO__SELECT_IO_WATCHER_HPP 8 | #define YASIO__SELECT_IO_WATCHER_HPP 9 | #include 10 | #include 11 | #include "yasio/impl/socket.hpp" 12 | #include "yasio/impl/select_interrupter.hpp" 13 | 14 | namespace yasio 15 | { 16 | YASIO__NS_INLINE 17 | namespace inet 18 | { 19 | class select_io_watcher { 20 | public: 21 | select_io_watcher() 22 | { 23 | FD_ZERO(&events_[read_op]); 24 | FD_ZERO(&events_[write_op]); 25 | FD_ZERO(&events_[except_op]); 26 | this->mod_event(interrupter_.read_descriptor(), socket_event::read, 0); 27 | } 28 | 29 | void mod_event(socket_native_type fd, int add_events, int remove_events) 30 | { 31 | if (add_events) 32 | { 33 | if (yasio__testbits(add_events, socket_event::read)) 34 | FD_SET(fd, &(events_[read_op])); 35 | 36 | if (yasio__testbits(add_events, socket_event::write)) 37 | FD_SET(fd, &(events_[write_op])); 38 | 39 | if (yasio__testbits(add_events, socket_event::error)) 40 | FD_SET(fd, &(events_[except_op])); 41 | 42 | if (max_descriptor_ < static_cast(fd) + 1) 43 | max_descriptor_ = static_cast(fd) + 1; 44 | } 45 | 46 | if (remove_events) 47 | { 48 | if (yasio__testbits(remove_events, socket_event::read)) 49 | FD_CLR(fd, &(events_[read_op])); 50 | 51 | if (yasio__testbits(remove_events, socket_event::write)) 52 | FD_CLR(fd, &(events_[write_op])); 53 | 54 | if (yasio__testbits(remove_events, socket_event::error)) 55 | FD_CLR(fd, &(events_[except_op])); 56 | } 57 | } 58 | 59 | int poll_io(int64_t waitd_us) 60 | { 61 | ::memcpy(this->revents_, events_, sizeof(revents_)); 62 | timeval timeout = {(decltype(timeval::tv_sec))(waitd_us / std::micro::den), (decltype(timeval::tv_usec))(waitd_us % std::micro::den)}; 63 | int num_events = ::select(this->max_descriptor_, &(revents_[read_op]), &(revents_[write_op]), nullptr, &timeout); 64 | if (num_events > 0 && is_ready(this->interrupter_.read_descriptor(), socket_event::read)) 65 | { 66 | if (!interrupter_.reset()) 67 | interrupter_.recreate(); 68 | --num_events; 69 | } 70 | return num_events; 71 | } 72 | 73 | void wakeup() { interrupter_.interrupt(); } 74 | 75 | int is_ready(socket_native_type fd, int events) const 76 | { 77 | int retval = 0; 78 | if (events & socket_event::read) 79 | retval |= FD_ISSET(fd, &revents_[read_op]); 80 | if (events & socket_event::write) 81 | retval |= FD_ISSET(fd, &revents_[write_op]); 82 | if (events & socket_event::error) 83 | retval |= FD_ISSET(fd, &revents_[except_op]); 84 | return retval; 85 | } 86 | 87 | int max_descriptor() const { return max_descriptor_; } 88 | 89 | protected: 90 | enum 91 | { 92 | read_op, 93 | write_op, 94 | except_op, 95 | max_ops, 96 | }; 97 | fd_set events_[max_ops]; 98 | fd_set revents_[max_ops]; 99 | int max_descriptor_ = 0; 100 | 101 | select_interrupter interrupter_; 102 | }; 103 | } // namespace inet 104 | } // namespace yasio 105 | #endif 106 | -------------------------------------------------------------------------------- /yasio/io_watcher.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | // 6 | // 7 | // Copyright (c) 2012-2025 HALX99 (halx99 at live dot com) 8 | 9 | #pragma once 10 | 11 | #include "yasio/config.hpp" 12 | 13 | #if YASIO__HAS_KQUEUE && defined(YASIO_ENABLE_HPERF_IO) 14 | # include "yasio/impl/kqueue_io_watcher.hpp" 15 | #elif YASIO__HAS_EPOLL && defined(YASIO_ENABLE_HPERF_IO) 16 | # include "yasio/impl/epoll_io_watcher.hpp" 17 | #elif YASIO__HAS_EVPORT && defined(YASIO_ENABLE_HPERF_IO) 18 | # include "yasio/impl/evport_io_watcher.hpp" 19 | #elif !defined(YASIO_DISABLE_POLL) 20 | # include "yasio/impl/poll_io_watcher.hpp" 21 | #else 22 | # include "yasio/impl/select_io_watcher.hpp" 23 | #endif 24 | 25 | namespace yasio 26 | { 27 | YASIO__NS_INLINE 28 | namespace inet 29 | { 30 | #if defined(YASIO__KQUEUE_IO_WATCHER_HPP) 31 | using io_watcher = kqueue_io_watcher; 32 | #elif defined(YASIO__EPOLL_IO_WATCHER_HPP) 33 | using io_watcher = epoll_io_watcher; 34 | #elif defined(YASIO__EVPORT_IO_WATCHER_HPP) 35 | using io_watcher = evport_io_watcher; 36 | #elif !defined(YASIO_DISABLE_POLL) 37 | using io_watcher = poll_io_watcher; 38 | #else 39 | using io_watcher = select_io_watcher; 40 | #endif 41 | } // namespace inet 42 | } // namespace yasio 43 | -------------------------------------------------------------------------------- /yasio/logging.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | #ifndef YASIO__LOGGING_HPP 29 | #define YASIO__LOGGING_HPP 30 | #include "yasio/strfmt.hpp" 31 | 32 | #if defined(__EMSCRIPTEN__) 33 | # include 34 | # include 35 | inline void yasio__print(std::string&& message) { ::write(::fileno(stdout), message.c_str(), message.size()); } 36 | # define YASIO_LOG_TAG(tag, format, ...) yasio__print(::yasio::strfmt(127, (tag format), ##__VA_ARGS__)) 37 | #elif defined(_WIN32) 38 | # define YASIO_LOG_TAG(tag, format, ...) OutputDebugStringA(::yasio::strfmt(127, (tag format "\n"), ##__VA_ARGS__).c_str()) 39 | #elif defined(ANDROID) || defined(__ANDROID__) 40 | # include 41 | # include 42 | # define YASIO_LOG_TAG(tag, format, ...) __android_log_print(ANDROID_LOG_INFO, "yasio", (tag format), ##__VA_ARGS__) 43 | #elif defined(__OHOS__) 44 | # include 45 | # define YASIO_LOG_TAG(tag, format, ...) OH_LOG_INFO(LOG_APP, (tag format "\n"), ##__VA_ARGS__) 46 | #else 47 | # define YASIO_LOG_TAG(tag, format, ...) printf((tag format "\n"), ##__VA_ARGS__) 48 | #endif 49 | 50 | #define YASIO_LOG(format, ...) YASIO_LOG_TAG("[yasio]", format, ##__VA_ARGS__) 51 | 52 | #if !defined(YASIO_VERBOSE_LOG) 53 | # define YASIO_LOGV(fmt, ...) (void)0 54 | #else 55 | # define YASIO_LOGV YASIO_LOG 56 | #endif 57 | 58 | #endif 59 | -------------------------------------------------------------------------------- /yasio/memory.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | #ifndef YASIO__MEMORY 29 | #define YASIO__MEMORY 30 | #include 31 | 32 | #include "yasio/compiler/feature_test.hpp" 33 | 34 | /// The make_unique workaround on c++11 35 | #if !YASIO__HAS_CXX14 36 | namespace cxx14 37 | { 38 | template std::unique_ptr<_Ty> make_unique(_Args&&... args) 39 | { 40 | return std::unique_ptr<_Ty>(new _Ty(std::forward<_Args>(args)...)); 41 | } 42 | } // namespace cxx14 43 | #endif 44 | 45 | #endif 46 | -------------------------------------------------------------------------------- /yasio/platform/java/com/simdsoft/yasio/AppGlobals.java: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | package com.simdsoft.yasio; 29 | 30 | import android.content.Context; 31 | 32 | public final class AppGlobals { 33 | private static Context sApplicationContext = null; 34 | 35 | public static void init(Context ctx) { 36 | sApplicationContext = ctx.getApplicationContext(); 37 | } 38 | 39 | @SuppressWarnings("unused") 40 | public static Context getApplicationContext() { 41 | return sApplicationContext; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /yasio/platform/yasio_jni.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | Copyright (c) 2012-2025 HALX99 8 | Permission is hereby granted, free of charge, to any person obtaining a copy 9 | of this software and associated documentation files (the "Software"), to deal 10 | in the Software without restriction, including without limitation the rights 11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | copies of the Software, and to permit persons to whom the Software is 13 | furnished to do so, subject to the following conditions: 14 | The above copyright notice and this permission notice shall be included in all 15 | copies or substantial portions of the Software. 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | */ 24 | #ifndef YASIO__JNI_HPP 25 | #define YASIO__JNI_HPP 26 | 27 | extern "C" void yasio__jni_init(void* vm, void* env); 28 | extern "C" int yasio__jni_onload(void* vm, void* reserved); 29 | 30 | extern "C" int yasio__ares_init_android(); 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /yasio/platform/yasio_unreal.cpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | Copyright (c) 2012-2025 HALX99 8 | Permission is hereby granted, free of charge, to any person obtaining a copy 9 | of this software and associated documentation files (the "Software"), to deal 10 | in the Software without restriction, including without limitation the rights 11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | copies of the Software, and to permit persons to whom the Software is 13 | furnished to do so, subject to the following conditions: 14 | The above copyright notice and this permission notice shall be included in all 15 | copies or substantial portions of the Software. 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | */ 24 | 25 | #include "Modules/ModuleManager.h" 26 | 27 | #include "yasio/yasio.hpp" 28 | 29 | using namespace yasio; 30 | 31 | DECLARE_LOG_CATEGORY_EXTERN(yasio_ue, Log, All); 32 | DEFINE_LOG_CATEGORY(yasio_ue); 33 | 34 | YASIO_API void yasio_unreal_init() 35 | { 36 | print_fn2_t log_cb = [](int level, const char* msg) { 37 | FString text(msg); 38 | const TCHAR* tstr = *text; 39 | UE_LOG(yasio_ue, Log, TEXT("%s"), tstr); 40 | }; 41 | io_service::init_globals(log_cb); 42 | } 43 | YASIO_API void yasio_unreal_cleanup() 44 | { 45 | io_service::cleanup_globals(); 46 | } 47 | 48 | #if defined(YASIO_INSIDE_UNREAL) && (YASIO_BUILD_SHARED_LIBS) 49 | class yasio_unreal_module : public IModuleInterface 50 | { 51 | public: 52 | /** IModuleInterface implementation */ 53 | void StartupModule() override {} 54 | void ShutdownModule() override {} 55 | }; 56 | IMPLEMENT_MODULE(yasio_unreal_module, yasio) 57 | #endif 58 | -------------------------------------------------------------------------------- /yasio/platform/yasio_unreal.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | Copyright (c) 2012-2025 HALX99 8 | Permission is hereby granted, free of charge, to any person obtaining a copy 9 | of this software and associated documentation files (the "Software"), to deal 10 | in the Software without restriction, including without limitation the rights 11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | copies of the Software, and to permit persons to whom the Software is 13 | furnished to do so, subject to the following conditions: 14 | The above copyright notice and this permission notice shall be included in all 15 | copies or substantial portions of the Software. 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | */ 24 | #ifndef YASIO__UNREAL_HPP 25 | #define YASIO__UNREAL_HPP 26 | 27 | #include "yasio/config.hpp" 28 | 29 | YASIO_API void yasio_unreal_init(); 30 | YASIO_API void yasio_unreal_cleanup(); 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /yasio/split.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | 29 | /* 30 | * The standard split stub of yasio: 31 | * The pred callback prototype: [](CStr first, CStr last) ->bool{ return true; } 32 | * returns: 33 | * true: want continue split 34 | * false: abort split 35 | * 36 | */ 37 | 38 | #pragma once 39 | 40 | #include "yasio/string_view.hpp" 41 | #include 42 | 43 | #if defined(_MSC_VER) 44 | # pragma warning(push) 45 | # pragma warning(disable : 4706) 46 | #endif 47 | 48 | namespace yasio 49 | { 50 | template 51 | inline void split_if(_CStr s, typename std::remove_pointer<_CStr>::type delim, _Pred&& pred) 52 | { 53 | auto _Start = s; // the start of every string 54 | auto _Ptr = s; // source string iterator 55 | while ((_Ptr = strchr(_Ptr, delim))) 56 | { 57 | if (_Start <= _Ptr && !pred(_Start, _Ptr)) 58 | return; 59 | _Start = _Ptr + 1; 60 | ++_Ptr; 61 | } 62 | pred(_Start, nullptr); // last one, end is nullptr 63 | } 64 | 65 | template 66 | inline void split_if_n(_CStr s, size_t slen, typename std::remove_pointer<_CStr>::type delim, _Pred&& pred) 67 | { 68 | auto _Start = s; // the start of every string 69 | auto _Ptr = s; // source string iterator 70 | auto _End = s + slen; 71 | while ((_Ptr = strchr(_Ptr, delim))) 72 | { 73 | if (_Ptr >= _End) 74 | break; 75 | 76 | if (_Start <= _Ptr && !pred(_Start, _Ptr)) 77 | return; 78 | _Start = _Ptr + 1; 79 | ++_Ptr; 80 | } 81 | if (_Start <= _End) 82 | pred(_Start, _End); 83 | } 84 | 85 | template 86 | inline void split(_CStr s, typename std::remove_pointer<_CStr>::type delim, _Func&& func) 87 | { 88 | split_if(s, delim, [func](_CStr first, _CStr last) { 89 | func(first, last); 90 | return true; 91 | }); 92 | } 93 | 94 | template 95 | inline void split_n(_CStr s, size_t slen, typename std::remove_pointer<_CStr>::type delim, _Func&& func) 96 | { 97 | split_if_n(s, slen, delim, [func](_CStr first, _CStr last) { 98 | func(first, last); 99 | return true; 100 | }); 101 | } 102 | 103 | struct split_term { 104 | split_term(char* end) 105 | { 106 | if (end) 107 | { 108 | this->val_ = *end; 109 | *end = '\0'; 110 | this->end_ = end; 111 | } 112 | } 113 | ~split_term() 114 | { 115 | if (this->end_) 116 | *this->end_ = this->val_; 117 | } 118 | 119 | private: 120 | char* end_ = nullptr; 121 | char val_ = '\0'; 122 | }; 123 | } // namespace yasio 124 | 125 | #if defined(_MSC_VER) 126 | # pragma warning(pop) 127 | #endif 128 | -------------------------------------------------------------------------------- /yasio/ssl.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | 29 | #ifndef YASIO__SSL_HPP 30 | #define YASIO__SSL_HPP 31 | 32 | #include "yasio/config.hpp" 33 | 34 | #if YASIO_SSL_BACKEND == 1 // OpenSSL 35 | # include 36 | # include 37 | # include 38 | typedef struct ssl_ctx_st yssl_ctx_st; 39 | struct yssl_st { 40 | ssl_st* session; 41 | int fd; 42 | BIO_METHOD* bmth; 43 | }; 44 | # define yssl_unwrap(ssl) ssl->session 45 | 46 | #elif YASIO_SSL_BACKEND == 2 // mbedtls 47 | # define MBEDTLS_ALLOW_PRIVATE_ACCESS 48 | # include "mbedtls/net_sockets.h" 49 | # include "mbedtls/debug.h" 50 | # include "mbedtls/ssl.h" 51 | # include "mbedtls/entropy.h" 52 | # include "mbedtls/ctr_drbg.h" 53 | # include "mbedtls/error.h" 54 | # include "mbedtls/version.h" 55 | typedef struct ssl_ctx_st { 56 | mbedtls_ctr_drbg_context ctr_drbg; 57 | mbedtls_entropy_context entropy; 58 | mbedtls_x509_crt cert; 59 | mbedtls_pk_context pkey; 60 | mbedtls_ssl_config conf; 61 | } yssl_ctx_st; 62 | struct yssl_st : public mbedtls_ssl_context { 63 | mbedtls_net_context bio; 64 | }; 65 | #endif 66 | 67 | #if defined(YASIO_SSL_BACKEND) 68 | struct yssl_options { 69 | char* crtfile_; 70 | char* keyfile_; 71 | bool client; 72 | }; 73 | 74 | YASIO__DECL yssl_ctx_st* yssl_ctx_new(const yssl_options& opts); 75 | YASIO__DECL void yssl_ctx_free(yssl_ctx_st*& ctx); 76 | 77 | YASIO__DECL yssl_st* yssl_new(yssl_ctx_st* ctx, int fd, const char* hostname, bool client); 78 | YASIO__DECL void yssl_shutdown(yssl_st*&, bool writable); 79 | 80 | /** 81 | * @returns 82 | * 0: succeed 83 | * other: use yssl_strerror(ret & YSSL_ERROR_MASK, ...) get error message 84 | * - err can bb 85 | - EWOULDBLOCK: status ok, repeat call next time 86 | * - yasio::errc::ssl_handshake_failed: failed 87 | */ 88 | YASIO__DECL int yssl_do_handshake(yssl_st* ssl, int& err); 89 | YASIO__DECL const char* yssl_strerror(yssl_st* ssl, int sslerr, char* buf, size_t buflen); 90 | 91 | YASIO__DECL int yssl_write(yssl_st* ssl, const void* data, size_t len, int& err); 92 | YASIO__DECL int yssl_read(yssl_st* ssl, void* data, size_t len, int& err); 93 | #endif 94 | 95 | /////////////////////////////////////////////////////////////////// 96 | // --- Implement common yasio ssl api with different ssl backends 97 | 98 | #define yasio__valid_str(cstr) (cstr && *cstr) 99 | #define yasio__c_str(str) (!str.empty() ? &str.front() : nullptr) 100 | 101 | #if YASIO_SSL_BACKEND == 1 // openssl 102 | # include "yasio/impl/openssl.hpp" 103 | #elif YASIO_SSL_BACKEND == 2 // mbedtls 104 | # include "yasio/impl/mbedtls.hpp" 105 | #else 106 | # error "yasio - Unsupported ssl backend provided!" 107 | #endif 108 | 109 | #endif 110 | -------------------------------------------------------------------------------- /yasio/sz.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | The above copyright notice and this permission notice shall be included in all 17 | copies or substantial portions of the Software. 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | SOFTWARE. 25 | */ 26 | #ifndef YASIO__SZ_HPP 27 | #define YASIO__SZ_HPP 28 | 29 | #include 30 | 31 | static const uint64_t YASIO__B = (1); 32 | static const uint64_t YASIO__KB = (1024 * YASIO__B); 33 | static const uint64_t YASIO__MB = (1024 * YASIO__KB); 34 | static const uint64_t YASIO__GB = (1024 * YASIO__MB); 35 | static const uint64_t YASIO__TB = (1024 * YASIO__GB); 36 | static const uint64_t YASIO__PB = (1024 * YASIO__TB); 37 | static const uint64_t YASIO__EB = (1024 * YASIO__PB); // lgtm [cpp/unused-static-variable] 38 | 39 | #define YASIO__K YASIO__KB 40 | #define YASIO__M YASIO__MB 41 | #define YASIO__G YASIO__GB 42 | #define YASIO__T YASIO__TB 43 | #define YASIO__P YASIO__PB 44 | #define YASIO__E YASIO__EB 45 | #define YASIO__b YASIO__B 46 | #define YASIO__k YASIO__K 47 | #define YASIO__m YASIO__M 48 | #define YASIO__g YASIO__G 49 | #define YASIO__t YASIO__T 50 | #define YASIO__p YASIO__P 51 | #define YASIO__e YASIO__E 52 | 53 | #define YASIO_SZ(n, u) ((n)*YASIO__##u) 54 | 55 | #define YASIO_SZ_ALIGN(d, a) (((d) + ((a)-1)) & ~((a)-1)) 56 | 57 | #endif 58 | -------------------------------------------------------------------------------- /yasio/thread_name.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | #ifndef YASIO__THREAD_NAME_HPP 29 | #define YASIO__THREAD_NAME_HPP 30 | #if defined(WIN32) 31 | # if !defined(WIN32_LEAN_AND_MEAN) 32 | # define WIN32_LEAN_AND_MEAN 33 | # endif 34 | # include 35 | #else 36 | # include 37 | # if defined(__FreeBSD__) || defined(__OpenBSD__) 38 | # include // For pthread_getthreadid_np() / pthread_set_name_np() 39 | # endif 40 | #endif 41 | 42 | #if defined(_WIN32) 43 | const DWORD MS_VC_EXCEPTION = 0x406D1388; 44 | # pragma pack(push, 8) 45 | typedef struct _yasio__thread_info { 46 | DWORD dwType; // Must be 0x1000. 47 | LPCSTR szName; // Pointer to name (in user addr space). 48 | DWORD dwThreadID; // Thread ID (-1=caller thread). 49 | DWORD dwFlags; // Reserved for future use, must be zero. 50 | } yasio__thread_info; 51 | # pragma pack(pop) 52 | static void yasio__set_thread_name(const char* threadName) 53 | { 54 | yasio__thread_info info; 55 | info.dwType = 0x1000; 56 | info.szName = threadName; 57 | info.dwThreadID = GetCurrentThreadId(); 58 | info.dwFlags = 0; 59 | # if !defined(__MINGW64__) && !defined(__MINGW32__) 60 | __try 61 | { 62 | RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info); 63 | } 64 | __except (EXCEPTION_EXECUTE_HANDLER) 65 | {} 66 | # endif 67 | } 68 | #elif defined(__linux__) 69 | # if (defined(__GLIBC__) && defined(_GNU_SOURCE)) || defined(__ANDROID__) 70 | # define yasio__set_thread_name(name) pthread_setname_np(pthread_self(), name) 71 | # else 72 | # define yasio__set_thread_name(name) 73 | # endif 74 | #elif defined(__APPLE__) 75 | # define yasio__set_thread_name(name) pthread_setname_np(name) 76 | #elif defined(__FreeBSD__) || defined(__OpenBSD__) 77 | # define yasio__set_thread_name(name) pthread_set_name_np(pthread_self(), name) 78 | #elif defined(__NetBSD__) 79 | # define yasio__set_thread_name(name) pthread_setname_np(pthread_self(), "%s", (void*)name); 80 | #else 81 | # define yasio__set_thread_name(name) 82 | #endif 83 | 84 | namespace yasio 85 | { 86 | inline void set_thread_name(const char* name) { yasio__set_thread_name(name); } 87 | } // namespace yasio 88 | #endif 89 | -------------------------------------------------------------------------------- /yasio/type_traits.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | 29 | #pragma once 30 | 31 | #include 32 | #include 33 | #include "yasio/sz.hpp" 34 | 35 | namespace yasio 36 | { 37 | template 38 | struct aligned_storage_size { 39 | static const size_t value = YASIO_SZ_ALIGN(sizeof(_Ty), sizeof(std::max_align_t)); 40 | }; 41 | template 42 | struct is_aligned_storage { 43 | static const bool value = aligned_storage_size<_Ty>::value == sizeof(_Ty); 44 | }; 45 | template 46 | struct is_iterator : public std::integral_constant::value> {}; 47 | 48 | template 49 | using enable_if_t = typename ::std::enable_if<_Test, _Ty>::type; 50 | 51 | template 52 | struct is_byte_type { 53 | static const bool value = std::is_same<_Ty, char>::value || std::is_same<_Ty, unsigned char>::value; 54 | }; 55 | 56 | template 57 | struct is_char_type { 58 | static const bool value = std::is_integral<_Ty>::value && sizeof(_Ty) <= sizeof(char32_t); 59 | }; 60 | 61 | } // namespace yasio 62 | -------------------------------------------------------------------------------- /yasio/utils.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | #ifndef YASIO__UTILS_HPP 29 | #define YASIO__UTILS_HPP 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include "yasio/compiler/feature_test.hpp" 35 | 36 | namespace yasio 37 | { 38 | // typedefs 39 | typedef long long highp_time_t; 40 | #if YASIO__HAS_CXX11 41 | typedef std::chrono::steady_clock steady_clock_t; 42 | #else 43 | typedef std::chrono::high_resolution_clock steady_clock_t; 44 | #endif 45 | typedef std::chrono::system_clock system_clock_t; 46 | 47 | // The high precision nano seconds timestamp since epoch 48 | template 49 | inline highp_time_t xhighp_clock() 50 | { 51 | auto duration = _Ty::now().time_since_epoch(); 52 | return std::chrono::duration_cast(duration).count(); 53 | } 54 | // The high precision micro seconds timestamp since epoch 55 | template 56 | inline highp_time_t highp_clock() 57 | { 58 | return xhighp_clock<_Ty>() / std::milli::den; 59 | } 60 | // The normal precision milli seconds timestamp since epoch 61 | template 62 | inline highp_time_t clock() 63 | { 64 | return xhighp_clock<_Ty>() / std::micro::den; 65 | } 66 | // The time now in seconds since epoch, better performance than chrono on win32 67 | // see: win10 sdk ucrt/time/time.cpp:common_time 68 | // https://docs.microsoft.com/en-us/windows/desktop/sysinfo/acquiring-high-resolution-time-stamps 69 | inline highp_time_t time_now() { return ::time(nullptr); } 70 | 71 | #if YASIO__HAS_CXX17 72 | using std::clamp; 73 | #else 74 | template 75 | const _Ty& clamp(const _Ty& v, const _Ty& lo, const _Ty& hi) 76 | { 77 | assert(!(hi < lo)); 78 | return v < lo ? lo : hi < v ? hi : v; 79 | } 80 | #endif 81 | 82 | template 83 | inline void invoke_dtor(_Ty* p) 84 | { 85 | p->~_Ty(); 86 | } 87 | 88 | inline bool is_regular_file(const char* path) 89 | { 90 | struct stat st; 91 | return (::stat(path, &st) == 0) && (st.st_mode & S_IFREG); 92 | } 93 | 94 | } // namespace yasio 95 | 96 | #endif 97 | -------------------------------------------------------------------------------- /yasio/wtimer_hres.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | The above copyright notice and this permission notice shall be included in all 17 | copies or substantial portions of the Software. 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | SOFTWARE. 25 | */ 26 | 27 | #pragma once 28 | 29 | #ifdef _WIN32 30 | 31 | # include "yasio/config.hpp" 32 | # include "yasio/utils.hpp" 33 | 34 | # if defined(YASIO__USE_TIMEAPI) 35 | # include 36 | # pragma comment(lib, "Winmm.lib") 37 | # endif 38 | 39 | namespace yasio 40 | { 41 | /** 42 | * CLASS wtimer_hres: The windows timer high-resolution setup helper 43 | */ 44 | struct wtimer_hres { 45 | using NTSTATUS = LONG; 46 | /** 47 | * @param res the timer resolution in 100-ns units: 100-ns * 10000 = 1ms 48 | * @remark 49 | * - timeapi timeBeginPeriod max resolution is 1ms 50 | * - ZwSetTimerResolution max resolution is 0.5ms aka 100-ns * 5000 51 | */ 52 | static const ULONG _1ms_den = 10000; 53 | wtimer_hres(ULONG timer_res = _1ms_den) 54 | { 55 | # if defined(YASIO__USE_TIMEAPI) 56 | TIMECAPS tc; 57 | if (TIMERR_NOERROR == timeGetDevCaps(&tc, sizeof(TIMECAPS))) 58 | { 59 | timer_res_ = yasio::clamp(static_cast(timer_res / _1ms_den), tc.wPeriodMin, tc.wPeriodMax); 60 | timeBeginPeriod(timer_res_); 61 | } 62 | # else 63 | do 64 | { 65 | HMODULE hNtDll = GetModuleHandleW(L"ntdll"); 66 | if (!hNtDll) 67 | break; 68 | 69 | NTSTATUS(__stdcall * NtQueryTimerResolution) 70 | (OUT PULONG MinimumResolution, OUT PULONG MaximumResolution, OUT PULONG CurrentResolution) = 71 | reinterpret_cast(GetProcAddress(hNtDll, "NtQueryTimerResolution")); 72 | if (!NtQueryTimerResolution) 73 | break; 74 | ZwSetTimerResolution = reinterpret_cast(GetProcAddress(hNtDll, "ZwSetTimerResolution")); 75 | if (!ZwSetTimerResolution) 76 | break; 77 | 78 | ULONG MinimumResolution, MaximumResolution, CurrentResolution; 79 | if (NtQueryTimerResolution(&MinimumResolution, &MaximumResolution, &CurrentResolution) != 0) 80 | break; 81 | ZwSetTimerResolution(yasio::clamp(timer_res, MaximumResolution, MinimumResolution), TRUE, &timer_res); 82 | } while (false); 83 | # endif 84 | } 85 | ~wtimer_hres() 86 | { 87 | # if defined(YASIO__USE_TIMEAPI) 88 | if (timer_res_ != 0) 89 | timeEndPeriod(timer_res_); 90 | # else 91 | if (timer_res_) 92 | ZwSetTimerResolution(timer_res_, FALSE, nullptr); 93 | # endif 94 | } 95 | # if defined(YASIO__USE_TIMEAPI) 96 | UINT timer_res_{0}; 97 | # else 98 | NTSTATUS(__stdcall* ZwSetTimerResolution) 99 | (IN ULONG RequestedResolution, IN BOOLEAN Set, OUT PULONG ActualResolution){nullptr}; 100 | ULONG timer_res_{0}; 101 | # endif 102 | }; 103 | 104 | } // namespace yasio 105 | #endif 106 | -------------------------------------------------------------------------------- /yasio/yasio.hpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////////// 2 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 3 | // client application. 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | #ifndef YASIO__CORE_HPP 29 | #define YASIO__CORE_HPP 30 | 31 | #include "yasio/ibstream.hpp" 32 | #include "yasio/obstream.hpp" 33 | #include "yasio/io_service.hpp" 34 | 35 | #endif 36 | -------------------------------------------------------------------------------- /yasio/yasio.natvis: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {{ size={_Mysize} capacity={_Myres} }} 6 | 7 | _Mysize 8 | _Myres 9 | 10 | _Mysize 11 | _Myfirst 12 | 13 | 14 | 15 | 16 | {{ size={_Mysize} {_Myfirst,[_Mysize]s8} }} 17 | 18 | _Mysize 19 | _Myres 20 | 21 | _Mysize 22 | _Myfirst 23 | 24 | 25 | 26 | 27 | 28 | {_Myfirst,s8} 29 | {&_Myfirst,s8} 30 | _Myfirst,s8 31 | &_Myfirst,s8 32 | 33 | _Mysize 34 | _Myres 35 | 36 | _Mysize 37 | _Myfirst 38 | 39 | 40 | _Mysize 41 | &_Myfirst 42 | 43 | 44 | 45 | 46 | 47 | 48 | {_Myfirst,su} 49 | {&_Myfirst,su} 50 | _Myfirst,su 51 | &_Myfirst,su 52 | 53 | _Mysize 54 | _Myres 55 | 56 | _Mysize 57 | _Myfirst 58 | 59 | 60 | _Mysize 61 | &_Myfirst 62 | 63 | 64 | 65 | 66 | {_Myfirst,s32} 67 | {&_Myfirst,s32} 68 | _Myfirst,s32 69 | &_Myfirst,s32 70 | 71 | _Mysize 72 | _Myres 73 | 74 | _Mysize 75 | _Myfirst 76 | 77 | 78 | _Mysize 79 | &_Myfirst 80 | 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /yasio/yasio_fwd.hpp: -------------------------------------------------------------------------------- 1 | // A multi-platform support c++11 library with focus on asynchronous socket I/O for any 2 | // client application. 3 | // 4 | ////////////////////////////////////////////////////////////////////////////////////////// 5 | /* 6 | The MIT License (MIT) 7 | 8 | Copyright (c) 2012-2025 HALX99 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | */ 28 | #ifndef YASIO__FWD_HPP 29 | #define YASIO__FWD_HPP 30 | #include "yasio/compiler/feature_test.hpp" 31 | 32 | namespace yasio 33 | { 34 | YASIO__NS_INLINE 35 | namespace inet 36 | { 37 | class highp_timer; 38 | class io_service; 39 | class io_event; 40 | class io_channel; 41 | typedef class io_transport* transport_handle_t; 42 | } // namespace inet 43 | #if !YASIO__HAS_CXX11 44 | using namespace yasio::inet; 45 | #endif 46 | } // namespace yasio 47 | 48 | #endif 49 | --------------------------------------------------------------------------------