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

Hi Monkees

I have a perl socket client, and a small problem. The socket server at the other end is not sending a newline, just a line of data terminated with '~'. At the moment my client just sits there (more accurately, it times out), since due to the lack of newline it never seems to read from the socket.

I assume there may be more questions, but here is the relevant bit of code - how should I resolve this problem?


$SIG{ALRM} = sub{die "timeout"}; eval{ alarm($timeout); $line_in = <$socket>; alarm(0); };

So... how do I read from $socket to $line_in when there is no newline?

Tom Melly, tom@tomandlu.co.uk

Replies are listed 'Best First'.
Re: Question from socket newbie
by blokhead (Monsignor) on Sep 26, 2003 at 16:13 UTC
    You can set $/
    $SIG{ALRM} = sub{die "timeout"}; eval{ alarm($timeout); local $/ = "~"; $line_in = <$socket>; alarm(0); };
    Now calling <$socket> will only read up to the first ~ character (or EOF).

    blokhead

      Bingo! Many, many thanks....
      Tom Melly, tom@tomandlu.co.uk
Re: Question from socket newbie
by hardburn (Abbot) on Sep 26, 2003 at 16:12 UTC

    A few thoughts come to mind:

    1. The server isn't flushing its buffer
    2. If the protocol specifies a new line, but the server doesn't send one, then the server is violating the protocol
    3. If the protocol doesn't specify a new line, then your program can't assume there will be one

    The first two are solved at the server end. For #1, set $| = 1; (assuming it's in Perl--other languages should have some method for flushing the buffer). For #2, you need to add a new line to the server's output.

    If #3 is the problem, you need to read the protocol docs more carefuly :)

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated

      I think it's #3 (and it's not a perl server) - no protocol has been supplied. We've established the problem, I'm just not sure how to resolve it (i.e. how do I get perl to read from a socket buffer when the content isn't newline terminated).

      Tom Melly, tom@tomandlu.co.uk
Re: Question from socket newbie ($/ | eof)
by tye (Sage) on Sep 26, 2003 at 17:42 UTC

    <$socket> will never return until it sees a newline (well $/, which defaults to "\n" on all platforms) or end-of-file. This is why you should avoid using <$socket>.

    There are several alternatives, most likely read or sysread would be a better choice.

                    - tye