在java中使用zmq

首先需要安装zmq以及java zmq的api。mac下安装的过程非常简单,

brew install zeromq

brew install pkg-config

brew install Libtool

  git clone https://github.com/zeromq/jzmq.git

./autogen.sh

./configure

make

make install

安装成功后,得到/usr/local/share/java/zmq.jar

我使用的ide是idea,在项目中添加: vm添加: -Djava.library.path=/usr/local/lib

ok,敲入官网的例子:

import org.zeromq.ZMQ;
import java.util.Date;

/**
 *
 * Created by darkbull on 14-4-21.
 */
public class Main {
    public static void main(String[] args)
            throws Exception {

        ZMQ.Context context = ZMQ.context(1);
        ZMQ.Socket socket = context.socket(ZMQ.REP);   
        socket.bind ("tcp://*:9005"); 

        while (true) {
            byte[] recv = socket.recv(0);
            String recvStr = new String(recv);
            System.out.println("recv:" + recvStr);
            String time = new Date().getTime() + "";

            byte[] reply = time.getBytes();
            socket.send(reply, 0);
        }
    }
}

用python验证下服务器是否可用

import zmq
import time

context = zmq.Context()
sock = context.socket(zmq.REQ)
sock.connect('tcp://127.0.0.1:9005')
while True:
    sock.send("Hello")
    print sock.recv()
    time.sleep(1)

 

ok, 简单吧。。。


标签: none


    Validate Code