Search code examples
rustnanomsg

Example of nanomsg crate does not work


I tried the Rust nanomsg pubsub example, but it does not work.

I did each of these operations in separate console windows:

  1. cargo run --example pubsub -- device hoge

    It shows

    Subscribed to '[104, 111, 103, 101]'.
    Device is ready.
    
  2. cargo run --example pubsub -- client hoge

    It shows

    Subscribed to '[104, 111, 103, 101]'.
    
  3. cargo run --example pubsub -- server hoge

    It shows

    Server is ready.
    Published '[104, 111, 103, 101] #1'.
    Published '[104, 111, 103, 101] #2'.
    Published '[104, 111, 103, 101] #3'.
    ...
    

All three commands kept running, none of them exited. I expected console 2 to show:

Subscribed to '[104, 111, 103, 101]'.
Recv '[104, 111, 103, 101] #1'.
Recv '[104, 111, 103, 101] #2'.
Recv '[104, 111, 103, 101] #3'.
...

But nothing was displayed.

My environment is

  • Max OS X Sierra
  • nanomsg 1.0.0
  • rustc 1.16.0

Solution

  • It was an issue with the server code, which has already been fixed in the master branch (#173). Here's the faulty snippet (from repo):

    let msg = format!("{:?} #{}", topic,  count);
    match socket.write_all(msg.as_bytes()) {
        Ok(..) => println!("Published '{}'.", msg),
        Err(err) => {
            println!("Server failed to publish '{}'.", err);
            break
        }
    }
    

    The published message was built using the format! macro, which was improperly pretty-printing the topic as an array of bytes, rather than a slice of text. A different topic identifier led to no subscribers receiving the message.

    The example was fixed here by the current maintainer. As an ending note, users of this API have to keep in mind that the first bytes of a publish message always refer to the subscription topic.