Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 82 lines (65 sloc) 1.615 kb
de14455 Rocco Caputo Add the beginnings of a socket listener, a stream reader/writer, and an ...
authored
1 # A TCP echo server.
2
3 use lib qw(./lib ../lib);
4
5 {
6 package TcpEchoSession;
7 use Moose;
8 extends 'Reflex::Stream';
9
10 sub on_my_stream {
11 my ($self, $args) = @_;
12 $self->put($args->{data});
13 }
14
15 sub on_my_fail {
16 my ($self, $args) = @_;
17 warn "$args->{errfun} error $args->{errnum}: $args->{errstr}\n";
18 $self->emit( event => "shutdown", args => {} );
19 }
20
21 sub on_my_close {
22 my ($self, $args) = @_;
23 $self->emit( event => "shutdown", args => {} );
24 }
25 }
26
27 {
28 package TcpEchoServer;
29
30 use Moose;
31 extends 'Reflex::Listener';
32 use Reflex::Callbacks qw(cb_method);
33
34 has clients => (
35 is => 'rw',
36 isa => 'HashRef[Reflex::Stream]',
37 default => sub { {} },
38 );
39
40 sub on_my_accepted {
41 my ($self, $args) = @_;
42
43 # TODO - We're developing a pattern here:
44 # 1. Create a managed object,
45 # 2. The new managed object will contain a weak manager reference.
46 # 3. The manager enters the object into a hash, keyed on object.
47 # 4. Later, the object will tell the manager when it shuts down.
48
49 my $client = TcpEchoSession->new(
50 handle => $args->{socket},
51 rd => 1,
52 );
53
54 $self->observe(
55 $client,
56 shutdown => cb_method($self, "on_client_shutdown")
57 );
58
59 $self->clients()->{$client} = $client;
60 }
61
62 sub on_my_fail {
63 my ($self, $args) = @_;
64 warn "$args->{errfun} error $args->{errnum}: $args->{errstr}\n";
65 }
66
67 sub on_client_shutdown {
68 my ($self, $args) = @_;
69 delete $self->clients()->{$args->{_sender}};
70 }
71 }
72
73 TcpEchoServer->new(
74 handle => IO::Socket::INET->new(
75 LocalAddr => '127.0.0.1',
76 LocalPort => 12345,
77 Listen => 5,
78 Reuse => 1,
79 ),
80 rd => 1,
81 )->run_all();
Something went wrong with that request. Please try again.