文档

  语言:   库:

入门

ZeroMQ(也可拼写为 ØMQ、0MQ 或 ZMQ)是一个高性能异步消息库,旨在用于分布式或并发应用程序。它提供一个消息队列,但与面向消息的中间件不同,ZeroMQ 系统无需专门的消息代理即可运行。

ZeroMQ 支持常见的消息模式(发布/订阅、请求/回复、客户端/服务器等),并通过多种传输方式(TCP、进程内、进程间、多播、WebSocket 等)进行传输,使进程间消息传递像线程间消息传递一样简单。这使您的代码清晰、模块化且极易扩展。

ZeroMQ 由庞大的贡献者社区开发。有许多流行编程语言的第三方绑定,以及 C# 和 Java 的原生移植。

ZeroMQ 中的 Zero

ZeroMQ 的理念始于 Zero。Zero 代表零代理(ZeroMQ 无代理)、零延迟、零成本(它是免费的)和零管理。

更普遍地讲,“zero” 指的是贯穿项目的极简主义文化。我们通过消除复杂性来增强功能,而不是通过暴露新功能。

指南

指南 解释如何使用 ØMQ,涵盖基础、中级和高级用法,包含 60 多张图表和 750 个示例(共 28 种语言)。

也可作为 O'Reilly 出版的提供。

Libzmq - 低层库

Libzmq (https://github.com/zeromq/libzmq) 是大多数不同语言绑定的低层库。Libzmq 提供了 C-API 接口,使用 C++ 实现。您很少会直接使用 libzmq,但是如果您想为项目贡献力量或学习 zeromq 的内部原理,这里是起点。

选择您的语言

选择您的库

libzmq | C

C++ 中的 ZeroMQ 核心引擎
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

czmq | C

libzmq 的高层绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

zmqpp | C++

libzmq 的高层绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

cppzmq | C++

libzmq 的仅头文件 C++ 绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

azmq | C++

libzmq 的 Boost Asio 风格绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

czmqpp | C++

czmq 的最小、简单包装器
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

fbzmq | C++

Facebook ZeroMQ 包装器
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

NetMQ | C#

用于 .Net 的 C# ZeroMQ 引擎
tcp, inproc, pgm
PLAIN, CURVE

clrzmq4 | C#

libzmq 的 .Net 绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

dartzmq | Dart

libzmq 的 Dart 绑定
tcp
PLAIN, CURVE

Chumak | Erlang

Erlang 中的 ZeroMQ 引擎
tcp
PLAIN, CURVE

ezmq | Erlang

Erlang 中的 ZeroMQ 引擎
tcp
PLAIN

erlang-czmq | Erlang

czmq 的 Erlang 绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

FsNetMQ | F#

NetMQ 的 F# 绑定
tcp, inproc, pgm
PLAIN, CURVE

fszmq | F#

libzmq 的 F# 绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

zmq4 | Go

libzmq 的 Go 绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

goczmq | Go

czmq 的 Go 绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

zeromq4-haskell | Haskell

libzmq 的 Haskell 绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

JeroMQ | Java

纯 Java ZeroMQ 引擎
tcp, inproc, ipc (仅 JeroMQ)
PLAIN, CURVE

JZMQ | Java

libzmq 的 JNI 绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

jczmq | Java

czmq 的 JNI 绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

zeromqjs | Node.js

czmq 的 Node.js 绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

perlzmq | Perl

libzmq 的 Perl 绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

Pyzmq | Python

libzmq 的 Python 绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

rbzmq | Ruby

libzmq 的 Ruby 绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

rust-zmq | Rust

libzmq 的 Rust 绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

zzmq | Zig

CZMQ 的 Zig 绑定
tcp, udp, pgm, norm, ipc, inproc, gssapi
PLAIN, CURVE

第一个示例

那么让我们从一些代码开始,比如“Hello world”示例(当然)。

//  Hello World server
#include <zmq.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>

int main (void)
{
    //  Socket to talk to clients
    void *context = zmq_ctx_new ();
    void *responder = zmq_socket (context, ZMQ_REP);
    int rc = zmq_bind (responder, "tcp://*:5555");
    assert (rc == 0);

    while (1) {
        char buffer [10];
        zmq_recv (responder, buffer, 10, 0);
        printf ("Received Hello\n");
        sleep (1);          //  Do some 'work'
        zmq_send (responder, "World", 5, 0);
    }
    return 0;
}
//  Hello World server
#include <czmq.h>

int main (void)
{
    //  Socket to talk to clients
    zsock_t *responder = zsock_new (ZMQ_REP);
    int rc = zsock_bind (responder, "tcp://*:5555");
    assert (rc == 5555);

    while (1) {
        char *str = zstr_recv (responder);
        printf ("Received Hello\n");
        sleep (1);          //  Do some 'work'
        zstr_send (responder, "World");
        zstr_free (&str);
    }
    return 0;
}
//  Hello World server

#include <zmqpp/zmqpp.hpp>
#include <string>
#include <iostream>
#include <chrono>
#include <thread>

using namespace std;

int main(int argc, char *argv[]) {
  const string endpoint = "tcp://*:5555";

  // initialize the 0MQ context
  zmqpp::context context;

  // generate a pull socket
  zmqpp::socket_type type = zmqpp::socket_type::reply;
  zmqpp::socket socket (context, type);

  // bind to the socket
  socket.bind(endpoint);
  while (1) {
    // receive the message
    zmqpp::message message;
    // decompose the message 
    socket.receive(message);
    string text;
    message >> text;

    //Do some 'work'
    std::this_thread::sleep_for(std::chrono::seconds(1));
    cout << "Received Hello" << endl;
    socket.send("World");
  }

}
#include <string>
#include <chrono>
#include <thread>
#include <iostream>

#include <zmq.hpp>

int main() 
{
    using namespace std::chrono_literals;

    // initialize the zmq context with a single IO thread
    zmq::context_t context{1};

    // construct a REP (reply) socket and bind to interface
    zmq::socket_t socket{context, zmq::socket_type::rep};
    socket.bind("tcp://*:5555");

    // prepare some static data for responses
    const std::string data{"World"};

    for (;;) 
    {
        zmq::message_t request;

        // receive a request from client
        socket.recv(request, zmq::recv_flags::none);
        std::cout << "Received " << request.to_string() << std::endl;

        // simulate work
        std::this_thread::sleep_for(1s);

        // send the reply to the client
        socket.send(zmq::buffer(data), zmq::send_flags::none);
    }

    return 0;
}
hello_world_server 示例在 azmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/cpp/azmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_server.md
    $example_dir/hello_world_server.md
hello_world_server 示例在 czmqpp 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/cpp/czmqpp
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_server.md
    $example_dir/hello_world_server.md
hello_world_server 示例在 fbzmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/cpp/fbzmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_server.md
    $example_dir/hello_world_server.md
using System;
using System.Threading;
using NetMQ;
using NetMQ.Sockets;

static class Program
{
    public static void Main()
    {        
        using (var responder = new ResponseSocket())
        {
            responder.Bind("tcp://*:5555");

            while (true) 
            {
                string str = responder.ReceiveFrameString();
                Console.WriteLine("Received Hello");
                Thread.Sleep(1000);  //  Do some 'work'
                responder.SendFrame("World");
            }
        }
    }
}
hello_world_server 示例在 clrzmq4 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/csharp/clrzmq4
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_server.md
    $example_dir/hello_world_server.md
hello_world_server 示例在 dartzmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/dart/dartzmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_server.md
    $example_dir/hello_world_server.md
-module(hello_world_server).
-export([main/0]).

main() ->
    application:start(chumak),
    {ok, Socket} = chumak:socket(rep, "hello world server"),

    {ok, _BindPid} = chumak:bind(Socket, tcp, "localhost", 5555),
    loop(Socket).

loop(Socket) ->
    Reply = chumak:recv(Socket),
    io:format("Question: ~p\n", [Reply]),
    chumak:send(Socket, <<"Hello Friend">>),
    loop(Socket).
hello_world_server 示例在 ezmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/erlang/ezmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_server.md
    $example_dir/hello_world_server.md
hello_world_server 示例在 erlang-czmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/erlang/erlang-czmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_server.md
    $example_dir/hello_world_server.md
hello_world_server 示例在 FsNetMQ 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/fsharp/fsnetmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_server.md
    $example_dir/hello_world_server.md
hello_world_server 示例在 fszmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/fsharp/fszmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_server.md
    $example_dir/hello_world_server.md
package main

import (
        "log"
        "time"

        zmq "github.com/pebbe/zmq4"
)

func main() {
        zctx, _ := zmq.NewContext()

        s, _ := zctx.NewSocket(zmq.REP)
        s.Bind("tcp://*:5555")

        for {
                // Wait for next request from client
                msg, _ := s.Recv(0)
                log.Printf("Received %s\n", msg)

                // Do some 'work'
                time.Sleep(time.Second * 1)

                // Send reply back to client
                s.Send("World", 0)
        }
}
package main

import (
	"log"
	"time"

	"github.com/zeromq/goczmq"
)

func main() {
	// Create a router socket and bind it to port 5555.
	router, err := goczmq.NewRouter("tcp://*:5555")
	if err != nil {
		log.Fatal(err)
	}
	defer router.Destroy()

	log.Println("router created and bound")

	for {
		// Receive the message. Here we call RecvMessage, which
		// will return the message as a slice of frames ([][]byte).
		// Since this is a router socket that support async
		// request / reply, the first frame of the message will
		// be the routing frame.
		request, err := router.RecvMessage()
		if err != nil {
			log.Fatal(err)
		}

		log.Printf("router received '%s' from '%v'", request[1], request[0])

		// Do some 'work'
		time.Sleep(time.Second * 1)

		// Send a reply. First we send the routing frame, which
		// lets the dealer know which client to send the message.
		// The FlagMore flag tells the router there will be more
		// frames in this message.
		err = router.SendFrame(request[0], goczmq.FlagMore)
		if err != nil {
			log.Fatal(err)
		}

		log.Printf("router sent 'World'")

		// Next send the reply. The FlagNone flag tells the router
		// that this is the last frame of the message.
		err = router.SendFrame([]byte("World"), goczmq.FlagNone)
		if err != nil {
			log.Fatal(err)
		}
	}
}
hello_world_server 示例在 zeromq4-haskell 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/haskell/zeromq4-haskell
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_server.md
    $example_dir/hello_world_server.md
//  Hello World server in Java
//  Binds REP socket to tcp://*:5555
//  Expects "Hello" from client, replies with "World"

import org.zeromq.SocketType;
import org.zeromq.ZMQ;
import org.zeromq.ZContext;

public class hwserver
{
  public static void main(String[] args) throws Exception
  {
    try (ZContext context = new ZContext()) {
      //  Socket to talk to clients
      ZMQ.Socket socket = context.createSocket(SocketType.REP);
      socket.bind("tcp://*:5555");

      while (!Thread.currentThread().isInterrupted()) {
        byte[] reply = socket.recv(0);
        System.out.println(
          "Received " + ": [" + new String(reply, ZMQ.CHARSET) + "]"
        );
        String response = "world";
        socket.send(response.getBytes(ZMQ.CHARSET), 0);
        Thread.sleep(1000); //  Do some 'work'
      }
    }
  }
}
hello_world_server 示例在 JZMQ 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/java/jzmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_server.md
    $example_dir/hello_world_server.md
hello_world_server 示例在 jczmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/java/jczmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_server.md
    $example_dir/hello_world_server.md
//  Hello World server
//  Binds REP socket to tcp://*:5555
//  Expects "Hello" from client, replies with "World"

const zmq = require('zeromq');

async function runServer() {
  const sock = new zmq.Reply();

  await sock.bind('tcp://*:5555');

  for await (const [msg] of sock) {
    console.log('Received ' + ': [' + msg.toString() + ']');
    await sock.send('World');
    // Do some 'work'
  }
}

runServer();
hello_world_server 示例在 perlzmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/perl/perlzmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_server.md
    $example_dir/hello_world_server.md
#
#   Hello World server in Python
#   Binds REP socket to tcp://*:5555
#   Expects b"Hello" from client, replies with b"World"
#

import time
import zmq

context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5555")

while True:
    #  Wait for next request from client
    message = socket.recv()
    print(f"Received request: {message}")

    #  Do some 'work'
    time.sleep(1)

    #  Send reply back to client
    socket.send(b"World")
hello_world_server 示例在 rbzmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/ruby/rbzmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_server.md
    $example_dir/hello_world_server.md
#![crate_name = "helloworld_server"]

//! Hello World server in Rust
//! Binds REP socket to tcp://*:5555
//! Expects "Hello" from client, replies with "World"

use std::thread;
use std::time::Duration;

fn main() {
    let context = zmq::Context::new();
    let responder = context.socket(zmq::REP).unwrap();

    assert!(responder.bind("tcp://*:5555").is_ok());

    let mut msg = zmq::Message::new();
    loop {
        responder.recv(&mut msg, 0).unwrap();
        println!("Received {}", msg.as_str().unwrap());
        thread::sleep(Duration::from_millis(1000));
        responder.send("World", 0).unwrap();
    }
}

查看完整示例以了解更多详情。

const std = @import("std");
const zzmq = @import("zzmq");

pub fn main() !void {
    std.log.info("Starting the server...", .{});

    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer {
        if (gpa.deinit() == .leak)
            @panic("Memory leaked");
    }

    const allocator = gpa.allocator();

    var socket = try zzmq.ZSocket.init(allocator, zzmq.ZSocketType.Rep);
    defer socket.deinit();

    _ = try socket.bind("tcp://127.0.0.1:5555");

    while (true) {
        // Wait for next request from client
        {
            var frame = try socket.receive();
            defer frame.deinit();

            const data = try frame.data();

            std.log.info("Received: {s}", .{data});
        }

        // Do some 'work'
        std.time.sleep(std.time.ns_per_s);

        // Send reply back to client
        {
            var frame = try zzmq.ZFrame.init("World");
            defer frame.deinit();

            try socket.send(&frame, .{});
        }
    }
}

服务器创建一个响应类型的 socket(稍后您将阅读更多关于请求-回复模式的内容),将其绑定到端口 5555,然后等待消息。您还可以看到我们是零配置的,我们只是在发送字符串。

//  Hello World client
#include <zmq.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

int main (void)
{
    printf ("Connecting to hello world server…\n");
    void *context = zmq_ctx_new ();
    void *requester = zmq_socket (context, ZMQ_REQ);
    zmq_connect (requester, "tcp://localhost:5555");

    int request_nbr;
    for (request_nbr = 0; request_nbr != 10; request_nbr++) {
        char buffer [10];
        printf ("Sending Hello %d…\n", request_nbr);
        zmq_send (requester, "Hello", 5, 0);
        zmq_recv (requester, buffer, 10, 0);
        printf ("Received World %d\n", request_nbr);
    }
    zmq_close (requester);
    zmq_ctx_destroy (context);
    return 0;
}
//  Hello World client
#include <czmq.h>

int main (void)
{
    printf ("Connecting to hello world server…\n");
    zsock_t *requester = zsock_new (ZMQ_REQ);
    zsock_connect (requester, "tcp://localhost:5555");

    int request_nbr;
    for (request_nbr = 0; request_nbr != 10; request_nbr++) {
        printf ("Sending Hello %d…\n", request_nbr);
        zstr_send (requester, "Hello");
        char *str = zstr_recv (requester);
        printf ("Received World %d\n", request_nbr);
        zstr_free (&str);
    }
    zsock_destroy (&requester);
    return 0;
}
//  Hello World client
#include <zmqpp/zmqpp.hpp>
#include <string>
#include <iostream>

using namespace std;

int main(int argc, char *argv[]) {
  const string endpoint = "tcp://localhost:5555";

  // initialize the 0MQ context
  zmqpp::context context;

  // generate a push socket
  zmqpp::socket_type type = zmqpp::socket_type::req;
  zmqpp::socket socket (context, type);

  // open the connection
  cout << "Connecting to hello world server…" << endl;
  socket.connect(endpoint);
  int request_nbr;
  for (request_nbr = 0; request_nbr != 10; request_nbr++) {
    // send a message
    cout << "Sending Hello " << request_nbr <<"…" << endl;
    zmqpp::message message;
    // compose a message from a string and a number
    message << "Hello";
    socket.send(message);
    string buffer;
    socket.receive(buffer);
    
    cout << "Received World " << request_nbr << endl;
  }
}
#include <string>
#include <iostream>

#include <zmq.hpp>

int main()
{
    // initialize the zmq context with a single IO thread
    zmq::context_t context{1};

    // construct a REQ (request) socket and connect to interface
    zmq::socket_t socket{context, zmq::socket_type::req};
    socket.connect("tcp://localhost:5555");

    // set up some static data to send
    const std::string data{"Hello"};

    for (auto request_num = 0; request_num < 10; ++request_num) 
    {
        // send the request message
        std::cout << "Sending Hello " << request_num << "..." << std::endl;
        socket.send(zmq::buffer(data), zmq::send_flags::none);
        
        // wait for reply from server
        zmq::message_t reply{};
        socket.recv(reply, zmq::recv_flags::none);

        std::cout << "Received " << reply.to_string(); 
        std::cout << " (" << request_num << ")";
        std::cout << std::endl;
    }

    return 0;
}
hello_world_client 示例在 azmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/cpp/azmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_client.md
    $example_dir/hello_world_client.md
hello_world_client 示例在 czmqpp 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/cpp/czmqpp
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_client.md
    $example_dir/hello_world_client.md
hello_world_client 示例在 fbzmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/cpp/fbzmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_client.md
    $example_dir/hello_world_client.md
using System;
using NetMQ;
using NetMQ.Sockets;

static class Program
{
    public static void Main()
    {
        Console.WriteLine("Connecting to hello world server…");
        using(var requester = new RequestSocket())
        {
            requester.Connect("tcp://localhost:5555");

            int requestNumber;
            for (requestNumber = 0; requestNumber != 10; requestNumber++)
            {
                Console.WriteLine("Sending Hello {0}...", requestNumber);
                requester.SendFrame("Hello");
                string str = requester.ReceiveFrameString();
                Console.WriteLine("Received World {0}", requestNumber);
            }
        }
    }    
}
hello_world_client 示例在 clrzmq4 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/csharp/clrzmq4
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_client.md
    $example_dir/hello_world_client.md
hello_world_client 示例在 dartzmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/dart/dartzmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_client.md
    $example_dir/hello_world_client.md
-module(hello_world_client).
-export([main/0]).

main() ->
    application:start(chumak),
    {ok, Socket} = chumak:socket(req, "hello world client"),

    {ok, Pid} = chumak:connect(Socket, tcp, "localhost", 5555),

    send_messages(Socket, 10).

send_messages(Socket, 0) ->
    ok;

send_messages(Socket, N) ->
    io:format("Sending Hello ~p\n...", [N]),
    ok = chumak:send(Socket, <<"Hello">>),

    {ok, RecvMessage} = chumak:recv(Socket),
    io:format("Received: ~p\n", [RecvMessage]),

    send_messages(Socket, N-1).
hello_world_client 示例在 ezmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/erlang/ezmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_client.md
    $example_dir/hello_world_client.md
hello_world_client 示例在 erlang-czmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/erlang/erlang-czmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_client.md
    $example_dir/hello_world_client.md
hello_world_client 示例在 FsNetMQ 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/fsharp/fsnetmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_client.md
    $example_dir/hello_world_client.md
hello_world_client 示例在 fszmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/fsharp/fszmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_client.md
    $example_dir/hello_world_client.md
package main

import (
        "fmt"

        zmq "github.com/pebbe/zmq4"
)

func main() {
        zctx, _ := zmq.NewContext()

        // Socket to talk to server
        fmt.Printf("Connecting to the server...\n")
        s, _ := zctx.NewSocket(zmq.REQ)
        s.Connect("tcp://localhost:5555")

        // Do 10 requests, waiting each time for a response
        for i := 0; i < 10; i++ {
                fmt.Printf("Sending request %d...\n", i)
                s.Send("Hello", 0)

                msg, _ := s.Recv(0)
                fmt.Printf("Received reply %d [ %s ]\n", i, msg)
        }
}
package main

import (
	"log"

	"github.com/zeromq/goczmq"
)

func main() {
	// Create a dealer socket and connect it to the router.
	dealer, err := goczmq.NewDealer("tcp://127.0.0.1:5555")
	if err != nil {
		log.Fatal(err)
	}
	defer dealer.Destroy()

	log.Println("dealer created and connected")

	// Do 10 requests, waiting each time for a response
	for i := 0; i < 10; i++ {
		// Send a 'Hello' message from the dealer to the router.
		// Here we send it as a frame ([]byte), with a FlagNone
		// flag to indicate there are no more frames following.
		err = dealer.SendFrame([]byte("Hello"), goczmq.FlagNone)
		if err != nil {
			log.Fatal(err)
		}

		log.Println("dealer sent 'Hello'")

		// Receive the reply.
		reply, err := dealer.RecvMessage()
		if err != nil {
			log.Fatal(err)
		}

		log.Printf("dealer received '%s'", string(reply[0]))
	}
}
hello_world_client 示例在 zeromq4-haskell 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/haskell/zeromq4-haskell
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_client.md
    $example_dir/hello_world_client.md
//  Hello World client in Java
//  Connects REQ socket to tcp://localhost:5555
//  Sends "Hello" to server, expects "World" back

import org.zeromq.SocketType;
import org.zeromq.ZMQ;
import org.zeromq.ZContext;

public class hwclient
{
    public static void main(String[] args)
    {
        try (ZContext context = new ZContext()) {
            System.out.println("Connecting to hello world server");

      		//  Socket to talk to server
            ZMQ.Socket socket = context.createSocket(SocketType.REQ);
            socket.connect("tcp://localhost:5555");

            for (int requestNbr = 0; requestNbr != 10; requestNbr++) {
                String request = "Hello";
                System.out.println("Sending Hello " + requestNbr);
                socket.send(request.getBytes(ZMQ.CHARSET), 0);

                byte[] reply = socket.recv(0);
                System.out.println(
                    "Received " + new String(reply, ZMQ.CHARSET) + " " +
                    requestNbr
                );
            }
        }
    }
}
hello_world_client 示例在 JZMQ 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/java/jzmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_client.md
    $example_dir/hello_world_client.md
hello_world_client 示例在 jczmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/java/jczmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_client.md
    $example_dir/hello_world_client.md
//  Hello World client
const zmq = require('zeromq');

async function runClient() {
  console.log('Connecting to hello world server…');

  //  Socket to talk to server
  const sock = new zmq.Request();
  sock.connect('tcp://localhost:5555');

  for (let i = 0; i < 10; i++) {
    console.log('Sending Hello ', i);
    await sock.send('Hello');
    const [result] = await sock.receive();
    console.log('Received ', result.toString(), i);
  }
}

runClient();
hello_world_client 示例在 perlzmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/perl/perlzmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_client.md
    $example_dir/hello_world_client.md
#
#   Hello World client in Python
#   Connects REQ socket to tcp://localhost:5555
#   Sends "Hello" to server, expects "World" back
#

import zmq

context = zmq.Context()

#  Socket to talk to server
print("Connecting to hello world server…")
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5555")

#  Do 10 requests, waiting each time for a response
for request in range(10):
    print(f"Sending request {request} …")
    socket.send(b"Hello")

    #  Get the reply.
    message = socket.recv()
    print(f"Received reply {request} [ {message} ]")
hello_world_client 示例在 rbzmq 中缺失。您想贡献它吗?然后按照以下步骤操作

    git clone https://github.com/zeromq/zeromq.org
    example_dir=content/docs/examples/ruby/rbzmq
    cd zeromq.org && mkdir -p $example_dir
    [ -s $example_dir/index.md ] || cat >$example_dir/index.md <<'EOF'
---
headless: true
---
EOF
    cp archetypes/examples/hello_world_client.md
    $example_dir/hello_world_client.md
#![crate_name = "helloworld_client"]

//! Hello World client

fn main() {
    println!("Connecting to hello world server...\n");

    let context = zmq::Context::new();
    let requester = context.socket(zmq::REQ).unwrap();

    assert!(requester.connect("tcp://localhost:5555").is_ok());

    let mut msg = zmq::Message::new();

    for request_nbr in 0..10 {
        println!("Sending Hello {}...", request_nbr);
        requester.send("Hello", 0).unwrap();

        requester.recv(&mut msg, 0).unwrap();
        println!("Received World {}: {}", msg.as_str().unwrap(), request_nbr);
    }
}

查看完整示例以了解更多详情。

const std = @import("std");
const zzmq = @import("zzmq");

pub fn main() !void {
    std.log.info("Connecting to the server...", .{});

    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer {
        if (gpa.deinit() == .leak)
            @panic("Memory leaked");
    }

    const allocator = gpa.allocator();

    var socket = try zzmq.ZSocket.init(allocator, zzmq.ZSocketType.Req);
    defer socket.deinit();

    try socket.connect("tcp://127.0.0.1:5555");

    // Do 10 requests, waiting each time for a response
    for (0..9) |i| {
        // Send the request
        {
            std.log.info("Sending request {}...", .{i});

            var frame = try zzmq.ZFrame.init("Hello");
            defer frame.deinit();

            try socket.send(&frame, .{});
        }

        // Receive the reply
        {
            var frame = try socket.receive();
            defer frame.deinit();

            const data = try frame.data();

            std.log.info("Received reply {} [ {s} ]", .{ i, data });
        }
    }
}

客户端创建一个请求类型的 socket,连接并开始发送消息。

sendreceive 方法都是阻塞的(默认情况下)。对于接收来说很简单:如果没有消息,方法将阻塞。对于发送来说更复杂,取决于 socket 类型。对于请求 socket,如果达到高水位线或没有对等端连接,方法将阻塞。