antichef has asked for the wisdom of the Perl Monks concerning the following question:
One-way communication (server to browser) is fine, but two ways would be nice, I guess. Not worried about two-way right now, since I can easily use HTTP(s) for browser-to-server.
I would like to use Mojolicious:: Lite (or something I can easily run in hypnotoad, and which allows for in-script hypnotoad configuration).
I found examples that look like they should work, but for me they don't - once the code hits the IO loop (whether the Mojo one or AnyEvent) to receive subscribed messages, I get either an 'operation on closed socket' if I'm using ZMQ::FFI, or a more cryptic error (something like Assertion failed: pfd.revents & POLLIN) if I use the ZMQ library like in the examples.
I decided to take a break and write the code in a plain perl script with Net::WebSocket::Server and AnyEvent, and found that it works fine when run from the command line:
which makes me think I should easily be able to make it work in Mojolicious::Lite, but for the life of me I can't seem to do it. It might be that in the code above, I'm able to put a subroutine in the on 'ready' state, but I can't figure out how to do that in the Mojolicious::Lite world.use strict; use IO::Socket::SSL; use ZMQ::FFI; use ZMQ::FFI::Constants qw (ZMQ_SUB); use AnyEvent; use EV; my $wsport = '3000'; my $zmqhost = 'tcp://localhost:5555'; my $subject = 'event'; Net::WebSocket::Server->new( listen => $wsport; on_connect => sub { my ($serv, $conn) = @_; $conn->on( ready => sub { my $context = ZMQ::FFI->new(); my $subsocket = $context->socket(ZMQ_SUB); $subsocket->connect($zmqhost); $subsocket->subscribe($subject); my $fd = $subsocket->get_fd(); my $w = AE::io $fd, 0, sub { while ($subsocket->has_pollin) { $conn->send_utf8($subsocket->recv()); } }; EV::run(); }, ); }, )->start;
(I would just use that code above, but it's single-user and not at all fault tolerant, and I'd rather not write a bunch of code to solve those issues if I don't have to)
Anyone with a suggestion on how to get this working in Mojolicious / hypnotoad, or perhaps another approach?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Mojolicious websocket question
by Corion (Patriarch) on Aug 26, 2017 at 07:14 UTC | |
|
Re: Mojolicious websocket question
by antichef (Acolyte) on Aug 26, 2017 at 17:14 UTC | |
|
Re: Mojolicious websocket question
by Anonymous Monk on Aug 26, 2017 at 03:20 UTC |