ZeroMQ通信:简单请求-应答模式

请求-应答模式

server

package com.dsf.adapter.ZZtest;

import org.zeromq.ZMQ;
import org.zeromq.ZMQ.Socket;
import org.zeromq.ZContext;

public class Server {
    public static void main(String[] args) {
        System.out.println("server begin");

        ZContext zContext = new ZContext(1);
        Socket socket = zContext.createSocket(ZMQ.REP);
        socket.bind("tcp://*:5555");

        while (!Thread.currentThread().isInterrupted()) {
            byte[] request = socket.recv();
            System.out.println("receive : " + new String(request));
            String response = "world";
            socket.send(response.getBytes());
        }
        socket.close();
    }
}

client

package com.dsf.adapter.ZZtest;

import org.zeromq.ZMQ;
import org.zeromq.ZMQ.Socket;
import org.zeromq.ZContext;
public class Client {
    public static void main(String[] args) {
        System.out.println("client begin");

        ZContext zContext = new ZContext(1);
        Socket socket = zContext.createSocket(ZMQ.REQ);
        socket.connect("tcp://*:5555");

        for (int i = 0; i < 10000; i++) {
            String request = "hello";
            socket.send(request.getBytes());
            byte[] response = socket.recv();
            System.out.println("receive : " + new String(response));
        }

    }
}

你可能感兴趣的:(ZeroMQ,Java)