ZeroMQ(C):基本请求 - 回复问题

时间:2016-03-01 11:59:27

标签: client-server zeromq

请考虑以下最小的请求 - 回复设置示例:

SERVER:

// Minimal example request & reply (REQ-REP)
// SERVER

#include <zmq.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>

int main (void) {
    //  Socket to talk to clients
    void *context = zmq_ctx_new ();
    void *responder = zmq_socket (context, ZMQ_REP);
    int rc = zmq_bind (responder, "tcp://*:5555");
    assert (rc == 0);

    while (1) {
         char buffer [2];
         zmq_recv (responder, buffer, 2, 0);
         printf ("Received: %s\n",buffer);
    }
    return 0;
}

客户端:

// Minimal example request & reply (REQ-REP)
// CLIENT

#include <zmq.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>

int main (void) {
    void *context = zmq_ctx_new ();
    void *requester = zmq_socket (context, ZMQ_REQ);
    zmq_connect (requester, "tcp://localhost:5555");
    zmq_send (requester, "0", 2, 0);
    zmq_close (requester);
    zmq_ctx_destroy (context);
    return 0;
}

结果如下:

Received: 0
Received: 0
...

..并且永远在标准输出中继续打击这一行。

我的期望:

Received: 0

显然,我认为请求 - 回复是完全错误的。

(20小时后)

我不知道为什么。但背靠背zmq_send()解决了这个问题。以下(服务器)代码段按预期工作:

int main (void) {
    //  Socket to talk to clients
    void *context = zmq_ctx_new ();
    void *responder = zmq_socket (context, ZMQ_REP);
    int rc = zmq_bind (responder, "tcp://*:5555");
    assert (rc == 0);

    while (1) {
         char buffer [2];
         zmq_recv (responder, buffer, 2, 0);
         zmq_send (responder, "ACK", 3, 0);
         printf ("Received: %s\n",buffer);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:1)

这是有道理的:REP套接字接收和发送,REQ套接字发送和接收。

在您的示例中,您应该尝试使用PUSH套接字发送和接收PULL套接字。