http://qs1969.pair.com?node_id=395564

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

Hello! Here is my perl script. I tried to communicate on the same port, but it wasn't worked. I can send message to a server, but I cannot get any response. The response is sent out from the server in the 30000 port - I tested the server with a C++ client and the same scenario worked fine.
#! /usr/bin/perl use IO::Socket::INET; my $sock = new IO::Socket::INET ( PeerAddr => '127.0.0.1', PeerPort => '30000', Proto => 'tcp', ); die "Could not create socket: $!\n" unless $sock; print $sock "Hello there!\n"; my $new_sock = $sock->accept(); while(defined(<$sockin>)) { print "Arrived?\n"; print $_; } print "Stopped! \n"; close($sock);
Maybe this line is wrong: my $new_sock = $sock->accept(); What other lib should I use? How could I fix it?

Br, HP

Edit by tye, remove PRE tag, preserve formatting

Replies are listed 'Best First'.
Re: Perl socket handling problem
by eyepopslikeamosquito (Archbishop) on Oct 01, 2004 at 07:54 UTC

    Are you writing a client or a server? BTW, the variable $sockin above is not initialised.

    Below is a simple client that connects to the echo server on port 7. Instead of using IO::Socket, you could write the client at a lower level using the socket/inet_aton/sockaddr_in/connect/close functions. See perldoc perlipc for more information. If you want to write a server instead, please let us know.

    use IO::Socket; my $sock = new IO::Socket::INET ( PeerAddr => '127.0.0.1', PeerPort => 7, # echo server Proto => 'tcp', Type => SOCK_STREAM ); die "Could not create socket: $!\n" unless $sock; print $sock "Hello there!\n"; my $answer = <$sock>; print "answer: $answer\n"; close($sock);
      Thank you for your solution!
Re: Perl socket handling problem
by bibo (Pilgrim) on Oct 01, 2004 at 12:46 UTC
    Another way to do it...

    Here's some client code for a slower responding socket server, or when all the data doesn't show up at once, due to other issues. It sends a chunk, and waits for a response, up to N loops. Small sleeps might be safer than just looping, but hey, everyone works differently. You also could add checks for some termination sequence, or checks for the chunk meeting a fixed size requirement.

    --bibo

    my $indata; my $remote = IO::Socket::INET->new( Proto => "tcp", PeerAddr =>'127.0.0.1' , PeerPort => $self->{'30000'}, ); if( defined($remote) ) { my $readsize; print $remote $bigdata; my $done = 0; my $zreads =0; while (! $done) { my $tempdata=""; $tempdata = <$remote>; $readsize = length $tempdata; $zreads++ if ($readsize == 0); $done = 1 if ($zreads > 30); $in_data = $in_data . $tempdata; $done = 1 if ($tempdata eq "\n"); } close $remote; }