zmq: request-reply multiple clients to multiple server, brute force way

/**
g++ req-res-N2M-brute-force-server.cpp -lzmq -g -O0 -o objs/req-res-N2M-brute-force-server
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zmq.h>
#include <assert.h>

int main(int argc, char** argv){
    void* context = zmq_ctx_new();
    void* responder = zmq_socket(context, ZMQ_REP);
    
    char id[256];
    memset(id, 0, sizeof(id));
    
    assert(argc > 1);
    for(int i = 1; i < argc; i++){
        const char* port = argv[i];
        
        char bind[64];
        snprintf(bind, sizeof(bind), "tcp://*:%s", port);
        printf("responder bind at: %s\n", bind);
        assert(zmq_bind(responder, bind) == 0);
        
        strcat(id, port);
        strcat(id, ",");
    }
    
    while(true){
        zmq_msg_t msg;
        zmq_msg_init(&msg);
        zmq_msg_recv(&msg, responder, 0);
        printf("get message: %s\n", zmq_msg_data(&msg));
        
        zmq_msg_t reply;
        zmq_msg_init_size(&reply, strlen((char*)zmq_msg_data(&msg))+1+strlen(id));
        memcpy(zmq_msg_data(&reply), id, strlen(id));      
        memcpy((char*)zmq_msg_data(&reply) + strlen(id), zmq_msg_data(&msg), strlen((char*)zmq_msg_data(&msg))+1);  
        zmq_msg_send(&reply, responder, 0);
        
        zmq_msg_close(&reply);
        zmq_msg_close(&msg);
    }
    
    zmq_close(responder);
    zmq_ctx_destroy(context);
    return 0;
}

/**
g++ req-res-N2M-brute-force-client.cpp -lzmq -g -O0 -o objs/req-res-N2M-brute-force-client
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zmq.h>
#include <assert.h>

int main(int argc, char** argv){
    void* context = zmq_ctx_new();
    void* requester = zmq_socket(context, ZMQ_REQ);
    
    assert(argc > 1);
    for(int i = 1; i < argc; i++){
        char endpoint[64];
        snprintf(endpoint, sizeof(endpoint), "tcp://localhost:%s", argv[i]);
        assert(zmq_connect(requester, endpoint) == 0);
    }
    
    srand(0);
    
    while(true){
        char buf[64];
        snprintf(buf, sizeof(buf), "msg, 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("get a message:%s\n", zmq_msg_data(&reply));
        zmq_msg_close(&reply);
        
        usleep(rand()%100 * 1000);
    }
    
    zmq_close(requester);
    zmq_ctx_destroy(context);
    return 0;
}

运行:

./objs/req-res-N2M-brute-force-server 1990 1991 1992 1993
./objs/req-res-N2M-brute-force-client 1990 1992

你可能感兴趣的:(zmq: request-reply multiple clients to multiple server, brute force way)