Skip to content

Instantly share code, notes, and snippets.

@pietern
Created December 31, 2010 13:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pietern/761021 to your computer and use it in GitHub Desktop.
Save pietern/761021 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <assert.h>
#include "hiredis.h"
#include "async.h"
#include "adapters/libev.h"
void message(redisAsyncContext *c, redisReply *reply, void *privdata) {
char *type, *channel;
((void) privdata);
if (reply != NULL) {
type = reply->element[0]->str;
channel = reply->element[1]->str;
printf("%s, %s", type, channel);
if (strcasecmp(type,"pmessage") == 0) {
printf(",%s", reply->element[3]->str);
redisAsyncCommand(c,NULL,NULL,"PUNSUBSCRIBE %s",channel);
} else if (strcasecmp(type,"punsubscribe") == 0) {
redisAsyncDisconnect(c);
}
printf("\n");
}
}
void disconnect(redisAsyncContext *c, redisReply *reply, void *privdata) {
((void) reply);
((void) privdata);
redisAsyncDisconnect(c);
}
redisAsyncContext *connect(EV_P) {
redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
if (c->errstr != NULL) {
printf("Error: %s\n", c->errstr);
redisAsyncFree(c);
exit(1);
}
assert(redisLibevAttach(EV_A_ c) == REDIS_OK);
return c;
}
int main (int argc, char **argv) {
((void) argc);
((void) argv);
signal(SIGPIPE, SIG_IGN);
struct ev_loop *loop = ev_default_loop(0);
int i;
redisAsyncContext *c1 = connect(EV_A);
redisAsyncContext *c2 = connect(EV_A);
for (i = 0; i < 4; i++) {
redisAsyncCommand(c1,message,NULL,"PSUBSCRIBE channel:%02d:*",i);
redisAsyncCommand(c2,disconnect,NULL,"PUBLISH channel:%02d:hello world",i);
}
ev_loop(loop, 0);
return 0;
}
psubscribe, channel:00:*
psubscribe, channel:01:*
psubscribe, channel:02:*
psubscribe, channel:03:*
pmessage, channel:00:*,world
pmessage, channel:01:*,world
pmessage, channel:02:*,world
pmessage, channel:03:*,world
punsubscribe, channel:00:*
punsubscribe, channel:01:*
punsubscribe, channel:02:*
punsubscribe, channel:03:*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment