July 2000
Intermediate to advanced
1104 pages
35h 1m
English
use IO::Socket;
As a client:
$socket = new IO::Socket::INET (PeerAddr => $remote_host,
PeerPort => $remote_port,
Proto => "tcp",
Type => SOCK_STREAM)
or die "Can't connect to $remote_host:$remote_port : $!\n";# Or use the simpler single-argument interface.
$socket = IO::Socket::INET->new("$remote_host:$remote_port");
# "localhost:80", for example.
print $socket "data\n";
$line = <$socket>;As a server:
$server = IO::Socket::INET->new(LocalPort => $server_port,
Type => SOCK_STREAM,
Reuse => 1,
Listen => 10 ) # or SOMAXCONN
or die "Can't be a TCP server on port $server_port : $!\n";while ($client = $server->accept()) {
# $client is the new connection
$request = <$client>;
print $client "answer\n";
close $client;
}
# Make simple TCP connecting function that returns a filehandle
# for use in simple client programs.
sub tcp_connect {
my ($host, $service) = @_;
require IO::Socket;
return IO::Socket::INET->new(join ":", $host, $service);
}
my $fh = tcp_connect("localhost", "smtp"); # with scalar
local *FH = tcp_connect("localhost", "smtp"); # with handleThe IO::Socket module
provides a higher-level approach to socket handling than the raw
Socket module. You may use it in an object-oriented
fashion, although this isn't mandatory, because the return values are
proper filehandles and may be used as such, as shown in the
tcp_connect function in the example. This module
inherits methods from IO::Handle, and itself
requires IO::Socket::INET and
IO::Socket::UNIX. See the description of ...