in reply to Re^2: Simple question regarding Bidirectional socket programming
in thread Simple question regarding Bidirectional socket programming

First, you should read from CLIENT, not from $client_addr:

while ( defined ($response = <CLIENT>) ){

Next, you have to flush (or autoflush) when you write something on either side. Otherwise, due to buffering, the messages will not be available on the other side right away, resulting in a deadlock, because both sides will wait for the other side to say something...  One way would be to use IO::Handle:

use IO::Handle; ... print CLIENT "Hello from the server \n\n "; CLIENT->flush(); ...

and similarly on the client side.

Also, as both client and server are in a readline while loop, you'll likely want to have some protocol that defines when to stop reading and terminate the connection.

Finally, when you read lines on the server side, you also have to print a line on the client side:

print SOCKET "Client says hellooooo toooo !!! \n"; # ^^ SOCKET->flush();

Otherwise, the server will hang in $response = <CLIENT>, waiting for the newline...

Replies are listed 'Best First'.
Re^4: Simple question regarding Bidirectional socket programming
by sajanagr (Acolyte) on Jun 15, 2010 at 10:27 UTC
    Hi almut, your solution worked just perfect for me, the code is working now after your changes.

    I added a condition for break in the while loop for the deadlock.

    There is another doubt, I read that $| variable of perl does flusing, so I had used that in the code above, but it didnt work somehow here and when i used IO::Socket and did CLIENT->flush(), it worked.

    I didn't understand this. Can you elaborate?

      Setting $| applies to the "selected" file handle, which by default is STDOUT. In theory, you could use select (the one argument variant) to have it apply to any other handle (see the example in the docs), but personally, I find the IO::Handle API less cumbersome to use.

      You can use
      use IO::Handle; ... CLIENT->autoflush(1); ... print CLIENT "Hello from the server \n\n"; ...
      instead of
      use IO::Handle; ... print CLIENT "Hello from the server \n\n"; CLIENT->flush(); ...

      The first is the same as calling $|=1; with the CLIENT handle selected.

        Thank you guys for putting some light on the topic. You helped me from banging my head on my desk all the day long. Thanks a ton