tags:

views:

74

answers:

2
#!/usr/bin/perl -w

use IO::Socket;

my $sock = new IO::Socket::INET (
   PeerAddr => 'remotehost',
   PeerPort => '1230',
   Proto => 'tcp',
 ) or die "ERROR in Socket Creation : $!\n";


print "TCP Connection Success.\n";

# write on the socket to server.
$data = "this is the data to send";
$socket->send($data);


# read the socket data sent by server.
$data = <$socket>;
print "Received from Server : $data\n";

sleep(10);

close($sock);

I am unable to send and receive response from the remotehost using the above code...any ideas?

Thanks Ashish

+2  A: 

You declared my $sock when you created the socket. Then later you use

$socket->send($data)

This should be

$sock->send($data)

and later

$data = <$sock>
mjschultz
This should be `use strict; ...` *rest of script* `...`
mobrule
yeah i realized that, but even after that i cannot get the server response printed out..
ashchawla
Is the server working correctly? Did you change the `$socket` to `$sock` in the response line? In my test I just ran `nc -l 127.0.0.1 1230`. The perl script connected and sent its message, then I typed the reply in the `nc` window and the perl script received it.
mjschultz
the server is working correctly, when i do this from my java program it works fine...
ashchawla
Hmmm, perhaps try using the IP address of the host instead of the name? This post has a little work-around if that is the problem: http://stackoverflow.com/questions/160876/how-does-a-perl-socket-resolve-hostnames-under-linux
mjschultz
A: 

When working with network data, it is useful to do this after declaring your socket:

$sock->autoflush(1);

By default your IO is buffered and most likely the $data variable is less than buffer size. In such a case OS is waiting for more data before sending full buffer to the remote host. Setting autoflush disables buffering.

MariusM