pp2@nereida:~/src/perl/Event/server$ cat -n server.pl 1 #!/usr/bin/perl -w 2 use strict; 3 use Event qw(loop unloop); 4 use IO::Socket; 5 6 my $channels; 7 8 # make socket 9 my $socket = IO::Socket::INET->new(Listen => 5, LocalPort => 8080, Reuse => 1); 10 die "[Fatal] Cannot build initial socket.\n" unless $socket; 11 12 # install an initial watcher 13 Event->io( 14 fd => $socket, 15 cb => sub { 16 my $channel=++$channels; 17 18 my $client = $socket->accept; 19 20 warn "[Error] Cannot connect to new client.\n" and return unless $client; 21 $client->autoflush; 22 23 Event->io( 24 fd => $client, 25 cb => sub { 26 warn "[Server] Talking on channel $channel.\n"; 27 28 my $handle = $_[0]->w->fd; 29 my $line=<$handle>; 30 31 $handle->print("[Channel $channel] $line"); 32 warn "Received from $channel: $line"; 33 34 if ($line=~/^quit\r?$/i) { 35 $_[0]->w->cancel; 36 warn "[Server] Closed channel $channel.\n"; 37 } 38 }, 39 ); 40 41 $client->print("Welcome, this is channel $channel.\n"); 42 43 warn "[Server] Opened new channel $channel.\n"; 44 }, 45 ); 46 47 print "Server process: $$\n"; 48 loop;
Servidor |
pp2@nereida:~/src/perl/Event/server$ server.pl Server process: 8461 [Server] Opened new channel 1. [Server] Talking on channel 1. Received from 1: Hola, aqui un cliente [Server] Opened new channel 2. [Server] Talking on channel 2. Received from 2: Soy el cliente lento [Server] Talking on channel 2. Received from 2: quit [Server] Closed channel 2. [Server] Talking on channel 1. Received from 1: quit [Server] Closed channel 1. Terminado (killed) |
Primer Cliente |
pp2@nereida:/tmp/Continuity-0.991/eg$ telnet localhost 8080 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Welcome, this is channel 1. Hola, aqui un cliente [Channel 1] Hola, aqui un cliente quit [Channel 1] quit Connection closed by foreign host. pp2@nereida:/tmp/Continuity-0.991/eg$ kill -9 8461 pp2@nereida:/tmp/Continuity-0.991/eg$ |
Segundo Cliente |
pp2@nereida:/tmp$ telnet localhost 8080 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Welcome, this is channel 2. Soy el cliente lento [Channel 2] Soy el cliente lento quit [Channel 2] quit Connection closed by foreign host. pp2@nereida:/tmp$ |
Para saber mas sobre sockets y el módulo IO::Socket véase la sección 13.5.