Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Server Problem

by pokemonk (Scribe)
on Nov 23, 2001 at 20:18 UTC ( [id://127132] : perlquestion . print w/replies, xml ) Need Help??

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

Ok, so i have this code:
use IO::Socket::INET; my $sock = new IO::Socket::INET ( LocalPort => 6547, Listen => 10, Proto => 'tcp', Reuse => 1 ); print "Waiting For Requests!!\n"; while(my $client = $sock->accept()){ print "Connection!\n"; my $blah=<$client>; handle($blah,$client); $client->close(); } sub handle{ my ($data,$client) = @_; chomp($data); my ($command, $param) = split '<div>',$data; print "$command\n"; if($command == 'start'){ print $client "Welcome to the game: $param\n"; } if($command == 'newUser'){ print $client "$param Has been added to the database!!\n"; } }
So, if i send "start" to the server, it will return "Welcome to the game: ", but if i send "newUser<div>username", the server returns "Welcome to the game: username" and sometimes it returns "username has been added to the database, and sometimes i'll return both!!!

I put that print statment before the conditionals to see if $command was right, and yes it is, it prints the right parameter i send.

Please HELP! thanks.

Replies are listed 'Best First'.
Re: Server Problem
by wog (Curate) on Nov 23, 2001 at 20:31 UTC
    The problem is probably in your conditionals; $command == 'start' compares $command and 'start' as numbers, likely converting them both to zero first then finding them always equal. You probably meant to use $command eq 'start', etc.

    You may find it useful to switch to a dispatch table instead of a whole bunch of if statements:

    sub handle_start { my($client,$param) = @_; print $client "Welcome to the game: $param\n"; } # ... more commands ... my %commands = ( start => \&handle_start, # ... more ... ); sub handle { # ... if (not exsits $commands{$commands}) { # bad command } else { # run command $commands{$command}->($client,$param); } # ... }

    (A side note: split always treats it's first argument as a regex, even if it is single-quoted like you have it. As a matter of style, I would advise using /<div>/ or similar so as not to make it look like it doesn't take a regex...)

Re: Server Problem
by MZSanford (Curate) on Nov 23, 2001 at 20:30 UTC
    A few things off the top of my rather empty head ...
    • use eq, not == for the string comparrisons in &handle()
    • you may want to use elsif instead of two seperate if statements.
    • Make sure you are using a CRLF at the end of each line you print (some clients will require that)
    • if the above does not help, you may want to look into using non-buffered IO


    i had a memory leak once, and it ruined my favorite shirt.