1

这是用于简单请求的 ZeroMq C++ 代码 - 两者交替交换消息的回复。但是当消息只连续发送时会发生错误......

回复代码:

include zmq.hpp
include string
include iostream
include unistd.h
include ctime

    int main () {
// Prepare our context and socket
  zmq::context_t context (1);
  zmq::socket_t socket (context, ZMQ_REP);
  socket.bind ("tcp://*:5557");
  zmq::message_t reply (5);

  memcpy ((void *) reply.data (), "World", 5);
  zmq::message_t request;

// Wait for next request from client
  socket.recv (&request);
///////////////// """observe_line_1"""
  std::cout << "Received Hello" << std::endl;
  while (true)
  {
 // Send reply back to client
    socket.send (reply);
  }
  return 0;
}

请求代码 :

include zmq.hpp
include string
include iostream
include ctime

int main ()
{
  zmq::context_t context (1);
  zmq::socket_t socket (context, ZMQ_REQ);

  socket.connect ("tcp://localhost:5557");
  zmq::message_t request (6);
  memcpy ((void *) request.data (), "Hello", 5);
  zmq::message_t reply;

  socket.send(request);
//////////////////////////////////////////"""observe_line_2"""
   for (int request_nbr = 0; request_nbr != 1000; request_nbr++) 
   {
    socket.recv (&reply);
    std::cout << "Received World " << request_nbr << std::endl;
   }
   return 0;
}

输出 执行 Reqply 然后执行请求然后出现以下错误

terminate called after throwing an instance of 'zmq::error_t'
  what():  Operation cannot be accomplished in current state
Aborted

观察点

当“observe_line_1”在它下面的for循环内并且“observe_line_2”在它下面的while循环内并执行时,代码成功执行而没有任何错误????

4

2 回答 2

4

REQ-REP 模型不允许为一个请求发送多个回复。

REQ-REP 套接字对是同步的。客户端发出 zmq_send(),然后是 zmq_recv(),在一个循环中(或者如果它只需要一次)。执行任何其他序列(例如,连续发送两条消息)将导致 send 或 recv 调用的返回码为 -1。类似地,服务会按照需要的频率依次发出 zmq_recv() 和 zmq_send()。

参考替代套接字类型也许这会有所帮助

于 2013-04-29T08:00:51.567 回答
0

实际上,您可以连续发送多条消息,只要您发送带有 flags=zmq::SNDMORE 的数据即可。

于 2021-08-31T04:52:54.967 回答