TCP/IP using perl

TCP/IP using perl

Shlomi Fish shlomif at shlomifish.org
Sat Apr 7 16:39:12 IDT 2012


Hi Ori,

Happy Passover to everybody.

some comments on your code.

On Sat, 7 Apr 2012 10:20:35 +0300
Ori Idan <ori at helicontech.co.il> wrote:

> I have a simple device that I need to send few lines of data in TCP
> protocol.
> The device should respond on each line sent.
> 
> I am using the following code:
> 
> #!/usr/bin/perl
> use IO::Socket::INET;

It's good that you are using the IO::Socket family of modules for socket
communications instead of the built-in and Socket.pm primitives (it is much
more recommended). However, you should add "use strict;" and "use warnings;"
to your code. See:

http://perl-begin.org/tutorials/bad-elements/ (caveat: this is a
site and a page which I have originated).

> 
> my ($socket,$client_socket);

You should not pre-declare your variables. Instead do:

my $socket = INIT_EXPR() at the time you want to initialise it. I cover it on
the "bad-elements" page as well.
  
> 
> $socket = new IO::Socket::INET (
> PeerHost => '192.168.0.20',
> PeerPort => '5086',
> Proto => 'tcp',
> ) or die "ERROR in Socket Creation : $!\n";
> 

The "or die" makes me happy, but you should write:

	IO::Socket::INET->new(...)

instead of:

	new IO::Socket::INET

See:

http://perl-begin.org/tutorials/bad-elements/#indirect-object-notation

> 
> $socket->send("a\n");

Shouldn't it be \r\n instead of \n? Note that Perl’s \n and \r are an
abstraction over the ASCII characters. For more information see:

http://onlamp.com/onlamp/2006/08/17/understanding-newlines.html

Link is currently broken (but O'Reilly says it is in maintenanace and will be
restored soon), so you can look at:

http://web.archive.org/web/20101101194037/http://onlamp.com/onlamp/2006/08/17/understanding-newlines.html

> $socket->recv($data, 128);
> print "Data 1: $data\n";
>

Where was $data declared? You should declare it using my.
 
> $socket->send("111000\n");

Again "\n" may be a problem.

> $socket->recv($data, 128);
> 

You don't have a print here.

> It seems that the device gets the first line but not the second line.
> Does anyone have an idea what am I doing wrong?
> 

Well, it might be a buffering problem:

http://perl.plover.com/FAQs/Buffering.html

Otherwise, does Wireshark tell you anything suspicious?

Regards,

	Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
My Public Domain Photos - http://www.flickr.com/photos/shlomif/

If you have the same ideas as everybody else, but have them one week earlier
than everyone else — then you will be hailed as a visionary. But if you have
them five years earlier, you will be named a lunatic. ( Barry Jones )

Please reply to list if it's a mailing list post - http://shlom.in/reply .



More information about the Linux-il mailing list