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

I'm trying to write a simple DICT client, but I've been tripped up by my lack of sockets knowledge.

The problem is that when I'm reading the response from the server the client hangs when there's no more data rather than moving on like I want it to.

I'd like to issue a command, read the server response, and then issue another command. If I know how much data is being returned from the server for a specific command, I can call sysread the correct number of times and it works, but that just seems silly to call it twice sometimes, thrice another and once other times.

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use IO::Socket; my $socket = IO::Socket::INET->new( PeerAddr => 'all.dict.org', PeerPort => '2628', Proto => 'tcp', Timeout => 10, Resue => 1, MultiHomed => 1); die ("Could not create socket: $!\n") unless $socket; $socket->send("CLIENT dict4perl\n"); my $buf; while (sysread($socket, $buf, 1024)) { print $buf; } print "Done\n"; 1;

Replies are listed 'Best First'.
Re: IO::Socket hangs reading data from server
by Khen1950fx (Canon) on Sep 08, 2010 at 23:09 UTC
    Just add Blocking => 0.
    !/usr/bin/perl use strict; use warnings; use Data::Dumper; use IO::Socket; my $socket = IO::Socket::INET->new( PeerAddr => 'all.dict.org', PeerPort => '2628', Proto => 'tcp', Timeout => 1, ReuseAddr => 1, MultiHomed => 1, Blocking => 0); die ("Could not create socket: $!\n") unless $socket; $socket->send("CLIENT dict4perl\n"); my $buf; while (sysread($socket, $buf, 1024)) { print $buf; } print "Done\n"; 1;

      Thanks for information, with Blocking => 0 the application doesn't hang but it also doesn't seem to allow me to pull any of the response data from the server.

      Probably another problem, but I've also tried to pull the response data with:

      $socket->send("CLIENT dict4perl\n"); my $buf; while ($socket->recv($buf, 1024)) { print $buf . "\n"; }

      But no luck. I'm missing something here.

        Scratch that it works fine, there's something wiggie with my Mac shell and printing data with a shell script. It works in mod_perl where I want it to work.

        Thanks again for your help.

        This is without a doubt the most useful Web site on the Internet. It's one of the reasons I stick with Perl, other than that it's a kick ass language.