gpt4 book ai didi

perl - 简单的 ZeroMQ Perl (AnyEvent) HelloWorld 程序在两次循环迭代后挂起

转载 作者:行者123 更新时间:2023-12-01 12:04:21 25 4
gpt4 key购买 nike

我稍微修改了 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

As of zeromq2-2.1.0, you can use getsockopt to retrieve the underlying file descriptor, so use that to integrate ZMQ::LibZMQ3 and 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;
};

另外, sleep 会阻塞。您真的应该注册一个与计时器事件相关联的回调,设置为在发送响应的一秒后运行。

关于perl - 简单的 ZeroMQ Perl (AnyEvent) HelloWorld 程序在两次循环迭代后挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18332718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com