File: chat-server.pl

package info (click to toggle)
libio-async-perl 0.804-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,184 kB
  • sloc: perl: 13,884; makefile: 8
file content (71 lines) | stat: -rw-r--r-- 1,428 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/perl

use v5.14;
use warnings;

use IO::Async::Loop;
use IO::Async::Stream;

my $PORT = 12345;

my $loop = IO::Async::Loop->new;

my $listener = ChatListener->new;

$loop->add( $listener );

$listener->listen(
   service  => $PORT,
   socktype => 'stream',
)->on_done( sub {
   my ( $listener ) = @_;
   my $socket = $listener->read_handle;

   printf STDERR "Listening on %s:%d\n", $socket->sockhost, $socket->sockport;
})->get;

$loop->run;

package ChatListener;
use base qw( IO::Async::Listener );

my @clients;

sub on_stream
{
   my $self = shift;
   my ( $stream ) = @_;

   # $socket is just an IO::Socket reference
   my $socket = $stream->read_handle;
   my $peeraddr = $socket->peerhost . ":" . $socket->peerport;

   # Inform the others
   $_->write( "$peeraddr joins\n" ) for @clients;

   $stream->configure(
      on_read => sub {
         my ( $self, $buffref, $eof ) = @_;

         while( $$buffref =~ s/^(.*\n)// ) {
            # eat a line from the stream input

            # Reflect it to all but the stream who wrote it
            $_ == $self or $_->write( "$peeraddr: $1" ) for @clients;
         }

         return 0;
      },

      on_closed => sub {
         my ( $self ) = @_;
         @clients = grep { $_ != $self } @clients;

         # Inform the others
         $_->write( "$peeraddr leaves\n" ) for @clients;
      },
   );

   $loop->add( $stream );
   push @clients, $stream;
}