From 573b3e7a2367922e9312a54bc90e4dc5c5516495 Mon Sep 17 00:00:00 2001 From: gxt_kt Date: Wed, 4 Dec 2024 19:35:03 +0800 Subject: [PATCH] first commit --- .clang-format | 308 +++++++++++++++++++++++++++++++++++++++++++++++ .gitignore | 9 ++ CMakeLists.txt | 65 ++++++++++ README.md | 11 ++ cmake/help.cmake | 4 + include/common.h | 0 src/receive.cc | 44 +++++++ src/send.cc | 42 +++++++ 8 files changed, 483 insertions(+) create mode 100644 .clang-format create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 README.md create mode 100644 cmake/help.cmake create mode 100644 include/common.h create mode 100644 src/receive.cc create mode 100644 src/send.cc diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..779f160 --- /dev/null +++ b/.clang-format @@ -0,0 +1,308 @@ +--- +Language: Cpp +AccessModifierOffset: -1 +AlignAfterOpenBracket: Align +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCaseArrows: false + AlignCaseColons: false +AlignConsecutiveTableGenBreakingDAGArgColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenCondOperatorColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenDefinitionColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignEscapedNewlines: Left +AlignOperands: Align +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowBreakBeforeNoexceptSpecifier: Never +AllowShortBlocksOnASingleLine: Never +AllowShortCaseExpressionOnASingleLine: true +AllowShortCaseLabelsOnASingleLine: false +AllowShortCompoundRequirementOnASingleLine: true +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: WithoutElse +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: true +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakBeforeMultilineStrings: true +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BitFieldColonSpacing: Both +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterExternBlock: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakAdjacentStringLiterals: true +BreakAfterAttributes: Leave +BreakAfterJavaFieldAnnotations: false +BreakAfterReturnType: None +BreakArrays: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: Attach +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeColon +BreakFunctionDefinitionParameters: false +BreakInheritanceList: BeforeColon +BreakStringLiterals: true +BreakTemplateDeclarations: Yes +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: true +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '^' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^<.*\.h>' + Priority: 1 + SortPriority: 0 + CaseSensitive: false + - Regex: '^<.*' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 3 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '([-_](test|unittest))?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: true +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true +IndentPPDirectives: None +IndentRequiresClause: true +IndentWidth: 2 +IndentWrappedFunctionNames: false +InsertBraces: false +InsertNewlineAtEOF: false +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLines: + AtEndOfFile: false + AtStartOfBlock: false + AtStartOfFile: true +LambdaBodyIndentation: Signature +LineEnding: DeriveLF +MacroBlockBegin: '' +MacroBlockEnd: '' +MainIncludeChar: Quote +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Never +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PackConstructorInitializers: NextLine +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 1 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakScopeResolution: 500 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 200 +PointerAlignment: Left +PPIndentWidth: -1 +QualifierAlignment: Leave +RawStringFormats: + - Language: Cpp + Delimiters: + - cc + - CC + - cpp + - Cpp + - CPP + - 'c++' + - 'C++' + CanonicalDelimiter: '' + BasedOnStyle: google + - Language: TextProto + Delimiters: + - pb + - PB + - proto + - PROTO + EnclosingFunctions: + - EqualsProto + - EquivToProto + - PARSE_PARTIAL_TEXT_PROTO + - PARSE_TEST_PROTO + - PARSE_TEXT_PROTO + - ParseTextOrDie + - ParseTextProtoOrDie + - ParseTestProto + - ParsePartialTestProto + CanonicalDelimiter: pb + BasedOnStyle: google +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SkipMacroDefinitionBody: false +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterPlacementOperator: true + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: Never +SpacesInContainerLiterals: true +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + ExceptDoubleParentheses: false + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false +SpacesInSquareBrackets: false +Standard: Auto +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TableGenBreakInsideDAGArg: DontBreak +TabWidth: 8 +UseTab: Never +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE +... + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c33ad11 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +build/ +cmake-build* +.cache +.idea +.vscode +.cache +*__pycache__* +*.md-E +*.log diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..fd969cf --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,65 @@ +cmake_minimum_required(VERSION 3.0) +project(cmake_template) + +include(cmake/help.cmake) + +set(CMAKE_BUILD_TYPE Release) # Debug Release RelWithDebInfo +# set a debug postfix +set(CMAKE_DEBUG_POSTFIX "-dbg") + +# set(CMAKE_C_COMPILER "gcc") # gcc clang +# set(CMAKE_CXX_COMPILER "g++") # g++ clang++ + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED True) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + +# set the most strict compile rule +if(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang") + add_compile_options(-Wall) + # add_compile_options(-Wall -Wextra -Wpedantic -Werror) +elseif(CMAKE_C_COMPILER_ID STREQUAL "MSVC") + add_compile_options(/W4 /WX) +endif() + +include_directories(include) + +if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux") + message("Building for Linux platform") +elseif (${CMAKE_SYSTEM_NAME} STREQUAL "Darwin") + message("Building for macOS platform") +elseif (${CMAKE_SYSTEM_NAME} STREQUAL "Windows") + message("Building for Windows platform") +else() + message(FATAL_ERROR "Unsupported platform: ${CMAKE_SYSTEM_NAME}") +endif() + + +option(OPTION_TEST "whether or not to build the tests" ON) +if(OPTION_TEST) + PrintVariable(OPTION_TEST) +endif() + + +# add_definitions(-DMY_MACRO) +# target_compile_definitions(demo PRIVATE MY_MACRO) + +# add_library(demo SHARED ${detail_header} ${header} ${src}) +# target_include_directories(demo) +# target_compile_definitions(demo PUBLIC COMPILE_TEST=) + + + +find_package(debugstream) +find_package(Boost REQUIRED) +# find_package(ZeroMQ_INCLUDE_DIR) + +include_directories(include) + +add_executable(send src/send.cc) +target_link_libraries (send ${Boost_LIBRARIES}) #链接boost +target_link_libraries(send debugstream) +add_executable(receive src/receive.cc) +target_link_libraries (receive ${Boost_LIBRARIES}) #链接boost +target_link_libraries(receive debugstream) +# target_link_libraries(demo ZeroMQ_LIBRARY) diff --git a/README.md b/README.md new file mode 100644 index 0000000..0dd861a --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +# boost asio test + +test time interval between send and receive + +```c++ +cmake -S . -B build +cmake --build build -j + +./build/receive +./build/send +``` diff --git a/cmake/help.cmake b/cmake/help.cmake new file mode 100644 index 0000000..0901981 --- /dev/null +++ b/cmake/help.cmake @@ -0,0 +1,4 @@ +# print value +macro(PrintVariable var_name) + message(STATUS "${var_name}=${${var_name}}") +endmacro() diff --git a/include/common.h b/include/common.h new file mode 100644 index 0000000..e69de29 diff --git a/src/receive.cc b/src/receive.cc new file mode 100644 index 0000000..97f64d4 --- /dev/null +++ b/src/receive.cc @@ -0,0 +1,44 @@ +#include +#include +#include +#include + +int main() { + try { + boost::asio::io_context io_context; + + // 创建 UDP socket + boost::asio::ip::udp::socket socket( + io_context, + boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 12345)); + + while (true) { + char recv_buffer[1024]; + boost::asio::ip::udp::endpoint sender_endpoint; + + // 接收数据 + size_t len = socket.receive_from(boost::asio::buffer(recv_buffer), + sender_endpoint); + std::string received_message(recv_buffer, len); + + // 解码时间字符串为微秒 + long long received_time_us = std::stoll(received_message); + auto now = std::chrono::high_resolution_clock::now(); + auto current_time_us = + std::chrono::duration_cast( + now.time_since_epoch()) + .count(); + + // 计算时间差 + long long time_difference = current_time_us - received_time_us; + + std::cout << "Received: " << received_message + << " | Time difference: " << time_difference << " us" + << std::endl; + } + } catch (std::exception& e) { + std::cerr << "Exception: " << e.what() << std::endl; + } + + return 0; +} diff --git a/src/send.cc b/src/send.cc new file mode 100644 index 0000000..a1bf633 --- /dev/null +++ b/src/send.cc @@ -0,0 +1,42 @@ +#include +#include +#include +#include +#include + +int main() { + try { + boost::asio::io_context io_context; + + // 创建 UDP socket + boost::asio::ip::udp::socket socket(io_context); + socket.open(boost::asio::ip::udp::v4()); + + // 设置目标地址和端口 + boost::asio::ip::udp::endpoint receiver_endpoint( + boost::asio::ip::make_address("127.0.0.1"), 12345); + + while (true) { + // 获取当前时间,转换为微秒 + auto now = std::chrono::high_resolution_clock::now(); + auto duration = now.time_since_epoch(); + auto microseconds = + std::chrono::duration_cast(duration) + .count(); + + // 转换为字符串 + std::string message = std::to_string(microseconds); + + // 发送数据 + socket.send_to(boost::asio::buffer(message), receiver_endpoint); + std::cout << "Sent: " << message << std::endl; + + // 等待 50 毫秒 + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + } catch (std::exception& e) { + std::cerr << "Exception: " << e.what() << std::endl; + } + + return 0; +}