Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

recv in socket programming

by madhu.hanigadde (Novice)
on Feb 12, 2009 at 10:20 UTC ( #743264=perlquestion: print w/replies, xml ) Need Help??
madhu.hanigadde has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, am trying to interacting with a server.I should get a response from the server when i will send a command. But there is a chance where i wont get response sometimes. In my code the recv function will get the response wen the server sends, but if there is no response then recv will hangout and will wait till the response come...i want it to wait for sometime and should comeout... Here is my code....
#!/usr/bin/perl use IO::Socket; $|=1; $socket = new IO::Socket::INET ( PeerAddr => '$IP', PeerPort => 3575, Proto => 'tcp', ) or die "Couldn't connect to Server\n"; while (1) { $send_data = "CHK $ARGV[0]"; print STDERR "\nSEND( TYPE q or Q to Quit):$send_data\n"; if ($send_data ne 'q' and $send_data ne 'Q') { $socket->send($send_data); sleep(1); $socket->recv($recv_data1,1024); sleep(1); $socket->recv($recv_data2,10240); print "RECIEVED: $recv_data2\n"; close $socket; last; } else { $socket->send($send_data); close $socket; last; } }

20090213 Janitored by Corion: Closed code tag, as per Writeup Formatting Tips

Replies are listed 'Best First'.
Re: recv in socket programming
by irah (Pilgrim) on Feb 12, 2009 at 12:39 UTC
    You can use Non-blocking I/O concept. Please use IO::Socket::Inet.
Re: recv in socket programming
by gone2015 (Deacon) on Feb 12, 2009 at 13:20 UTC

    If the far end simply stops responding, but leaves the connection open, then you are indeed in for a long wait.

    BTW send and recv are really packet level operations... and may not be what you really want with TCP. In particular, $socket->recv($recv_data2,10240); is unlikely to return anything like 10K of data.

    So you need to implement a time-out. You can use an ALRM signal to do this -- but it's a bit messy and won't work on all systems (notably not on Windows -- go figure). So I'd use IO::Select, as in the example below.

Re: recv in socket programming
by weismat (Friar) on Feb 12, 2009 at 12:33 UTC
    You may use IO::Select before the recv to determine if yoy can read from the socket.
    Example:
    my $select=new IO::Select(); $select->add($socket); if ($select->can_read($timeout)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://743264]
Approved by marto
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2016-12-04 23:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (70 votes). Check out past polls.