### Installation Rules for DartZMQ Application Source: https://github.com/enwi/dartzmq/blob/main/example/windows/CMakeLists.txt Configures the installation process for the DartZMQ application. It sets the installation prefix to be adjacent to the executable, installs the main executable, ICU data file, Flutter library, bundled plugin libraries, and assets. It also handles the AOT library installation for release configurations. ```cmake set(BUILD_BUNDLE_DIR "$") set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### CMake Project Setup and Configuration Source: https://github.com/enwi/dartzmq/blob/main/example/linux/CMakeLists.txt Sets up the CMake project, defines the executable name and application ID, and configures modern CMake behaviors. It also specifies the runtime path for bundled libraries. ```cmake cmake_minimum_required(VERSION 3.10) project(runner LANGUAGES CXX) set(BINARY_NAME "dartzmq_example") set(APPLICATION_ID "com.example.dartzmq") cmake_policy(SET CMP0063 NEW) set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") ``` -------------------------------- ### CMake Installation Rules for Application Bundle Source: https://github.com/enwi/dartzmq/blob/main/example/linux/CMakeLists.txt Defines installation rules to create a relocatable application bundle. It cleans the build bundle directory, installs the executable, Flutter data, libraries, and assets. ```cmake set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Implement CURVE Security for Encrypted Connections Source: https://context7.com/enwi/dartzmq/llms.txt Provides an example of setting up a secure ZMQ connection using CURVE encryption. It covers server-side key configuration and client-side authentication requirements. ```dart import 'package:dartzmq/dartzmq.dart'; final context = ZContext(); // Check if CURVE is supported if (!context.hasCURVE()) { print('CURVE not supported in this build'); return; } // Server setup final server = context.createSocket(SocketType.rep); server.setOption(ZMQ_CURVE_SERVER, 1); // Enable CURVE server mode server.setCurveSecretKey('JTKVSB%SD}U?@Lns47E1%kR.o@n%FcmmsL/@{H8]Z.xL'); // Server public key server.bind('tcp://*:5556'); // Client setup final client = context.createSocket(SocketType.req); // Client's own keypair client.setCurveSecretKey('D:)Q[IlAW!ahhC2ac:9*A}h:p?([4%wOTJ%JR%CS'); client.setCurvePublicKey('Yne@$w-vo}U?@Lns47E1%kR.o@n%FcmmsL/@{H8]Z.xL'); client.connect('tcp://localhost:5556'); // Communication is now encrypted client.sendString('Secure message'); server.close(); client.close(); await context.stop(); ``` -------------------------------- ### Dartzmq: Monitor Socket Events Source: https://github.com/enwi/dartzmq/blob/main/README.md Provides examples of how to monitor socket events using both MonitoredZSocket and ZMonitor classes. This allows for reacting to connection status changes and other socket lifecycle events. ```dart // Using MonitoredZSocket final MonitoredZSocket socket = context.createMonitoredSocket(SocketType.req); socket.events.listen((event) { log('Received event ${event.event} with value ${event.value}'); }); // Using ZMonitor final ZSocket socket = context.createSocket(SocketType.req); final ZMonitor monitor = ZMonitor( context: context, socket: socket, event: ZMQ_EVENT_CONNECTED | ZMQ_EVENT_CLOSED, // Only listen for connected and closed events ); monitor.events.listen((event) { log('Received event ${event.event} with value ${event.value}'); }); ``` -------------------------------- ### Manage ZeroMQ Context and Sockets Source: https://context7.com/enwi/dartzmq/llms.txt Demonstrates how to initialize a global ZContext, check for library capabilities like CURVE encryption, and instantiate various socket types including async, sync, and monitored sockets. ```dart import 'package:dartzmq/dartzmq.dart'; final ZContext context = ZContext(); if (context.hasCURVE()) { print('CURVE encryption is supported'); } if (context.hasDRAFT()) { print('Draft API is available'); } print('IPC supported: ${context.hasIPC()}'); print('PGM supported: ${context.hasPGM()}'); final asyncSocket = context.createSocket(SocketType.dealer); final syncSocket = context.createSyncSocket(SocketType.req); final monitoredSocket = context.createMonitoredSocket(SocketType.req); asyncSocket.close(); syncSocket.close(); monitoredSocket.close(); await context.stop(); ``` -------------------------------- ### Dartzmq: Create and Initialize Sockets Source: https://github.com/enwi/dartzmq/blob/main/README.md Demonstrates how to create a ZContext and then instantiate both asynchronous (ZSocket) and synchronous (ZSyncSocket) sockets with various ZeroMQ socket types. ```dart final ZContext context = ZContext(); // Create asynchronous socket final ZSocket socket = context.createSocket(SocketType.req); // Create synchronous socket final ZSyncSocket socket = context.createSyncSocket(SocketType.req); ``` -------------------------------- ### Dartzmq: Clean Up Resources Source: https://github.com/enwi/dartzmq/blob/main/README.md Demonstrates the correct procedures for closing sockets, monitors, and the ZeroMQ context to release resources properly when they are no longer needed. ```dart // Destroy socket socket.close(); // Destroy monitor monitor.close(); // Destroy context context.stop(); ``` -------------------------------- ### Configure Socket Options for ZMQ Source: https://context7.com/enwi/dartzmq/llms.txt Shows how to use setOption to tune socket behavior, including high-water marks, timeouts, keepalive settings, and IPv6 support. ```dart import 'package:dartzmq/dartzmq.dart'; final context = ZContext(); final socket = context.createSocket(SocketType.dealer); // Set socket identity socket.setOption(ZMQ_IDENTITY, 'my-client-id'); // Set high-water marks (message queue limits) socket.setOption(ZMQ_SNDHWM, 1000); // Send high-water mark socket.setOption(ZMQ_RCVHWM, 1000); // Receive high-water mark // Set timeouts in milliseconds socket.setOption(ZMQ_RCVTIMEO, 5000); // Receive timeout socket.setOption(ZMQ_SNDTIMEO, 5000); // Send timeout // Set linger period (time to send pending messages on close) socket.setOption(ZMQ_LINGER, 0); // Don't wait, discard pending // Enable TCP keepalive socket.setOption(ZMQ_TCP_KEEPALIVE, 1); socket.setOption(ZMQ_TCP_KEEPALIVE_IDLE, 300); socket.setOption(ZMQ_TCP_KEEPALIVE_INTVL, 60); // Set reconnect interval socket.setOption(ZMQ_RECONNECT_IVL, 100); // Initial interval (ms) socket.setOption(ZMQ_RECONNECT_IVL_MAX, 5000); // Max interval (ms) // Enable IPv6 socket.setOption(ZMQ_IPV6, true); socket.connect('tcp://localhost:5555'); socket.close(); await context.stop(); ``` -------------------------------- ### DartZMQ Socket Type Initialization Source: https://context7.com/enwi/dartzmq/llms.txt Demonstrates how to create and initialize various ZeroMQ socket types using the DartZMQ library. It covers standard patterns like REQ/REP, DEALER/ROUTER, PUB/SUB, PUSH/PULL, PAIR, and STREAM, as well as draft patterns if the draft API is enabled. ```dart import 'package:dartzmq/dartzmq.dart'; final context = ZContext(); // Request/Reply pattern (synchronous) final reqSocket = context.createSyncSocket(SocketType.req); final repSocket = context.createSyncSocket(SocketType.rep); // Dealer/Router pattern (asynchronous req/rep) final dealerSocket = context.createSocket(SocketType.dealer); final routerSocket = context.createSocket(SocketType.router); // Publish/Subscribe pattern final pubSocket = context.createSocket(SocketType.pub); final subSocket = context.createSocket(SocketType.sub); // Push/Pull pattern (pipeline) final pushSocket = context.createSocket(SocketType.push); final pullSocket = context.createSocket(SocketType.pull); // Pair pattern (exclusive pair) final pairSocket = context.createSocket(SocketType.pair); // Stream pattern (raw TCP) final streamSocket = context.createSocket(SocketType.stream); // Draft patterns (if supported) if (context.hasDRAFT()) { final serverSocket = context.createSocket(SocketType.server); final clientSocket = context.createSocket(SocketType.client); } ``` -------------------------------- ### Manage Multipart Messages with ZFrame and ZMessage Source: https://context7.com/enwi/dartzmq/llms.txt Demonstrates how to create individual message frames using ZFrame and assemble them into multipart messages using ZMessage. It also shows how to send and receive these messages over a dealer socket. ```dart import 'dart:typed_data'; import 'package:dartzmq/dartzmq.dart'; final context = ZContext(); final socket = context.createSocket(SocketType.dealer); socket.connect('tcp://localhost:5566'); // Create a single frame final frame = ZFrame(Uint8List.fromList([1, 2, 3, 4, 5])); print('Frame payload: ${frame.payload}'); print('Has more frames: ${frame.hasMore}'); // Create a multipart message final message = ZMessage(); message.add(ZFrame(Uint8List.fromList([0]))); // Identity frame message.add(ZFrame(Uint8List.fromList([1, 2, 3]))); // Data frame 1 message.add(ZFrame(Uint8List.fromList([4, 5, 6]))); // Data frame 2 // Queue operations on ZMessage message.addFirst(ZFrame(Uint8List(0))); // Add empty delimiter at start message.addLast(ZFrame(Uint8List.fromList([7, 8, 9]))); print('Message has ${message.length} frames'); print('First frame: ${message.first.payload}'); print('Last frame: ${message.last.payload}'); // Send the multipart message socket.sendMessage(message, flags: ZMQ_DONTWAIT); // Receive and process multipart messages socket.messages.listen((ZMessage received) { for (int i = 0; i < received.length; i++) { final frame = received.elementAt(i); print('Frame $i: ${frame.payload}'); } }); socket.close(); await context.stop(); ``` -------------------------------- ### Dartzmq: Connect and Send Messages Source: https://github.com/enwi/dartzmq/blob/main/README.md Illustrates how to establish a connection to a ZeroMQ endpoint and send messages using different data types supported by dartzmq, including byte lists, strings, ZFrames, and ZMessages. ```dart socket.connect("tcp://localhost:5566"); socket.send([1, 2, 3, 4, 5]); socket.sendString('My Message'); socket.sendFrame(ZFrame([1, 2, 3, 4, 5])); var message = ZMessage(); message.add(ZFrame([1, 2, 3, 4, 5])); message.add(ZFrame([6, 7, 8, 9, 10])); socket.sendMessage(message, flags: ZMQ_DONTWAIT); ``` -------------------------------- ### ZContext Management Source: https://context7.com/enwi/dartzmq/llms.txt The ZContext class is the entry point for all ZeroMQ operations, managing socket lifecycles and providing factory methods for socket creation. ```APIDOC ## ZContext Management ### Description Manages the global ZeroMQ context and provides methods to create sockets and check library capabilities. ### Methods - **createSocket(SocketType type)**: Creates an asynchronous socket. - **createSyncSocket(SocketType type)**: Creates a synchronous (blocking) socket. - **createMonitoredSocket(SocketType type)**: Creates a socket with monitoring capabilities. - **stop()**: Stops the context and cleans up resources. ### Usage Example ```dart final ZContext context = ZContext(); final asyncSocket = context.createSocket(SocketType.dealer); await context.stop(); ``` ``` -------------------------------- ### Configure Flutter Library and Dependencies Source: https://github.com/enwi/dartzmq/blob/main/example/linux/flutter/CMakeLists.txt Sets up the Flutter library path and links system dependencies including GTK, GLIB, and GIO. It also defines the interface library for Flutter to be used by other targets. ```cmake find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) add_library(flutter INTERFACE) target_link_libraries(flutter INTERFACE PkgConfig::GTK PkgConfig::GLIB PkgConfig::GIO ) ``` -------------------------------- ### Configure Flutter Windows Build Targets Source: https://github.com/enwi/dartzmq/blob/main/example/windows/flutter/CMakeLists.txt This snippet defines the Flutter library interface and the static wrapper libraries for plugins and applications. It sets up include directories and links the necessary Flutter Windows DLLs. ```cmake add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}") target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") add_dependencies(flutter flutter_assemble) add_library(flutter_wrapper_plugin STATIC ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN}) apply_standard_settings(flutter_wrapper_plugin) target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) ``` -------------------------------- ### Python ZeroMQ ROUTER Server Source: https://github.com/enwi/dartzmq/blob/main/example/README.md This Python script sets up a ZeroMQ ROUTER socket server that listens on TCP port 5566. It continuously polls for incoming messages, prints them, appends 'ECHO' to them, and sends them back to the client. It includes proper resource management for the socket and context. ```python #!/usr/bin/env python import zmq def main(): context = zmq.Context() poller = zmq.Poller() socket = context.socket(zmq.ROUTER) address = "tcp://*:5566".format() socket.bind(address) poller.register(socket, zmq.POLLIN) print("Running...") try: while True: items = dict(poller.poll(zmq.NOBLOCK)) for sock in items: try: msg = sock.recv_multipart(zmq.NOBLOCK) print("I: %r" % (msg)) reply = msg + ['ECHO'.encode()] print("O: %r" % (reply)) sock.send_multipart(reply) except: print("Could not read socket") pass finally: socket.unbind(address) # ALWAYS RELEASE PORT socket.close() # ALWAYS RELEASE RESOURCES context.term() # ALWAYS RELEASE RESOURCES if __name__ == "__main__": try: main() except KeyboardInterrupt: print("Done") pass ``` -------------------------------- ### Dartzmq Dealer/Router Pattern Implementation Source: https://context7.com/enwi/dartzmq/llms.txt This code demonstrates the Dealer/Router pattern for asynchronous request-reply messaging in Dart using the dartzmq library. The router acts as a server, receiving messages and sending replies, while the dealer acts as a client, sending requests and processing replies. Note the use of an empty delimiter frame for compatibility between dealer and router sockets. ```dart import 'dart:typed_data'; import 'package:dartzmq/dartzmq.dart'; // Router (server) side void runRouter() async { final context = ZContext(); final router = context.createSocket(SocketType.router); router.bind('tcp://*:5566'); router.messages.listen((ZMessage message) { // First frame is the identity of the sender final identity = message.removeFirst(); // Second frame is empty delimiter (from dealer) message.removeFirst(); // Remaining frames are the actual message final request = message.first.payload; print('Router received: $request from ${identity.payload}'); // Send reply back (must include identity and delimiter) final reply = ZMessage(); reply.add(identity); // Identity reply.add(ZFrame(Uint8List(0))); // Empty delimiter reply.add(ZFrame(Uint8List.fromList([42]))); // Reply data router.sendMessage(reply, flags: ZMQ_DONTWAIT); }); } // Dealer (client) side void runDealer() async { final context = ZContext(); final dealer = context.createSocket(SocketType.dealer); dealer.setOption(ZMQ_IDENTITY, 'client-1'); dealer.connect('tcp://localhost:5566'); // Listen for replies dealer.messages.listen((ZMessage message) { // Skip empty delimiter message.removeFirst(); final reply = message.first.payload; print('Dealer received reply: $reply'); }); // Send requests (include empty delimiter for router compatibility) for (int i = 0; i < 5; i++) { final request = ZMessage(); request.add(ZFrame(Uint8List(0))); // Empty delimiter request.add(ZFrame(Uint8List.fromList([i]))); // Request data dealer.sendMessage(request, flags: ZMQ_DONTWAIT); } } ``` -------------------------------- ### Socket Options - Configure Socket Behavior Source: https://context7.com/enwi/dartzmq/llms.txt Configures socket behavior using ZMQ constants for timeouts, high-water marks, and connection settings. ```APIDOC ## Socket Options ### Description `setOption()` configures socket behavior with various ZMQ_* constants. Options accept String, int, or bool values. ### Common Options - **ZMQ_IDENTITY**: Set socket identity. - **ZMQ_SNDHWM / ZMQ_RCVHWM**: Set high-water marks. - **ZMQ_RCVTIMEO / ZMQ_SNDTIMEO**: Set timeouts in milliseconds. - **ZMQ_TCP_KEEPALIVE**: Enable TCP keepalive. ### Example ```dart socket.setOption(ZMQ_SNDHWM, 1000); socket.setOption(ZMQ_RCVTIMEO, 5000); ``` ``` -------------------------------- ### Dart ZMQ Error Handling with ZeroMQException Source: https://context7.com/enwi/dartzmq/llms.txt Demonstrates how to handle ZeroMQ operations that may fail by catching ZeroMQException in Dart. It shows how to inspect the error code and handle common errors like EAGAIN, ETERM, and ECONNREFUSED. ```dart import 'package:dartzmq/dartzmq.dart'; final context = ZContext(); final socket = context.createSyncSocket(SocketType.req); try { // Attempt to connect socket.connect('tcp://localhost:5555'); // Set receive timeout socket.setOption(ZMQ_RCVTIMEO, 1000); socket.sendString('Hello'); // This may throw if timeout expires final reply = socket.recv(); print('Reply: ${reply.first.payload}'); } on ZeroMQException catch (e) { print('ZeroMQ error: $e'); print('Error code: ${e.errorCode}'); // Handle specific errors if (e.errorCode == EAGAIN) { print('Operation would block - try again later'); } else if (e.errorCode == ETERM) { print('Context was terminated'); } else if (e.errorCode == ECONNREFUSED) { print('Connection refused - is the server running?'); } } on StateError catch (e) { // Thrown when operating on a closed socket print('Socket state error: $e'); } finally { socket.close(); await context.stop(); } ``` -------------------------------- ### DartZMQ Subscribe and Unsubscribe Topics Source: https://context7.com/enwi/dartzmq/llms.txt Shows how to manage topic subscriptions for ZeroMQ SUB sockets using DartZMQ. Publishers send messages with topic prefixes, and subscribers can filter these messages by subscribing to specific topics or a wildcard. Unsubscribing removes the filter. ```dart import 'package:dartzmq/dartzmq.dart'; final context = ZContext(); // Publisher final pub = context.createSocket(SocketType.pub); pub.bind('tcp://*:5556'); // Subscriber final sub = context.createSocket(SocketType.sub); sub.connect('tcp://localhost:5556'); // Subscribe to specific topics sub.subscribe('weather'); // Messages starting with "weather" sub.subscribe('sports'); // Messages starting with "sports" sub.subscribe(''); // All messages (empty string = wildcard) // Listen for messages sub.messages.listen((message) { final topic = String.fromCharCodes(message.first.payload); print('Received on topic: $topic'); }); // Publisher sends messages with topic prefix pub.sendString('weather: sunny'); pub.sendString('sports: game started'); // Unsubscribe from topic sub.unsubscribe('weather'); pub.close(); sub.close(); await context.stop(); ``` -------------------------------- ### CMake Project Configuration and Build Settings Source: https://github.com/enwi/dartzmq/blob/main/example/windows/CMakeLists.txt Configures the CMake project, sets the binary name, and defines build types (Debug, Profile, Release) based on whether the generator is multi-config. It also sets up linker and compiler flags for the Profile build mode. ```cmake cmake_minimum_required(VERSION 3.14) project(dartzmq_example LANGUAGES CXX) set(BINARY_NAME "dartzmq_example") cmake_policy(SET CMP0063 NEW) get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) if(IS_MULTICONFIG) set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" CACHE STRING "" FORCE) else() if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() endif() set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") ``` -------------------------------- ### Prepend Prefix to List Items in CMake Source: https://github.com/enwi/dartzmq/blob/main/example/linux/flutter/CMakeLists.txt A utility function that iterates through a list and prepends a specified prefix to each element. This is used as a workaround for older CMake versions lacking the list(TRANSFORM) functionality. ```cmake function(list_prepend LIST_NAME PREFIX) set(NEW_LIST "") foreach(element ${${LIST_NAME}}) list(APPEND NEW_LIST "${PREFIX}${element}") endforeach(element) set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) endfunction() ``` -------------------------------- ### Define Flutter Tool Backend Command Source: https://github.com/enwi/dartzmq/blob/main/example/windows/flutter/CMakeLists.txt This snippet creates a custom command to invoke the Flutter tool backend. It uses a phony output file to ensure the build command runs during every build cycle. ```cmake add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ${PHONY_OUTPUT} COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" windows-x64 $ VERBATIM ) ``` -------------------------------- ### Configure Flutter Windows Executable with CMake Source: https://github.com/enwi/dartzmq/blob/main/example/windows/runner/CMakeLists.txt This CMake configuration sets up the build environment for a Flutter Windows application. It aggregates source files, applies standard build settings, defines NOMINMAX to prevent macro collisions, and links the necessary Flutter libraries. ```cmake cmake_minimum_required(VERSION 3.14) project(runner LANGUAGES CXX) add_executable(${BINARY_NAME} WIN32 "flutter_window.cpp" "main.cpp" "utils.cpp" "win32_window.cpp" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" "Runner.rc" "runner.exe.manifest" ) apply_standard_settings(${BINARY_NAME}) target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") add_dependencies(${BINARY_NAME} flutter_assemble) ``` -------------------------------- ### Subdirectory and Plugin Inclusion Source: https://github.com/enwi/dartzmq/blob/main/example/windows/CMakeLists.txt Includes the Flutter managed directory and the runner subdirectory, which contain their respective build rules. It also includes generated plugin build rules to manage plugin compilation and integration. ```cmake set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") add_subdirectory(${FLUTTER_MANAGED_DIR}) add_subdirectory("runner") include(flutter/generated_plugins.cmake) ``` -------------------------------- ### CMake Runtime Output Directory Configuration Source: https://github.com/enwi/dartzmq/blob/main/example/linux/CMakeLists.txt Configures the runtime output directory for the executable to a subdirectory within the build directory. This is to prevent users from running unbundled copies of the application. ```cmake set_target_properties(${BINARY_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" ) ``` -------------------------------- ### Dart ZMQ Socket Event Monitoring with ZMonitor Source: https://context7.com/enwi/dartzmq/llms.txt Demonstrates how to monitor socket state changes using ZMonitor in Dart. It covers both the convenience MonitoredZSocket and manual ZMonitor instantiation for specific events. Events are delivered as SocketEvent objects. ```dart import 'package:dartzmq/dartzmq.dart'; final context = ZContext(); // Option 1: Use MonitoredZSocket (monitors all events) final monitoredSocket = context.createMonitoredSocket(SocketType.req); monitoredSocket.connect('tcp://localhost:5555'); monitoredSocket.events.listen((SocketEvent event) { print('Event: ${event.event}, Value: ${event.value}'); switch (event.event) { case ZEvent.CONNECTED: print('Socket connected!'); break; case ZEvent.DISCONNECTED: print('Socket disconnected!'); break; case ZEvent.CONNECT_RETRIED: print('Reconnecting in ${event.value}ms...'); break; case ZEvent.HANDSHAKE_SUCCEEDED: print('Handshake completed'); break; default: break; } }); // Option 2: Create ZMonitor manually (monitor specific events only) final socket = context.createSocket(SocketType.dealer); final monitor = ZMonitor( context: context, socket: socket, event: ZMQ_EVENT_CONNECTED | ZMQ_EVENT_DISCONNECTED | ZMQ_EVENT_CLOSED, ); monitor.events.listen((event) { print('Monitored event: ${event.event}'); }); socket.connect('tcp://localhost:5566'); // Clean up monitor.close(); socket.close(); monitoredSocket.close(); await context.stop(); ``` -------------------------------- ### CMake Flutter Integration and Dependencies Source: https://github.com/enwi/dartzmq/blob/main/example/linux/CMakeLists.txt Integrates Flutter by adding its managed directory as a subdirectory and finds system-level dependencies like GTK using PkgConfig. It also defines the application ID as a preprocessor macro. ```cmake set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") add_subdirectory(${FLUTTER_MANAGED_DIR}) find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") ``` -------------------------------- ### Configure CMake for dartzmq Source: https://github.com/enwi/dartzmq/blob/main/windows/CMakeLists.txt Sets the minimum CMake version, defines the project name, and specifies the path for bundled native ZeroMQ libraries. This configuration is essential for building the native components of the Flutter plugin on Windows. ```cmake cmake_minimum_required(VERSION 3.14) set(PROJECT_NAME "dartzmq") project(${PROJECT_NAME} LANGUAGES CXX) set(dartzmq_bundled_libraries "${CMAKE_CURRENT_SOURCE_DIR}/../native/win_x64/libzmq-v142-mt-4_3_5.dll" PARENT_SCOPE ) ``` -------------------------------- ### Configure CMake for dartzmq Plugin Source: https://github.com/enwi/dartzmq/blob/main/linux/CMakeLists.txt This CMake script sets the minimum required version to 3.10 to ensure compatibility with Flutter tooling. It defines the project name and specifies the path for bundling the native libzmq shared library. ```cmake cmake_minimum_required(VERSION 3.10) set(PROJECT_NAME "dartzmq") project(${PROJECT_NAME} LANGUAGES CXX) set(dartzmq_bundled_libraries "${CMAKE_CURRENT_SOURCE_DIR}/../native/linux_${CMAKE_SYSTEM_PROCESSOR}/libzmq.so" PARENT_SCOPE ) ``` -------------------------------- ### DartZMQ Socket Binding and Connecting Source: https://context7.com/enwi/dartzmq/llms.txt Illustrates how to bind sockets to specific network addresses (server mode) and connect them to remote endpoints (client mode) using DartZMQ. It supports multiple transports like TCP, IPC, and in-process, and allows sockets to bind or connect to multiple endpoints. ```dart import 'package:dartzmq/dartzmq.dart'; final context = ZContext(); // Server socket - binds to endpoint final server = context.createSocket(SocketType.rep); server.bind('tcp://*:5555'); // Bind to all interfaces server.bind('tcp://127.0.0.1:5556'); // Bind to specific IP server.bind('ipc:///tmp/myapp.ipc'); // IPC transport (Unix) server.bind('inproc://myendpoint'); // In-process transport // Client socket - connects to endpoint final client = context.createSocket(SocketType.req); client.connect('tcp://localhost:5555'); client.connect('tcp://192.168.1.100:5555'); // Connect to remote host // For Android emulator, use special IP for host machine // client.connect('tcp://10.0.2.2:5555'); server.close(); client.close(); await context.stop(); ``` -------------------------------- ### Dartzmq: Receive Messages Source: https://github.com/enwi/dartzmq/blob/main/README.md Shows how to receive messages from a ZeroMQ socket using different stream listeners provided by dartzmq, allowing processing of complete ZMessages, individual ZFremes, or raw payloads (Uint8List). ```dart // Receive ZMessage's socket.messages.listen((message) { // Do something with message }); // Receive ZFrame's socket.frames.listen((frame) { // Do something with frame }); // Receive payloads (Uint8List) socket.payloads.listen((payload) { // Do something with payload }); ``` -------------------------------- ### CMake Executable Target Definition Source: https://github.com/enwi/dartzmq/blob/main/example/linux/CMakeLists.txt Defines the main executable target for the application, listing its source files including generated plugin registration. It then applies standard build settings and links necessary libraries. ```cmake add_executable(${BINARY_NAME} "main.cc" "my_application.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) apply_standard_settings(${BINARY_NAME}) target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) add_dependencies(${BINARY_NAME} flutter_assemble) ``` -------------------------------- ### Standard Compilation Settings Function Source: https://github.com/enwi/dartzmq/blob/main/example/windows/CMakeLists.txt Defines a CMake function `APPLY_STANDARD_SETTINGS` that applies common compilation features, options, and definitions to a target. This includes setting the C++ standard to C++17, enabling specific warning levels, and managing exception handling and debug definitions. ```cmake add_definitions(-DUNICODE -D_UNICODE) function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_17) target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") target_compile_options(${TARGET} PRIVATE /EHsc) target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") endfunction() ``` -------------------------------- ### Perform Asynchronous Socket Operations Source: https://context7.com/enwi/dartzmq/llms.txt Shows how to use ZSocket for non-blocking I/O. It covers connecting to endpoints, listening to message streams (messages, frames, payloads), and sending single or multipart messages. ```dart import 'package:dartzmq/dartzmq.dart'; final context = ZContext(); final socket = context.createSocket(SocketType.dealer); socket.connect('tcp://localhost:5566'); socket.messages.listen((ZMessage message) { print('Received message with ${message.length} frames'); for (final frame in message) { print('Frame data: ${frame.payload}'); } }); socket.frames.listen((ZFrame frame) { print('Frame: ${frame.payload}, hasMore: ${frame.hasMore}'); }); socket.payloads.listen((Uint8List payload) { print('Payload: $payload'); }); socket.send([1, 2, 3, 4, 5]); socket.sendString('Hello ZeroMQ'); socket.sendFrame(ZFrame(Uint8List.fromList([1, 2, 3]))); var message = ZMessage(); message.add(ZFrame(Uint8List.fromList([1, 2, 3]))); message.add(ZFrame(Uint8List.fromList([4, 5, 6]))); socket.sendMessage(message, flags: ZMQ_DONTWAIT); socket.close(); await context.stop(); ``` -------------------------------- ### CMake Standard Build Settings Function Source: https://github.com/enwi/dartzmq/blob/main/example/linux/CMakeLists.txt Defines a function `APPLY_STANDARD_SETTINGS` to apply common compilation features, options, and definitions to a target. This includes C++14 standard, warnings, optimization levels, and NDEBUG definition. ```cmake function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_14) target_compile_options(${TARGET} PRIVATE -Wall -Werror) target_compile_options(${TARGET} PRIVATE "<$>:-O3>") target_compile_definitions(${TARGET} PRIVATE "<$>:NDEBUG>") endfunction() ``` -------------------------------- ### CMake Plugin Registration Inclusion Source: https://github.com/enwi/dartzmq/blob/main/example/linux/CMakeLists.txt Includes the CMake script that manages the build rules for generated plugins, ensuring they are built and linked correctly with the application. ```cmake include(flutter/generated_plugins.cmake) ``` -------------------------------- ### Define Flutter Assembly Custom Command Source: https://github.com/enwi/dartzmq/blob/main/example/linux/flutter/CMakeLists.txt Defines a custom command and target to trigger the Flutter tool backend. It uses a phony file to ensure the command runs during every build cycle. ```cmake add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CMAKE_CURRENT_BINARY_DIR}/_phony_ COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ) ``` -------------------------------- ### CMake Build Type Configuration Source: https://github.com/enwi/dartzmq/blob/main/example/linux/CMakeLists.txt Sets the default build type to 'Debug' if not already defined, and restricts it to 'Debug', 'Profile', or 'Release' options. This ensures consistent build configurations. ```cmake if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() ``` -------------------------------- ### CMake Cross-Building Configuration Source: https://github.com/enwi/dartzmq/blob/main/example/linux/CMakeLists.txt Configures CMake for cross-building by setting the sysroot and find root paths when FLUTTER_TARGET_PLATFORM_SYSROOT is defined. This ensures correct library and include path resolution. ```cmake if(FLUTTER_TARGET_PLATFORM_SYSROOT) set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) endif() ``` -------------------------------- ### CURVE Security - Encrypted Connections Source: https://context7.com/enwi/dartzmq/llms.txt Provides encrypted and authenticated connections using elliptic curve cryptography with Z85-encoded keys. ```APIDOC ## CURVE Security ### Description CURVE provides encrypted and authenticated connections. Keys are 40-character Z85-encoded strings. ### Server Configuration - **ZMQ_CURVE_SERVER**: Set to 1 to enable server mode. - **setCurveSecretKey**: Set server secret key. - **setCurvePublicKey**: Set server public key. ### Client Configuration - **setCurveSecretKey**: Client's secret key. - **setCurvePublicKey**: Client's public key. - **setCurveServerKey**: Server's public key for verification. ``` -------------------------------- ### ZFrame and ZMessage - Message Containers Source: https://context7.com/enwi/dartzmq/llms.txt ZFrame represents a single message frame containing a payload, while ZMessage acts as a queue of ZFrames for managing multipart messages. ```APIDOC ## ZFrame and ZMessage ### Description ZFrame represents a single message frame containing a payload (Uint8List). ZMessage is a queue of ZFrames that represents a complete multipart message. The hasMore flag indicates if additional frames follow in the message. ### Usage - **ZFrame**: Instantiate with a Uint8List payload. - **ZMessage**: Use `add`, `addFirst`, or `addLast` to manage frames. ### Request Example ```dart final message = ZMessage(); message.add(ZFrame(Uint8List.fromList([1, 2, 3]))); ``` ``` -------------------------------- ### Perform Synchronous Socket Operations Source: https://context7.com/enwi/dartzmq/llms.txt Illustrates the use of ZSyncSocket for blocking request/reply patterns. The recv() method halts execution until a message is received, making it ideal for simple client-server interactions. ```dart import 'package:dartzmq/dartzmq.dart'; final context = ZContext(); final socket = context.createSyncSocket(SocketType.req); socket.connect('tcp://localhost:5555'); socket.sendString('Hello'); ZMessage reply = socket.recv(); print('Received reply: ${reply.first.payload}'); socket.send([1, 2, 3], flags: ZMQ_DONTWAIT); socket.close(); await context.stop(); ``` -------------------------------- ### ZSocket Asynchronous Operations Source: https://context7.com/enwi/dartzmq/llms.txt ZSocket provides non-blocking, stream-based message handling for event-driven applications. ```APIDOC ## ZSocket Asynchronous Operations ### Description Handles asynchronous messaging using Dart streams for messages, frames, and raw payloads. ### Streams - **messages**: Stream of ZMessage objects. - **frames**: Stream of ZFrame objects. - **payloads**: Stream of Uint8List payloads. ### Methods - **connect(String address)**: Connects the socket to a remote endpoint. - **send(List data)**: Sends data as a message. - **sendMessage(ZMessage message)**: Sends a multipart message. ### Usage Example ```dart socket.messages.listen((ZMessage message) { ... }); socket.sendString('Hello ZeroMQ'); ``` ``` -------------------------------- ### Dart ZMQ Send Flags: ZMQ_DONTWAIT and ZMQ_SNDMORE Source: https://context7.com/enwi/dartzmq/llms.txt Illustrates the use of ZMQ_DONTWAIT for non-blocking sends and ZMQ_SNDMORE to indicate multipart messages in Dart. It shows sending individual frames and complete messages using ZFrame and ZMessage. ```dart import 'dart:typed_data'; import 'package:dartzmq/dartzmq.dart'; final context = ZContext(); final socket = context.createSocket(SocketType.dealer); socket.connect('tcp://localhost:5566'); // Non-blocking send (won't wait if no peers available) socket.send([1, 2, 3], flags: ZMQ_DONTWAIT); socket.sendString('Hello', flags: ZMQ_DONTWAIT); // Send multipart message manually using SNDMORE flag socket.send([], flags: ZMQ_SNDMORE | ZMQ_DONTWAIT); // Empty delimiter socket.send([1, 2], flags: ZMQ_SNDMORE | ZMQ_DONTWAIT); // Part 1 socket.send([3, 4], flags: ZMQ_DONTWAIT); // Final part (no SNDMORE) // Using ZFrame with hasMore socket.sendFrame( ZFrame(Uint8List.fromList([1, 2, 3]), hasMore: true), flags: ZMQ_DONTWAIT, ); socket.sendFrame( ZFrame(Uint8List.fromList([4, 5, 6]), hasMore: false), flags: ZMQ_DONTWAIT, ); // Using ZMessage (handles SNDMORE automatically) final message = ZMessage(); message.add(ZFrame(Uint8List(0))); // Empty frame message.add(ZFrame(Uint8List.fromList([1, 2, 3]))); message.add(ZFrame(Uint8List.fromList([4, 5, 6]))); socket.sendMessage(message, flags: ZMQ_DONTWAIT); socket.close(); await context.stop(); ``` -------------------------------- ### ZSyncSocket Synchronous Operations Source: https://context7.com/enwi/dartzmq/llms.txt ZSyncSocket provides blocking receive operations, ideal for request/reply patterns. ```APIDOC ## ZSyncSocket Synchronous Operations ### Description Provides blocking I/O operations where the execution waits for a response from the peer. ### Methods - **recv()**: Blocks until a message is received. - **send(List data)**: Sends data synchronously. ### Usage Example ```dart socket.sendString('Hello'); ZMessage reply = socket.recv(); ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.