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

Hi, I have the following code - $socket new IO::Socket::INET ( PeerAddr => "localhost", PeerPort => 12323, Proto => 'tcp' )); print $socket "Hi!" print $socket "Aha, I see!" $socket->close(); The thing is, I'd like to listen to the replies I get when I send thes +e command, and perhaps I get reply... Anyway, how would I modify this code to print the replies I get. thank you!

Replies are listed 'Best First'.
Re: Recieving reply from a socket
by puudeli (Pilgrim) on Mar 19, 2009 at 13:46 UTC

    A simple server-client setup is what you are looking for then.

    For the server side you have to set up a listening socket, accept incoming connections and read from the connections. Then you need clients that connect to that server. Please see Internet TCP Clients and Servers for instructions.

    corrected typo's
    --
    seek $her, $from, $everywhere if exists $true{love};
Re: Recieving reply from a socket
by lostjimmy (Chaplain) on Mar 19, 2009 at 13:47 UTC

    First thing first, your code won't even compile in its present state. Also, always use strict and use warnings.

    Reworked and compiling code:

    use strict; use warnings; use IO::Socket::INET; my $socket = IO::Socket::INET->new(PeerAddr => "localhost", PeerPort => 12323, Proto => 'tcp'); print $socket "Hi!"; print $socket "Aha, I see!"; $socket->close();

    To read the replies, all you really need to do is read from the socket like any other file handle. You can use recv, or, more simply, my $response = <$socket>.

    And just because it is a common issue, you might want to take a look at Suffering From Buffering.

      My code is hanging on this line: my $response = <$socket>; How come? Thanks.
Re: Recieving reply from a socket
by locked_user sundialsvc4 (Abbot) on Mar 19, 2009 at 15:11 UTC

    Also... if you are “looking for a server,” first check to see if what you are looking for has not already been done by someone else. It probably has.

    It's a natural tendency for computer programmers, when first presented with a new (sic...) problem, to immediately start spinning algorithms in their heads. Instead, you need to consciously develop the instinct that says to you, look first.