Book Home Programming PerlSearch this book

32.29. IO::Socket

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 handle
The 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 the FileHandle module for other interesting features. See Chapter 16, "Interprocess Communication" for a description of using sockets.



Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.