add test connection to the nats server.

This commit is contained in:
NADAL Jean-Baptiste
2019-11-08 16:08:26 +01:00
parent 657ce4f051
commit 8e8a649a88
3 changed files with 53 additions and 4 deletions

View File

@@ -19,6 +19,7 @@ add_executable (domo-iot ${source_files})
target_link_libraries (domo-iot target_link_libraries (domo-iot
LINK_PUBLIC LINK_PUBLIC
nats
rt rt
) )

View File

@@ -27,6 +27,21 @@
#include <nats.h> #include <nats.h>
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 * @fn main
* *
@@ -34,12 +49,41 @@
*/ */
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
natsConnection *conn = NULL; natsConnection *conn = NULL;
natsSubscription *sub = NULL; natsSubscription *sub = NULL;
natsStatus s; natsStatus s;
volatile bool done = false; volatile bool done = false;
printf("Listening on subject 'foo'\n"); 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; return 0;
} }

4
tools/nats-pub.sh Executable file
View File

@@ -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"