Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: IO::Socket tutorial

by haukex (Archbishop)
on Feb 20, 2020 at 16:36 UTC ( [id://11113259]=note: print w/replies, xml ) Need Help??


in reply to IO::Socket tutorial

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;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11113259]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2024-04-19 23:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found