【问题标题】:nng to pynng pub/sub. No messages recieved by clientnng 到 nng 发布/订阅。客户端没有收到消息
【发布时间】:2020-08-28 05:55:56
【问题描述】:

我有以下服务器(C++):

#include <nng/nng.h>
#include <nng/protocol/pubsub0/pub.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <unistd.h>
void
fatal(const char *func, int rv)
{
        fprintf(stderr, "%s: %s\n", func, nng_strerror(rv));
}
int main(int argc, char* argv[]){
    nng_socket sock;
    int rv;
    std::string url = "tcp://0.0.0.0:" + std::to_string(5563);
    if ((rv = nng_pub0_open(&sock)) != 0) {
            fatal("nng_pub0_open", rv);
    }
    if ((rv = nng_listen(sock, url.c_str(), NULL, 0)) < 0) {
            fatal("nng_listen", rv);
    }
    while(1){
        std::string msg = std::string("msg");
        //if ((rv = nng_send(sock, (void*)frame, bpp * nImgW * nImgH, 0)) != 0) {
        if ((rv = nng_send(sock, (void*)msg.c_str(), 3, 0)) != 0) {
            fatal("nng_send", rv);
        }else{
            std::cout << "Frame Sent... "<< std::endl;
        } 
        sleep(1);
    }
}

还有以下客户端(python):

import pynng
from pynng import Pub0, Sub0, Timeout
cam_path = "tcp://127.0.0.1:5563"
with Sub0(dial=cam_path,recv_timeout=2000, topics=b'') as sub:
    sub.recv_max_size = 0 #recieve msg of any size
    while(1):
        try:
            print("waiting for msg")
            img = sub.recv()
            print(img)
        except pynng.exceptions.Timeout as e:
            print('Timed out, retrying...')

我不明白为什么没有消息到达客户端。我已经设置了主题和 recv_max_size 但仍然没有消息到达客户端。 我现在在这里做错了什么?

【问题讨论】:

  • 我发现了问题所在。这是因为另一个 nng 发布者正在同一个端口上运行。为什么尝试绑定到被占用的地址/端口时没有抛出错误?
  • 我认为您只需将支票从 nng_listen(...) &lt; 0 更改为 nng_listen(...) != 0nng_listen 在无法绑定时会返回错误代码。

标签: python c++ nanomsg pynng


【解决方案1】:

“我现在做错了什么?”

您碰巧盲目地假设事情以您的代码不会尝试验证的方式发生。老汇编狼在开始编写代码之前常常声明 # ASSUME NOTHING :o)

Pieter Hintjens,著名的 AMQP / ZeroMQ 传播大师(nanomsg / nng 的哥哥)使用来自assert-s 的显式 POSACK-s:

if ( (  aRetCODE = nng_pub0_open( &sock ) ) != 0 ) {
        fatal( "nng_pub0_open",
                aRetCODE );
}
assert( aRetCODE == 0 && "EXC: Pub0 socket failed to instantiate" );

if ( (  aRetCODE = nng_listen( sock, url.c_str(), NULL, 0 ) ) < 0 ) {
        fatal( "nng_listen",
                aRetCODE );
}
assert( aRetCODE == 0 && "EXC: Pub0 socket failed to .listen()" );

Python 也有一个类似的 assert-tool 用于显式 POSACK 检查,因此值得使用它们来完善代码的稳健性,因为 Pieter Hintjens 让 Martin Sustrik 可以在您阅读 API 的任何地方这样做:o)

assert rc == 0, "INF: some condition was not met for ( %r )" % someVariableNAME

很高兴为您的项目使用 nng / pynng

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多