#!/usr/bin/perl -w
#
#https://www.tutorialspoint.com/perl/perl_socket_programming.htm
#https://perldoc.perl.org/5.8.8/perlfaq5.pdf
#Script to Create a Server
#!/usr/bin/perl -w
# Filename : server.pl
#
#
#$perl sever.pl&
#

use strict;
use Socket;
use IO::Handle;


# 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 );
   my $count;
   my $line;

   # Nothing is sent  until the socket close close, or flush
   for ( $count=0; $count < 40 ; $count = $count + 1 ){
     print NEW_SOCKET "Smile from the server [ $count ] \n";
     print "[ $count ] sending to socket\n";
     #sleep( 1 );
     # the flush below is really important for the connection to flow. 
     flush NEW_SOCKET ;

     print NEW_SOCKET "done some processing.\n";
     sleep( 1 );

     # look for input
     if ( $line = <NEW_SOCKET> ){
       print "$line\n";	
     };  

   }
   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&
