Here's a complete example with Mojo::IOLoop and Mojo::IOLoop::Stream::Role::LineBuffer:
mojo_serv.pl:
#!/usr/bin/env perl
use warnings;
use strict;
use Mojo::Util qw/dumper/;
use Mojo::IOLoop;
use Mojo::IOLoop::Stream::Role::LineBuffer;
Mojo::IOLoop->server(
{ address => '127.0.0.1', port => 3000, reuse => 1 } => sub {
my ($loop, $stream) = @_;
my $peer = $stream->handle->peerhost.":".$stream->handle->peer
+port;
print "$peer: Connect\n";
$stream->timeout(30);
$stream = $stream->with_roles('+LineBuffer')->watch_lines;
$stream->on(read_line => sub {
my ($strm, $line, $sep) = @_;
print "$peer: Got line ".dumper($line);
});
$stream->on(timeout => sub { print "$peer: Timeout\n" });
$stream->on(close => sub { print "$peer: Closed\n" });
$stream->on(error => sub { warn "$peer: Error: $_[1]" });
$stream->write("Hello, client from $peer.\n");
});
print "Starting server...\n";
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
mojo_cli.pl:
#!/usr/bin/env perl
use warnings;
use strict;
use Mojo::Util qw/dumper/;
use Mojo::IOLoop;
use Mojo::IOLoop::Stream::Role::LineBuffer;
Mojo::IOLoop->client(
{ address => '127.0.0.1', port => 3000 } => sub {
my ($loop, $err, $stream) = @_;
if (defined $err) { warn "Error: $err"; return }
print "Connect\n";
$stream->timeout(10);
$stream = $stream->with_roles('+LineBuffer')->watch_lines;
$stream->on(read_line => sub {
my ($strm, $line, $sep) = @_;
print "Got line ".dumper($line);
});
$stream->on(timeout => sub { print "Timeout\n" });
$stream->on(close => sub { print "Closed\n" });
$stream->on(error => sub { warn "Error: $_[1]" });
$stream->write("Hello, server, I am a client.\n");
});
print "Starting client...\n";
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.