/**
g++ req-rep-router-dealer-requester.cpp -lzmq -g -O0 -o objs/req-rep-router-dealer-requester
*/
#include <zmq.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
int main(int argc, char** argv){
void* context = zmq_ctx_new();
void* requester = zmq_socket(context, ZMQ_REQ);
assert(zmq_connect(requester, "tcp://localhost:1990") == 0);
srand(0);
while(true){
char buf[64];
snprintf(buf, sizeof(buf), "rand=%d", rand());
zmq_msg_t msg;
zmq_msg_init_size(&msg, strlen(buf)+1);
memcpy(zmq_msg_data(&msg), buf, strlen(buf)+1);
zmq_msg_send(&msg, requester, 0);
zmq_msg_close(&msg);
zmq_msg_t reply;
zmq_msg_init(&reply);
zmq_msg_recv(&reply, requester, 0);
printf("recv msg=%s\n", zmq_msg_data(&reply));
zmq_msg_close(&reply);
}
zmq_close(requester);
zmq_ctx_destroy(context);
return 0;
}
/**
g++ req-rep-router-dealer-broker.cpp -lzmq -g -O0 -o objs/req-rep-router-dealer-broker
*/
#include <zmq.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
int main(int argc, char** argv){
void* context = zmq_ctx_new();
void* router = zmq_socket(context, ZMQ_ROUTER);
void* dealer = zmq_socket(context, ZMQ_DEALER);
assert(zmq_bind(router, "tcp://*:1990") == 0);
assert(zmq_bind(dealer, "tcp://*:1991") == 0);
zmq_proxy(router, dealer, NULL);
zmq_close(dealer);
zmq_close(router);
zmq_ctx_destroy(context);
return 0;
}
/**
g++ req-rep-router-dealer-replyer.cpp -lzmq -g -O0 -o objs/req-rep-router-dealer-replyer
*/
#include <zmq.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
int main(int argc, char** argv){
void* context = zmq_ctx_new();
void* replyer = zmq_socket(context, ZMQ_REP);
assert(zmq_connect(replyer, "tcp://localhost:1991") == 0);
srand(0);
while(true){
zmq_msg_t msg;
zmq_msg_init(&msg);
zmq_msg_recv(&msg, replyer, 0);
printf("recv msg: %s\n", zmq_msg_data(&msg));
zmq_msg_send(&msg, replyer, 0);
zmq_msg_close(&msg);
usleep(rand() % 100 * 1000);
}
zmq_close(replyer);
zmq_ctx_destroy(context);
return 0;
}
运行:
./objs/req-rep-router-dealer-requester
./objs/req-rep-router-dealer-broker
./objs/req-rep-router-dealer-replyer