The problem with your server code is that, once it gets into that while loop, there is another inner while loop to communicate with the first client (Your code looks like it is reading from STDIN, but I think it is a simple typo on your side, as it makes less sense, so i take it as reading from client socket). It simply stuck there as long as the first client is connected. Once the first client is disconnected, the server starts to get empty strings (or undef, platform dependent), and quit the inner while loop. Only then, your execution path goes back to that accept statement.
One way is to make your server multi-threaded. One thread keeps accept connections, when the other one reads from clients by using select to determine readable ones.
Another choice is to spawn thread for each connection.
Third solution. Actually it is even okay to not use multi-thread or fork, simply make sure your server will accept new connections once a while, instead of stuck with one client.
Do a super search with my name as author, and search for key words: Socket and threads. You can find quite a few code samples for different purposes. They are helpful.
Here is a sample to spawn a new thread for each connection:
server: use strict; use IO::Socket; use threads; $|++; my $server = IO::Socket::INET->new(LocalPort => '5123',Reuse => 1,List +en => 5) or die "Could not create server: $!\n"; while (my $client = $server->accept()) { threads->create(\&talk_with_one_client, $client)->detach(); } sub talk_with_one_client { my $client = shift; while (my $line = <$client>) { print $line; chomp $line; print $client $line + 1, "\n"; } } client: use strict; use IO::Socket; $|++; my $socket = IO::Socket::INET->new(PeerAddr => "localhost", PeerPort = +> '5123', Proto => "tcp") or die "Could not create client: $!\n"; print $socket "1\n"; while (my $line = <$socket>) { print $line; chomp $line; sleep 1; print $socket $line + 1, "\n"; }
In reply to Re: To Fork for Not to Fork
by pg
in thread To Fork for Not to Fork
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |