我对ZeroMQ指南中的helloworld服务器程序(hwserver.pl)进行了少许修改,以使用AnyEvent实现它。然而,在两次REQ / REP迭代之后,程序挂起了。有人能弄清楚为什么吗?
这是服务器:
#!/usr/bin/perl -w
use strict;
use warnings;
use 5.12.0;
use EV;
use AnyEvent;
use ZMQ::LibZMQ3;
use ZMQ::Constants qw/ ZMQ_REP ZMQ_FD /;
my $context = zmq_init();
my $responder = zmq_socket($context, ZMQ_REP);
my $fh = zmq_getsockopt( $responder, ZMQ_FD );
zmq_bind($responder, 'tcp://*:5555');
our $w; $w = AE::io $fh, 0, sub {
say "Receiving...";
zmq_recv($responder, my $buf, 1_000_000);
say "Received request: [$buf]";
sleep(1);
zmq_msg_send('World', $responder);
sleep(1);
};
EV::run;
这是客户:
#!/usr/bin/perl -w
use strict;
use warnings;
use 5.12.0;
use ZMQ::LibZMQ3;
use ZMQ::Constants qw(ZMQ_REQ);
my $context = zmq_init();
# Socket to talk to server
say 'Connecting to hello world server...';
my $requester = zmq_socket($context, ZMQ_REQ);
zmq_connect($requester, 'tcp://localhost:5555');
for my $request_nbr (0..9) {
say "Sending request $request_nbr...";
zmq_msg_send('Hello', $requester);
my $msg = zmq_msg_init();
say "Receiving...";
zmq_msg_recv($msg, $requester);
say "Received reply $request_nbr: [". zmq_msg_data($msg) ."]";
}
这是服务器的输出:
Receiving...
Received request: [Hello]
Receiving...
Received request: [Hello]
这是客户端的输出:
Connecting to hello world server...
Sending request 0...
Receiving...
Received reply 0: [World]
Sending request 1...
Receiving...
Received reply 1: [World]
Sending request 2...
Receiving...
怎么了?
最佳答案
您没有使用文档为服务器建议的while()语法是有原因的吗?
http://search.cpan.org/~dmaki/ZMQ-LibZMQ3-1.00_04/lib/ZMQ/LibZMQ3.pm
从zeromq2-2.1.0开始,您可以使用getsockopt检索基础
文件描述符,因此可以使用它来集成ZMQ::LibZMQ3和AnyEvent:
my $socket = zmq_socket( $ctxt, ZMQ_REP );
my $fh = zmq_getsockopt( $socket, ZMQ_FD );
my $w; $w = AE::io $fh, 0, sub {
while ( my $msg = zmq_recv( $socket, ZMQ_RCVMORE ) ) {
# do something with $msg;
}
undef $w;
};
此外,睡眠将被阻止。您应该真正注册一个与计时器事件相关联的回调,该回调将在发送响应的一秒钟后运行。
关于perl - 简单的ZeroMQ Perl(AnyEvent)HelloWorld程序在两次循环迭代后挂起,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18332718/