Client Connections

On the client side, the next step is to connect with a server at a particular port and host. To do this, the client uses the connect call. connect requires the socket filehandle as its first argument. The second argument is a data structure containing the port and hostname that together specify the address. The Socket package provides the sockaddr_in function to create this structure for Internet addresses and the sockaddr_un function for Unix domain addresses.

The sockaddr_in function takes a port number for its first argument and a 32-bit IP address for the second argument. The 32-bit address is formed from the inet_aton function found in the Socket package. This function takes either a hostname (e.g., www.oreilly.com) or a dotted-decimal string (e.g., 207.54.2.25) and returns the corresponding 32-bit structure.

Continuing with the previous example, a call to connect could look like this:

my $dest = sockaddr_in (80, inet_aton('www.oreilly.com'));
connect (SH, $dest) || die $!;

This call attempts to establish a network connection to the specified server and port. If successful, it returns true. Otherwise, it returns false and dies with the error in $!.

Assuming that the connect call has completed successfully and a connection has been established, there are a number of functions we can use to write to and read from the filehandle. For example, the send function sends data to a socket:

$data = "Hello";
send (FH, $data);

The print function allows a wider variety of expressions for sending data to a filehandle:

select (FH);
print "$data";

To read incoming data from a socket, use either the recv function or the diamond input operator regularly used on filehandles. For example:

recv (FH, $buffer);
$input = <FH>;

After the conversation with the server is finished, use close or shutdown to close the connection and destroy the socket.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.59.219