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

Hi All,

I'm a relative newbie, but looking several samples I have a basic setup which is working, but now I'd like for the server to send a return code (ok/fail) to the client. However I can't get it working, the client get's stuck in the recv.

I believe I don't need forking, my use case is synchronous, I just want to send commands to a test machine and get a response, then send more commands, etc... (part of some testing automation framework)

I have the following code:

################## SERVER
$OUTPUT_AUTOFLUSH=1; my $socket = new IO::Socket::INET (LocalHost => '0.0.0.0', LocalPort => $port, Proto => 'tcp', Listen => 1, Reuse => 1); die "Cannot create socket $!\n" unless $socket; # waiting for a new client connection $client_socket = $socket->accept(); $stop_server = 0; while(!$stop_server) { $client_data = ""; $client_socket->recv($client_data, 1024); # dispatch command my $ret = DispatchCommand($client_data); # reply to client ### ADD REPLY $client_socket->send($ret); ### ADD REPLY } $client_socket->close();
################## CLIENT
$OUTPUT_AUTOFLUSH=1; my $socket = new IO::Socket::INET (PeerHost => 'my.domain.net', PeerPort => '8888', Proto => 'tcp', Reuse => 1); die "cannot connect to the server $!\n" unless $socket; while (1) { print "Command??? "; chomp ($cmd = <>); # data to send to a server $socket->send($cmd); # wait for server acknowledgement ### GET REPLY $socket->recv($ack, 1024); ### GET REPLY print "response from server was $ack\n"; ### GET REPLY } $socket->close();

Without the ADD REPLY / GET REPLY, it works in the sense I can send my commands, but how do I get back to the client to tell it the return code?

Also, is there an easy way to get client's recv timeout after some set seconds? I've seen suggested I should use select, how would I use it this example?

Many thanks in advance.

Replies are listed 'Best First'.
Re: Interactive simple client server
by kcott (Archbishop) on Jul 05, 2013 at 10:53 UTC

      Thanks, I went through a lot of it, but couldn't find any reason why the above didn't work.

      Anyway, after spending few hours with this not going anywhere, I decided to create an account and post the question, and just typical, soon after I found the solution:

      <$socket> only returns after a complete line is received, which is to say when newline is received. sysread will return as soon as data is available

      so I've just tried that if I add newline (0x0A) to the reply or even better, use sysread instead, everything is fine (d'huh!)

      I'll see about the timeout next :-)