Rust,libzmq,客户端仅发送消息,然后接收

Rust, libzmq, client only send message, when followed by receive

我正在测试 Rust libzmq 客户端

https://crates.io/crates/libzmq

https://docs.rs/libzmq/0.2.5/libzmq/struct.ClientBuilder.html

并偶然发现了这种奇怪的行为。

此客户端不会发送消息:

use libzmq::{prelude::*, *, ServerBuilder, ClientBuilder, TcpAddr};

fn main() -> Result<(), String> {
    
    let saddr = format!("{}:{}", "192.168.1.206","5540");
    println!("Strating client for {}", saddr);
    let addr2: TcpAddr = saddr.try_into().unwrap();
    
    let client = ClientBuilder::new()
        .connect(&addr2)
        .build().unwrap();
    client.send("test").unwrap();

    println!("Finished");
    Ok(())
}

这将发送:

use libzmq::{prelude::*, *, ServerBuilder, ClientBuilder, TcpAddr};

fn main() -> Result<(), String> {
    
    let saddr = format!("{}:{}", "192.168.1.206","5540");
    println!("Strating client for {}", saddr);
    let addr2: TcpAddr = saddr.try_into().unwrap();
    
    let client = ClientBuilder::new()
        .connect(&addr2)
        .build().unwrap();
    client.send("test").unwrap();

    let mut msg = Msg::new();
    client.recv(&mut msg).unwrap();

    println!("Finished");
    Ok(())
}

为了接收,我正在使用 python 服务器(但我也在 Rust 上进行了测试):

import zmq
if __name__ == '__main__':

    context = zmq.Context()
    socket = context.socket(zmq.SERVER)
    socket.bind("tcp://0.0.0.0:5540")
    print("waiting for hand shake")
    m = socket.recv(copy=False)
    print("got it...")
    socket.send(b'READY', routing_id=m.routing_id)
    print("sent reply")
    socket.close()
    context.term()

代码 1 在服务器端的输出:

waiting for hand shake
[blocked]

代码 2 在服务器端的输出:

waiting for hand shake
got it...
sent reply

将此版本用于 Rust:

[dependencies]
libzmq = "0.2.5"

libzmq crate 只是 libzmq C library. In the documentation for the C library 的包装器,您会发现这条注释:

NOTE: A successful invocation of zmq_msg_send() does not indicate that the message has been transmitted to the network, only that it has been queued on the 'socket' and 0MQ has assumed responsibility for the message.

在您的第一个示例中,由于程序在调用send 后立即退出,消息仍在libzmq 队列中,尚未传输。在您的第二个示例中,消息在您的程序等待 recv 调用时传输。