nng至pynng发布/订阅。客户未收到任何消息

2024-06-16 13:48:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下服务器(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,但仍然没有消息到达客户端。 我现在做错什么了


Tags: sendsizestringifincludemsgintsock
1条回答
网友
1楼 · 发布于 2024-06-16 13:48:14

Q : "What am I doing wrong here now?"

您碰巧盲目地假设事情的发生方式与您的代码不尝试验证的方式非常相似。旧的汇编程序狼在启动代码之前通常会声明# ASSUME NOTHING(o)

著名的AMQP/ZeroMQ福音传道者Pieter Hintjens(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工具用于显式POSACK检查,因此值得使用它们来提高代码的健壮性,正如Pieter Hintjens让Martin Sustrik在您阅读API时所做的那样:o)

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

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

相关问题 更多 >