PDA

View Full Version : Sockets and Threads question


Moorgasfahrer
02-07-2007, 08:16 AM
With the following stripped down code the perl program does not behave as it was intended. Can anybody tell me, what I missed?
The Code:

#!c:\usr\perl\bin\perl.exe

# Multithreaded-TCP-Server
use strict; # Always
use Term::ReadKey; # For unbuffered input from commandline
use threads; # For multithreading
use threads::shared; # For shared thread variables
use IO::Socket; # For socket communication
use POSIX; # For math functions
use constant BFPORT => 4610;
use constant PI => acos(-1);

my $newThread;
my $sock; # The socket
my $client; # The client connecting to the server
my $bfData; # The data received from the client


$sock = new IO::Socket::INET(LocalPort => BFPORT,
Reuse => 1,
Listen => 5)
or die "\nCan't create local socket: $@\n";

$SIG{'CHLD'} = sub { wait(); };

# Thread for command line menue
$newThread = threads->create("commandlineInterpreter");
$newThread->detach();

# Start server
print "\nAccepting connections on Port ", BFPORT, "...\n";
while ($client = $sock->accept())
{
# New connection
# Print who connects
print "\nAccepted connection from ",
$client->peerhost(), ":", $client->peerport(), "\n";

# Thread for new client.
$newThread = threads->create("bfReceiver");
$newThread->detach();
}

sub bfReceiver()
{
# The receiverthread.
print "\nReceiverthread started ";
while (recv($client, $bfData, 5000, 0))
{
if (length($bfData) <= 0)
{
return;
}
else
{
print "\nData with length ".length($bfData)." received";
}
}
return;
}

sub commandlineInterpreter()
{
my $key = " ";
ReadMode 4;
printMenue();
while (($key = getc))
{
print $key."\n";
last if $key eq "x";
printMenue();
}
ReadMode 1;
exit 0;
}

sub printMenue()
{
print "\n";
print "\nSim: x to end simulation";
print "\n\nSim: Your selection: ";
}
# EOF

What I witness is:
After I start a client the message "Accepted connection from 127.0.0.1:2601" is printed as expected. But I have to press the enter key in the program window to see the message "Receiverthread started" come up. And yet another hit on the enter key is necessary to get the messages
Data with length 1048 received
Data with length 1048 received
Data with length 1048 received
starting to come out. The client is sending them about once every second.

The intention of the program is a simple server simulation that prints out the received data where it is possible to set printout filters from the command line interface.
Why do the threads interfere? How can it be improved?
Thanks in advance for any suggestions!
Moorgasfahrer