How is it work the event handlers!?

I just have started studying perl and I can not figure out what is the exact strategy used in the following script to handle events.

Precisely, what I do not understand is if the loop that is in charge to control the state of the socket, is managed at the system level (where the process will be locked inside the scheduler and so the following code must be read sequentially) or if this happens anywhere else, or maybe just in these "while loop" that apparently are based on the success of the setting of a variable.

Especially the "while" block at the server-side leaves me some concern.

Script to Create a Server

#!/usr/bin/perl -w
# Filename : server.pl

use strict;
use Socket;

# use port 7890 as default
my $port = shift || 7890;
my $proto = getprotobyname('tcp');
my $server = "localhost";  # Host IP running the server

# create a socket, make it reusable
socket(SOCKET, PF_INET, SOCK_STREAM, $proto)
   or die "Can't open socket $!\n";
setsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, 1)
   or die "Can't set socket option to SO_REUSEADDR $!\n";

# bind to a port, then listen
bind( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
   or die "Can't bind to port $port! \n";

listen(SOCKET, 5) or die "listen: $!";
print "SERVER started on port $port\n";

# accepting a connection
my $client_addr;
while ($client_addr = accept(NEW_SOCKET, SOCKET)) {
   # send them a message, close connection
   my $name = gethostbyaddr($client_addr, AF_INET );
   print NEW_SOCKET "Smile from the server";
   print "Connection recieved from $name\n";
   close NEW_SOCKET;
}
To run the server in background mode issue the following command on Unix prompt 

$perl sever.pl&
Script to Create a Client

#!/usr/bin/perl -w
# Filename : client.pl

use strict;
use Socket;

# initialize host and port
my $host = shift || 'localhost';
my $port = shift || 7890;
my $server = "localhost";  # Host IP running the server

# create the socket, connect to the port
socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2])
   or die "Can't create a socket $!\n";
connect( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
   or die "Can't connect to port $port! \n";

my $line;
while ($line = <SOCKET>) {
        print "$line\n";
}
close SOCKET or die "close: $!";

Thanks for any answare!

accept() will block at the kernel level, yes. It will be forced to wait until the client connects.

It's not based on the success of setting a variable. It does the same thing as while(accept(...)) without the assignment -- but the program needs the value accept is returning, so it's saved for later.

Thanks very clear!

1 Like