Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

reading lines from sockets with while

by Amoe (Friar)
on Feb 18, 2002 at 18:19 UTC ( #146193=perlquestion: print w/ replies, xml ) Need Help??
Amoe has asked for the wisdom of the Perl Monks concerning the following question:

I'm writing a module to interface with the MSN Instant Messenger servers and I've run into a little snag. I'm pretty new to socket programming, having only worked through the MP3 server exercise in the Tutorials section here before. Still, IO::Socket::INET looked like a good choice, providing an interface that looked like the file IO I was used to.

Little did I know what dastardly occurences could...occur. I wanted to read the messages the server was sending me, so I thought a good old my $message = <$server> would do the job, and it did. Until I realised that sometimes I might have to read more than one line. No big deal, I though - I'll just do a magic while loop, and that'll automatically stop when the server's stopped sending information. So here's a slice of code:

while (<$server>) { print "got $_"; chomp; # some more stuff... }

And what did I find? When the server sent me a line, crime of crimes, it recieved the first line, then BLOCKED. Recieving the first line was okay - there was only one line - but shouldn't that have been detected. Running over in the debugger, I could see that it did block at the while condition. Surely the while loop or some other sorcery should have seen that the server had nothing else to send and exited?

Super Search led me to How do I get started (reading data from a socket), but that used the same approach as I'm already using. The only way I can see to get around this at the moment is to hardcode a list of when the server will only send one line and when it could send any amount of stuff. This would feel so horrible, it makes me wince just to think about it. Please aid.

my one true love

Comment on reading lines from sockets with while
Select or Download Code
Re: reading lines from sockets with while
by dmmiller2k (Chaplain) on Feb 18, 2002 at 18:51 UTC

    If you want to avoid blocking on a read, try reading up on IO::Select. This module wraps around the select() socket API, basically letting you know when a handle may be read from (has data waiting to be read) or written to.

    See Using socket descriptor with IO::Select for a detailed explanation.


    If you GIVE a man a fish you feed him for a day
    TEACH him to fish and you feed him for a lifetime

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://146193]
Approved by root
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (9)
As of 2014-10-01 21:42 GMT
Find Nodes?
    Voting Booth?

    What is your favourite meta-syntactic variable name?

    Results (39 votes), past polls