In sockets I have written the client server program. First I tried to send the normal string among them it sends fine. After that I tried to send the hash and array values from client to server and server to client. When I print the values using Dumper, it gives me only the reference value. What should I do to get the actual values in client server?
Server Program:
use IO::Socket;
use strict;
use warnings;
my %hash = ( "name" => "pavunkumar " , "age" => 20 ) ;
my $new = \%hash ;
#Turn on System variable for Buffering output
$| = 1;
# Creating a a new socket
my $socket=
IO::Socket::INET->new(LocalPort=>5000,Proto=>'tcp',Localhost =>
'localhost','Listen' => 5 , 'Reuse' => 1 );
die "could not create $! \n" unless ( $socket );
print "\nUDPServer Waiting port 5000\n";
my $new_sock = $socket->accept();
my $host = $new_sock->peerhost();
while(<$new_sock>)
{
#my $line = <$new_sock>;
print Dumper "$host $_";
print $new_sock $new . "\n";
}
print "$host is closed \n" ;
Client Program
use IO::Socket;
use Data::Dumper ;
use warnings ;
use strict ;
my %hash = ( "file" =>"log.txt" , size => "1000kb") ;
my $ref = \%hash ;
# This client for connecting the specified below address and port
# INET function will create the socket file and establish the connection with
# server
my $port = shift || 5000 ;
my $host = shift || 'localhost';
my $recv_data ;
my $send_data;
my $socket = new IO::Socket::INET (
PeerAddr => $host ,
PeerPort => $port ,
Proto => 'tcp', )
or die "Couldn't connect to Server\n";
while (1)
{
my $line = <stdin> ;
print $socket $ref."\n";
if ( $line = <$socket> )
{
print Dumper $line ;
}
else
{
print "Server is closed \n";
last ;
}
}
I have given my sample program about what I am doing. Can any one tell me what I am doing wrong in this code? And what I need to do for accessing the hash values?
When you say
, you're in part instructing Perl to turn
$ref
into a string (since only strings can beprint
ed). It turns out that references don't turn into very useful strings by default.You need to turn
$ref
into a string that you can send across the wire and then decode on the other side to get the data back out. This process is referred to as "serialization".Data::Dumper
's output is actually a valid serialization of its arguments, but the basic serialization module in Perl isStorable
.Procedurally, you can say[1]
on one side and
on the other.
There's also an OO interface; read the
Storable
documentation for more information.[1]: Notice the yaddayaddas. This is incomplete code that merely illustrates the key differences from your code.
Problem is you are sending references to the data, not the data itself. You need to serialize the data somehow. JSON is a very easy way to do that. There is also YAML.