int zmq_recv (void *s_, void *buf_, size_t len_, int flags_)
{
if (!s_ || !((zmq::socket_base_t*) s_)->check_tag ()) {
errno = ENOTSOCK;
return -1;
}
zmq_msg_t msg; // 创建消息结构
int rc = zmq_msg_init (&msg); // 初始化空消息
errno_assert (rc == 0);
zmq::socket_base_t *s = (zmq::socket_base_t *) s_;
int nbytes = s_recvmsg (s, &msg, flags_); // 接收消息
if (unlikely (nbytes < 0)) {
int err = errno;
rc = zmq_msg_close (&msg);
errno_assert (rc == 0);
errno = err;
return -1;
}
// At the moment an oversized message is silently truncated.
// TODO: Build in a notification mechanism to report the overflows.
size_t to_copy = size_t (nbytes) < len_ ? size_t (nbytes) : len_; //计算消息大小
memcpy (buf_, zmq_msg_data (&msg), to_copy); // 通过zmq_msg_data()获得消息的data地址,拷贝到buf_中
rc = zmq_msg_close (&msg); // 释放或销毁消息
errno_assert (rc == 0);
return nbytes;
}
---------------------------------------------------------------------
int zmq_recvmsg (void *s_, zmq_msg_t *msg_, int flags_)
{
return zmq_msg_recv (msg_, s_, flags_);
}
----------------------------------------------------------------------
int zmq_msg_recv (zmq_msg_t *msg_, void *s_, int flags_)
{
if (!s_ || !((zmq::socket_base_t*) s_)->check_tag ()) {
errno = ENOTSOCK;
return -1;
}
zmq::socket_base_t *s = (zmq::socket_base_t *) s_;
int result = s_recvmsg (s, msg_, flags_);
return result;
}
-----------------------------------------------------------------------
static int
s_recvmsg (zmq::socket_base_t *s_, zmq_msg_t *msg_, int flags_)
{
int rc = s_->recv ((zmq::msg_t*) msg_, flags_);
if (unlikely (rc < 0))
return -1;
return (int) zmq_msg_size (msg_);// 计算消息的大小
}
---------------------------------------------------------------------------------
=================================================================================
---------------------------------------------------------------------------------
int zmq_send (void *s_, const void *buf_, size_t len_, int flags_)
{
if (!s_ || !((zmq::socket_base_t*) s_)->check_tag ()) {
errno = ENOTSOCK;
return -1;
}
zmq_msg_t msg; // 创建消息结构
int rc = zmq_msg_init_size (&msg, len_); // 以buf长度初始化成消息
if (rc != 0)
return -1;
memcpy (zmq_msg_data (&msg), buf_, len_); // 将buf的内容拷贝给消息
zmq::socket_base_t *s = (zmq::socket_base_t *) s_;
rc = s_sendmsg (s, &msg, flags_); // 发送消息
if (unlikely (rc < 0)) {
int err = errno;
int rc2 = zmq_msg_close (&msg); // 释放和销毁消息
errno_assert (rc2 == 0);
errno = err;
return -1;
}
// Note the optimisation here. We don't close the msg object as it is
// empty anyway. This may change when implementation of zmq_msg_t changes.
return rc;
}
从注释中可以看出消息发送的流程,czmq,jzmq等已经做了封装,也可以自己做封装。
zmq源码阅读 —— zmq_send()和zmq_recv()
最新推荐文章于 2024-01-10 21:24:37 发布