http://www.perlmonks.org?node_id=197484

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

which solution you suggest to me for writting a powerful socket server ?! Use traditional IO::Select or Thread in 5.8? Please tell me your reasons if you have suggesstion.
#!/usr/bin/perl -w #Traditional IO::Select Example use IO::Select; use IO::Socket; $Server = new IO::Socket::INET(Listen => 0, LocalPort => 4000, Reuse = +> 0) || die('Can not open port 4000'); $Select = new IO::Select( $Server ); while(@allSockets = $Select->can_read) { foreach $ClientSocket (@allSockets) { if($ClientSocket == $Server) { $newClient = $Server->accept; $Select->add($newClient); } else { .... } }
#!/usr/bin/perl -w #New stable Thread module in 5.8 use IO::Socket; use Thread; $Server = new IO::Socket::INET(Listen => 0, LocalPort => 4000, Reuse = +> 0) || die('Can not open port 4000'); while(1) { $newClientSocket=$Server->accept; new Thread \&handleRequest,$newClientSocket; } sub handleRequest() { $clientSocket=shift; ... }

Replies are listed 'Best First'.
Re: Thread or Select for sockets?!
by strat (Canon) on Sep 13, 2002 at 10:15 UTC
Re: Thread or Select for sockets?!
by ozone (Friar) on Sep 13, 2002 at 10:01 UTC
    Well, if it was me starting from scratch, I'd probably have a go at using POE, which implements user-space threads and can handle most of the typical networking problems. What you're probably looking for can be found in the Components section.

    Good luck :-)

Re: Thread or Select for sockets?!
by Preceptor (Deacon) on Sep 13, 2002 at 10:20 UTC
    Well, not to blow my own trumpet _too_ much, have a look at this. It's a mud client (read almost telnet but not quite) using IO::Select. IMHO this is the more elegant way than threading or forking, since you neatly sidestep the delightful things known as 'concurrent issues'. Threading requires a certain amount more thought, especially when you do anything to modify a 'global' value. (Some models, threading is good, like for example, I'm currently hacking together an FTP download manager for which it'd suit well. Others, it's just overkill, and potentially dangerous.)
    Update: Be aware that some network calls, such as 'gethostbyaddr()' at the OS level are NOT thread safe. I don't know how perl deals with this, but it's one to watch for.
    --
    It's not pessimism if there is a worse option, it's not paranoia when they are and it's not cynicism when you're right.