Gossamer Forum
Home : General : Perl Programming :

Simple server socket problem

Quote Reply
Simple server socket problem
Hi all
I'm a newbie on perl programming and i need to create a tcp socket connection
my code is below and my problem is that i can't print the message from the client ($_)

#!/usr/bin/perl
use IO::Socket::INET;

my $my_server = 'whatever';
my $my_proto = 'tcp';
my $my_port = '1234';
my $my_listen = 1;
my $my_reuse = 1;

my $sock = IO::Socket::INET->new( LocalHost => $my_server,
LocalPort => $my_port,
Proto => $my_proto,
Listen => $my_listen,
Reuse => $my_reuse
);
die "Can't stablish connection with the socket: $!\n" unless $sock;
my $new_sock = $sock->accept();
while(defined(<$new_sock>))
{
print $_;
}
close $sock;

Happy coding!!!

José García Sabbagh
México D.F.
Quote Reply
Re: [sabbagh1o] Simple server socket problem In reply to
On the other hand i have the Client that just connect to the server and sends a "Hi there" message:

#TCP Socket Client
use IO::Socket::INET;

my $my_server = 'localhost';
my $my_proto = 'tcp';
my $my_port = '1234';

my $sock = IO::Socket::INET->new(
PeerAddr => $my_server,
PeerPort => $my_port,
Proto => $my_proto
);
die "Can't stablish a connection with the server: $!\n" unless $sock;
while($sock)
{
print $sock "Hello there!\n";
}
close($sock);


When i run both programs the server accept the connection but don't print the message.

Can u help me???

Happy coding!!!

José García Sabbagh
México D.F.
Quote Reply
Re: [sabbagh1o] Simple server socket problem In reply to
Change:

while(defined(<$new_sock>))

to:

while(<$new_sock>)

You don't want defined in there, Should work as expected then.

Cheers,

Alex
--
Gossamer Threads Inc.
Quote Reply
Re: [sabbagh1o] Simple server socket problem In reply to
As Alex says, change:

while(defined(<$new_sock>))

to:

while(<$new_sock>)

The 2nd form has hidden Perl magic which contains an automatic check for defined-ness and assigns the return from <> to $_.
The 1st one doesn't assign anything to $_, hence no output from your program.

Of course, if you'd had "use warnings;" near the top of your code (as any sensible program should, along with "use strict;"), perl would have given you a clue as to what was wrong...

Cheers,
Dave.
Quote Reply
Re: [utinni] Simple server socket problem In reply to
Quote:
as any sensible >development< program should
Quote Reply
Re: [Paul] Simple server socket problem In reply to
In Reply To:
Quote:
as any sensible >development< program should


Even small test programs benefit from these things, as the above code amply demonstrates.

I see little downside to strictures and warnings, and many benefits.

Cheers,
Dave.
Quote Reply
Re: [utinni] Simple server socket problem In reply to
use warnings;

...is a Perl 5.6.0+ feature. The -w switch is probably more compatible.
Quote Reply
Re: [Paul] Simple server socket problem In reply to
Thanks all, It works fine !!

Happy coding!!!

José García Sabbagh
México D.F.