ashok13123 has asked for the wisdom of the Perl Monks concerning the following question:

CLIENT.pl #!/usr/bin/perl use strict; use IO::Socket; $file="file1.txt" #This is the file to be opened in server side my $sock = new IO::Socket::INET( PeerAddr => '192.168.100.30', PeerPort => 7880, Proto => 'tcp', ); print $sock "$file"; open(FILE,">file.txt"); binmode(FILE); while(<$sock>) { print FILE $_; print FILE <$sock>; } close(FILE);
Server Side
#!/usr/bin/perl use strict; use IO::Socket; my $file1; my $sock = new IO::Socket::INET( LocalAddr => '192.168.100.30', LocalPort => 6224, Listen => 10, Proto => 'tcp', Reuse => 1, ); while(my $conn = $sock->accept()) { $file1=$_;#This should collect the filename send by client right? open(FILE,"$file1"); binmode(FILE); my @file = <FILE>; close(FILE); foreach my $x (@file) { print $conn $x; } }
My intention is to send a file name to a remote server from client and the server should open the file and send the contents to client.The client should write it tio a local file My problem is that the server is not receiving the filename send by client.How can i receive the file name and send the contents???

Replies are listed 'Best First'.
Re: FIle transfer using sockets
by ikegami (Patriarch) on May 09, 2009 at 06:34 UTC

    $file1=$_;#This should collect the filename send by client right?

    No. Nothing is being assigned anything to $_. You'll need to read it from $conn. You'll also have to provide a mechanism to indicate when the end of the file name is reached. Without that, you won't know when to stop reading.

    Why are you reinventing HTTP?

Re: FIle transfer using sockets
by zwon (Abbot) on May 09, 2009 at 09:53 UTC

    First of all PeerPort on client side doesn't match LocalPort on server side, so client can't connect to server.

    In order to read file name you should use $file1=<$conn>.

    You're reading the whole file into memory before send it to client. That's not a good idea. You'd better use the loop like this:

    while (sysread FILE, my $buffer, 4096) { $conn->send($buffer); }
    This would help if you plan to send file which doesn't fit into memory.

      In order to read file name you should use $file1=<$conn>.

      Only if
      print $sock "$file";
      is changed to
      print $sock "$file\n";

        You're right. I suggest something like this for client side:

        print $sock "$file\0";
        and something like this for server:
        { local $/ = "\0"; $file1 = <$conn>; chomp $file1; }

        "\n" isn't portable. And at least on *nix file name may contain "\n"