#!/usr/bin/perl -w
#
#https://www.tutorialspoint.com/perl/perl_socket_programming.htm
#https://perldoc.perl.org/5.8.8/perlfaq5.pdf
#http://perldoc.perl.org/perlipc.html#Sockets%3a-Client%2fServer-Communication
#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
my $server = "192.168.1.64";  # 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, 0) or die "listen: $!";
print "SERVER started on port $port\n";

# accepting a connection
my $client_addr="";
my $name ="";
#
# Block in accept, but other connections are not rejected.
#
#

while ($client_addr = accept(NEW_SOCKET, SOCKET)) {
   # send them a message, close connection
   $name = gethostbyaddr( $client_addr, AF_INET );
   my( $port, $iaddr ) = sockaddr_in( $client_addr );

   #unpack address to string, print it and flush it.
   print "Connection recieved from " .  inet_ntoa($iaddr) . " : $port \n\r";
   print NEW_SOCKET "hello " . inet_ntoa($iaddr) .": $port \n\r";
   flush NEW_SOCKET ;

   my $count;
   my $line;

   # Nothing is sent  until the socket closed , or flush
   $count =0;	
   # the defined is important in getting the NEW_SOCKET as it detects the remote end closes NEW_SOCKET.

   # block awaiting input from Client
   while(  defined( $line = <NEW_SOCKET> ) ){
     print NEW_SOCKET "Smile from the server [ $count ] $line \n\r";
     print "$line \n\r";
     print "[ $count ] sending to socket\n\r";
     
     # the flush below is really important for the connection to flow. 
     flush NEW_SOCKET ;
     # sleep( 1 );

     print NEW_SOCKET "done some processing.\n\r";
     $count +=1;	
   }   
   close NEW_SOCKET;
}
#To run the server in background mode issue the following command on Unix prompt −

#$perl sever.pl&
