Last active
September 9, 2025 11:43
-
-
Save peterhellberg/3249c48ff3572580009549106abb6a7b to your computer and use it in GitHub Desktop.
A pretty minimal publisher example using nats.c
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <nats/nats.h> | |
| #include <string.h> | |
| const char *subj = "foo"; | |
| const char *payload = "example"; | |
| int64_t start = 0; | |
| int64_t total = 1000000; | |
| volatile int64_t count = 0; | |
| volatile int64_t elapsed = 0; | |
| static void printPerf(const char *label) { | |
| if (start && !elapsed) | |
| elapsed = nats_Now() - start; | |
| if (elapsed <= 0) | |
| printf("\nNot enough messages or too fast to report performance!\n"); | |
| else | |
| printf("\n%s %" PRId64 " messages in %" PRId64 " ms (%d msgs/sec)\n", | |
| label, count, elapsed, (int)((count * 1000) / elapsed)); | |
| } | |
| int main(void) { | |
| natsConnection *conn = NULL; | |
| natsStatus s = natsConnection_Connect(&conn, NULL); | |
| if (s != NATS_OK) { | |
| printf("Error: %u - %s\n", s, natsStatus_GetText(s)); | |
| nats_PrintLastErrorStack(stderr); | |
| nats_Close(); | |
| return 1; | |
| } | |
| printf("Sending %" PRId64 " messages to subject '%s'\n", total, subj); | |
| start = nats_Now(); | |
| int dataLen = (int)strlen(payload); | |
| for (count = 0; count < total && s == NATS_OK; count++) | |
| s = natsConnection_Publish(conn, subj, payload, dataLen); | |
| if (s == NATS_OK) | |
| s = natsConnection_FlushTimeout(conn, 1000); | |
| if (s == NATS_OK) | |
| printPerf("Sent"); | |
| else | |
| printf("Error: %u - %s\n", s, natsStatus_GetText(s)); | |
| natsConnection_Destroy(conn); | |
| nats_Close(); | |
| return 0; | |
| } |
Author
peterhellberg
commented
Sep 9, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment