如何发送不同长度的消息而不用尾随字节\ x00?

时间:2017-04-27 04:05:34

标签: c++ zeromq

20message.data(),zmq::message_t message(20); snprintf ((char *) message.data(), 20 ,"%05d %d %d", zipcode, temperature, relhumidity); publisher.send(message); message(20)的影响与下面代码中的20有什么关系?

message.data(),

通过阅读文档,\x00将消息初始化为20个字节。 "%05d %d %d", zipcode, temperature, relhumidity之后$query = mysqli_query($con,"SELECT COUNT(id) FROM users WHERE name = '$name'"); 做了什么?

如何更改消息的大小以发送消息而不追踪字节$query = mysqli_query($con,"SELECT name FROM users WHERE name = '$name'"); ?是tags = db.Table('tags', db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')), db.Column('page_id', db.Integer, db.ForeignKey('page.id')) ) class Page(db.Model): id = db.Column(db.Integer, primary_key=True) tags = db.relationship('Tag', secondary=tags, backref=db.backref('pages', lazy='dynamic')) class Tag(db.Model): id = db.Column(db.Integer, primary_key=True) 可以在外面声明,并且该变量的长度可用于启动消息并发送它吗?

1 个答案:

答案 0 :(得分:1)

您可以使用限制为零的snprintf()来衡量数据在为其分配空间之前的大小:

auto length = std::snprintf(nullptr, 0, "%05d %d %d", zipcode, temperature, relhumidity) + 1;
// +1 to account for null terminating character.

zmq::message_t message(length);

std::snprintf(
    static_cast<char *>(message.data()), length,
    "%05d %d %d", zipcode, temperature, relhumidity
);

publisher.send(message);

你也可以格式化为你知道足够大的本地缓冲区,测量字符串的长度,然后复制它:

char buffer[64];

auto length = std::snprintf(buffer, 64, "%05d %d %d", zipcode, temperature, relhumidity) + 1;

zmq::message_t message(length);

std::copy(buffer, buffer + length, static_cast<char *>(message.data());

publisher.send(message);