Skip to content

Instantly share code, notes, and snippets.

@voidlily voidlily/client.c
Last active Oct 2, 2015

Embed
What would you like to do?
pubsub logger
#include <zmq.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define SOCKET_ADDR "ipc:///tmp/logger"
// source: http://stackoverflow.com/questions/122616/how-do-i-trim-leading-trailing-whitespace-in-a-standard-way
char *trim_whitespace(char *str)
{
char *end;
// Trim leading space
while(isspace(*str)) str++;
if(*str == 0) // All spaces?
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while(end > str && isspace(*end)) end--;
// Write new null terminator
*(end+1) = 0;
return str;
}
int string_empty(char *str) {
return strlen(str) == 0;
}
char *s_recv(void *socket) {
zmq_msg_t message;
zmq_msg_init(&message);
zmq_recv(socket, &message, 0);
int size = zmq_msg_size(&message);
char *string = malloc((size+1) * sizeof(char));
memcpy(string, zmq_msg_data(&message), size);
zmq_msg_close(&message);
string[size] = 0;
return string;
}
int main(void) {
void *context = zmq_init(1);
void *socket = zmq_socket(context, ZMQ_SUB);
zmq_setsockopt(socket, ZMQ_SUBSCRIBE, "", 0);
zmq_connect(socket, SOCKET_ADDR);
while(1) {
char *r_str = s_recv(socket);
char *str = trim_whitespace(r_str);
if (!string_empty(str)) {
printf("%s\n", str);
}
free(r_str);
}
zmq_close(socket);
zmq_term(context);
return 0;
}
#include <zmq.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define SOCKET_ADDR "ipc:///tmp/logger"
static int
s_send (void *socket, char *string) {
int rc;
zmq_msg_t message;
zmq_msg_init_size (&message, strlen (string));
memcpy (zmq_msg_data (&message), string, strlen (string));
rc = zmq_send (socket, &message, 0);
zmq_msg_close (&message);
return (rc);
}
int main(int argc, char *argv[]) {
void *context = zmq_init(1);
void *socket = zmq_socket(context, ZMQ_PUB);
zmq_bind(socket, SOCKET_ADDR);
char msg[20];
strlcpy(msg, argv[1], 20);
while(1) {
s_send(socket, msg);
}
zmq_close(socket);
zmq_term(context);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.