From 8e8a649a880808f528dc57e7f27582f240be1d16 Mon Sep 17 00:00:00 2001 From: NADAL Jean-Baptiste Date: Fri, 8 Nov 2019 16:08:26 +0100 Subject: [PATCH] add test connection to the nats server. --- src/CMakeLists.txt | 1 + src/domo-iot.c | 52 ++++++++++++++++++++++++++++++++++++++++++---- tools/nats-pub.sh | 4 ++++ 3 files changed, 53 insertions(+), 4 deletions(-) create mode 100755 tools/nats-pub.sh diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index fba3511..cb78cb8 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -19,6 +19,7 @@ add_executable (domo-iot ${source_files}) target_link_libraries (domo-iot LINK_PUBLIC + nats rt ) diff --git a/src/domo-iot.c b/src/domo-iot.c index 4e9e5a2..7b5e353 100644 --- a/src/domo-iot.c +++ b/src/domo-iot.c @@ -27,6 +27,21 @@ #include +static void +onMsg(natsConnection *nc, natsSubscription *sub, natsMsg *msg, void *closure) +{ + printf("Received msg: %s - %.*s\n", + natsMsg_GetSubject(msg), + natsMsg_GetDataLength(msg), + natsMsg_GetData(msg)); + + // Need to destroy the message! + natsMsg_Destroy(msg); + + // Notify the main thread that we are done. + *(bool *)(closure) = true; +} + /*! ---------------------------------------------------------------------------- * @fn main * @@ -34,12 +49,41 @@ */ int main(int argc, char *argv[]) { - natsConnection *conn = NULL; - natsSubscription *sub = NULL; - natsStatus s; - volatile bool done = false; + natsConnection *conn = NULL; + natsSubscription *sub = NULL; + natsStatus s; + volatile bool done = false; printf("Listening on subject 'foo'\n"); + // Creates a connection to the default NATS URL + s = natsConnection_ConnectTo(&conn, "nats.nadal-fr.com"); + if (s == NATS_OK) + { + // Creates an asynchronous subscription on subject "foo". + // When a message is sent on subject "foo", the callback + // onMsg() will be invoked by the client library. + // You can pass a closure as the last argument. + s = natsConnection_Subscribe(&sub, conn, "foo", onMsg, (void *)&done); + } + if (s == NATS_OK) + { + for (; !done;) + { + nats_Sleep(100); + } + } + + // Anything that is created need to be destroyed + natsSubscription_Destroy(sub); + natsConnection_Destroy(conn); + + // If there was an error, print a stack trace and exit + if (s != NATS_OK) + { + nats_PrintLastErrorStack(stderr); + exit(2); + } + return 0; } diff --git a/tools/nats-pub.sh b/tools/nats-pub.sh new file mode 100755 index 0000000..672c28e --- /dev/null +++ b/tools/nats-pub.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +go get github.com/nats-io/go-nats-examples/tools/nats-pub +${HOME}/go/bin/nats-pub -s nats://nats.nadal-fr.com:4222 "$1" "$2"