作者:gfree.wind@gmail.com博客:blog.focus-linux.net linuxfocus.blog.chinaunix.net
前段时间和crazyhadoop聊天中,他推荐了zeromq这个开源库。所以今天开始学习一下。看了一下zeromq的在线文档,感觉确实不错,准备学习一下。
我的目的是阅读zeromq的源代码,那么首先要学会去用zeromq,所以刚开始是zeromq的应用学习,然后再开始阅读其源代码。另外,为了重新拾起以前的C++,所以在学习zeromq的过程中,主要使用C++。
今天先来编译一下其示例程序吧。
首先要先安装zeromq,使用默认的选项./configure, make, make install。
然后是zeromq的server的示例代码
- #include <zmq.hpp>
-
#include <string>
-
#include <iostream>
-
#include <unistd.h>
-
-
int main () {
-
// Prepare our context and socket
-
zmq::context_t context (1);
-
zmq::socket_t socket (context, ZMQ_REP);
-
socket.bind ("tcp://*:5555");
-
-
while (true) {
-
zmq::message_t request;
-
-
// Wait for next request from client
-
socket.recv (&request);
-
std::cout << "Received Hello" << std::endl;
-
-
// Do some 'work'
-
sleep (1);
-
-
// Send reply back to client
-
zmq::message_t reply (5);
-
memcpy ((void *) reply.data (), "World", 5);
-
socket.send (reply);
-
}
-
return 0;
-
}
编译:
- g++ -g -Wall -fPIC -I../../include -I../../utils -shared -c server.cpp -o server.o
-
cc -L../../lib -g -lstdc++ -lzmq -o server server.o
在编译的时候,如果找不到zmq库,别忘了把安装路径加入到/etc/ld.so.conf中,并执行ldconfig。
下面是client的示例程序
- //
-
// Hello World client
-
// Connects REQ socket to tcp://localhost:5555
-
// Sends "Hello" to server, expects "World" back
-
//
-
#include <zmq.h>
-
#include <string.h>
-
#include <stdio.h>
-
#include <unistd.h>
-
-
int main (void)
-
{
-
void *context = zmq_init (1);
-
-
// Socket to talk to server
-
printf ("Connecting to hello world server…\n");
-
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++) {
-
zmq_msg_t request;
-
zmq_msg_init_size (&request, 5);
-
memcpy (zmq_msg_data (&request), "Hello", 5);
-
printf ("Sending Hello %d…\n", request_nbr);
-
zmq_send (requester, &request, 0);
-
zmq_msg_close (&request);
-
-
zmq_msg_t reply;
-
zmq_msg_init (&reply);
-
zmq_recv (requester, &reply, 0);
-
printf ("Received World %d\n", request_nbr);
-
zmq_msg_close (&reply);
-
}
-
zmq_close (requester);
-
zmq_term (context);
-
return 0;
-
}
编译:
- g++ -g -Wall -fPIC -I../../include -I../../utils -shared -c client.cpp -o client.o
-
cc -L../../lib -g -lstdc++ -lzmq -o client client.o
下面运行一下:
- [xxx@xxx-vm-fc13 client]$ ./client
-
Connecting to hello world server…
-
Sending Hello 0…
-
Received World 0
-
Sending Hello 1…
-
Received World 1
-
Sending Hello 2…
-
Received World 2
-
Sending Hello 3…
-
Received World 3
-
Sending Hello 4…
-
Received World 4
-
Sending Hello 5…
-
^C
-
[xxx@xxx-vm-fc13 client]$
- [xxx@xxx-vm-fc13 server]$ ./server
-
Received Hello
-
Received Hello
-
Received Hello
-
Received Hello
-
Received Hello
-
Received Hello
-
^C
-
[xxx@xxx-vm-fc13 server]$
虽然使用的是示例程序,但是从代码上看,使用zeromq确实比直接使用socket要简单方便的多。更何况据说还高效。
今天只是简单的试用zeromq,以后就慢慢开始深入了。
参考:
阅读(34280) | 评论(3) | 转发(2) |