I wrote these as guidelines. Please do not feel intimidated, it's just that I want to provide as much feedback as I can. By all means, please ask more questions if you've got them. A few thoughts:
Always, always, always use strict.
Indentation is very important. Use the Preview button to insure that the code looks like you intend to. Your code probably contained tabs and spaces, that are expanded differently, so take the time to tidy up the code, as I also had to do :) It is also very nice if you line your braces, as I show in my code below.
I am unsure as to the purpose of the fork() call in your original post. If it was to handle the two directions of data flow, it was unnecesary. If you were trying to support multiple, concurrent clients, you were fork()ing the wrong code.
When using fork(), always think about what will happen to children after they die or exit. Perl's default behavior is to collect their exit status for you, but you might want to explicitly wait for them in order to provide some reporting, statistics, etc. You might want to take a look at this snippet by me for a better example of an invocation of fork(). Also note that you must make sure that the child effectively terminates after doing its work. Otherwise, it might jump to the start of the loop again.
The close $server in the children as well as the close $client in the server are good ways to save on file descriptors.
On the same vein, note that the return value of fork() is always defined. Errors are signalled by returning -1.
It is always a good idea to ->autoflush(1) when doing this kind of things. This insures that data is not buffered for long at the server side.
This is a version I adapted from your snippet and that incorporates what I say. It can read and write fine from as many clients as your machine supports.
#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket;
my $server = IO::Socket::INET->new
(
LocalPort => 1337,
Type => SOCK_STREAM,
Reuse => 1,
Listen => 5
) or die "could not open port\n";
warn "server ready waiting for connections..... \n";
my $client;
while ($client = $server->accept())
{
my $pid;
while (not defined ($pid = fork()))
{
sleep 5;
}
if ($pid)
{
close $client; # Only meaningful in the client
}
else
{
$client->autoflush(1); # Always a good idea
close $server;
&do_your_stuff();
}
}
sub do_your_stuff
{
warn "client connected to pid $$\n";
while(my $line = <$client>)
{
print "client> ", $line;
print $client "pid $$ > ", $line;
}
exit 0;
}
Update: Thanks (and ++) to chromatic for correcting my confusion with Perl's fork() and C's. Looks like this mistake is going to live with me for a lot of time...
Best regards
-lem, but some call me fokat