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

Dear monks,

I've written a tcp server based on the examples in Perl Cookbook and using IO::Socket::INET. It blocks on accept() and then forks to handle each new connection as they come in.

while (($connection) = $server->accept()) { # do fork stuff
All that works fine. Connection are made and the server can receive and send data.
while(<$connection>) { # waits for data # handle the incoming message
The problem is - each child process blocks while listening for data from the client.

i.e. the server cannot initiate sending data to the client until after it receives something.

This is a real problem as my clients are only sending data sporadically.

Can the "listen" for each connection behave in a non-blocking fashion?

Basically, I'd like to test if there's a message and if so, process it. If not, however, I'd like to have the option to 'do other stuff' like sending messages back to the client if necessary. Oh, and sleep for a bit.

Replies are listed 'Best First'.
Re: non-blocking listen on a tcp server
by almut (Canon) on Jun 09, 2010 at 18:14 UTC
        Thanks alot folks. You're giving me good ideas.

        ikegami, I like the Coro option - the code is neat. I'm still trying to get my head around it though.

        The example doesn't appear to have the forking server but I need my server to handle multiple client connection simultaneously.

        Is that still an option when using Coro?
Re: non-blocking listen on a tcp server
by ikegami (Patriarch) on Jun 09, 2010 at 18:34 UTC
    There's also threads and Coro (cooperative multitasking)
Re: non-blocking listen on a tcp server
by zwon (Abbot) on Jun 09, 2010 at 18:22 UTC

    Perhaps you should spend some time learning POE or AnyEvent.

Re: non-blocking listen on a tcp server
by bingos (Vicar) on Jun 10, 2010 at 21:07 UTC