📄 ch15_01.htm
字号:
<html><head><title>Sockets (Perl in a Nutshell, 2nd Edition)</title><link rel="stylesheet" type="text/css" href="../style/style1.css" /><meta name="DC.Creator" content="Stephen Spainhour" /><meta name="DC.Format" content="text/xml" scheme="MIME" /><meta name="DC.Language" content="en-US" /><meta name="DC.Publisher" content="O'Reilly & Associates, Inc." /><meta name="DC.Source" scheme="ISBN" content="0596002416L" /><meta name="DC.Subject.Keyword" content="stuff" /><meta name="DC.Title" content="Perl in a Nutshell, 2nd Edition" /><meta name="DC.Type" content="Text.Monograph" /></head><body bgcolor="#ffffff"><img src="gifs/smbanner.gif" usemap="#banner-map" border="0" alt="Book Home" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Java and XSLT" /><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><table width="684" border="0"><tr><td align="left" valign="top" width="228"><a href="part7.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0" /></a></td><td align="center" valign="top" width="228" /><td align="right" valign="top" width="228"><a href="ch15_02.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0" /></a></td></tr></table></div><h1 class="chapter">Chapter 15. Sockets</h1><div class="htmltoc"><h4 class="tochead">Contents:</h4> <p> <a href="#perlnut2-CHP-15-SECT-1">Built-in Socket Functions</a><br /><a href="ch15_02.htm">The IO::Socket Module</a><br /></p></div><p>Why build networking functionality into your Perl scripts? You mightwant to access your email remotely, or write a simple script thatupdates files on an FTP site<a name="INDEX-1897" /></a><a name="INDEX-1898" /></a>.You might want to check up on your employees with a program thatsearches for Usenet postings that came from your site. You might wantto check a web site for any recent changes, or even write your ownhome-grown web server. The network is the computer these days, andPerl makes network applications easy.</p><p>Perl programmers have their choice of modules for doing common taskswith network protocols; <a href="ch14_01.htm">Chapter 14, "SOAP"</a> through <a href="ch17_01.htm">Chapter 17, "Usenet News"</a> cover the modules forwriting email, news, FTP, and web applications in Perl. If you can dowhat you want with the available modules, you'reencouraged to jump to those chapters and skip this one. However,there will be times when you'll have to wrestle withsockets directly, and that's when this chapter comesin.</p><p>Sockets are the underlying mechanism for networking on the Internet.With sockets, one application (a <em class="emphasis">server</em>) sits ona port waiting for connections. Another application (the<em class="emphasis">client</em>) connects to that port and says hello;then the client and server have a chat. Their actual conversation isdone with whatever protocol they choose—for example, a webclient and server would use HTTP, an email server would use POP3 andSMTP, etc. But at the most basic level, you might say that allnetwork programming comes down to opening a socket, reading andwriting data, and closing the socket.</p><p>You can work with sockets in Perl at various levels. At the lowestlevel, Perl's built-in functions include socketroutines similar to the system calls in C of the same name. To makethese routines easier to use, the Socket module in the standardlibrary imports common definitions and constants specific to yoursystem's networking capabilities. Finally, theIO::Socket module provides an object interface to the socketfunctions through a standard set of methods and options forconstructing both client and server communications programs.</p><p>Sockets provide a connection between systems or applications. Theycan be set up to handle streaming data or discrete data packets.Streaming data continually comes and goes over a connection. Atransport protocol such as TCP (Transmission Control Protocol) isused to process streaming data so that all of the data is properlyreceived and ordered<a name="INDEX-1899" /></a><a name="INDEX-1900" /></a><a name="INDEX-1901" /></a>. Packet-oriented communication sendsdata across the network in discrete chunks. The message-orientedprotocol UDP (User Datagram Protocol) works on this type ofconnection. Although streaming sockets using TCP are widely used forapplications, UDP sockets also have their uses.</p><p>Sockets exist in one of two address domains: the Internet domain andthe Unix domain. Sockets used for Internet connections require thecareful binding and assignment of the proper type of address dictatedby the <a name="INDEX-1902" /></a>Internet Protocol (IP). These socketsare referred to as Internet-domain sockets.</p><p><a name="INDEX-1903" /></a>Sockets in the Unix domain createconnections between applications either on the same machine or withina LAN. The addressing scheme is less complicated, often justproviding the name of the target process.</p><p>In Perl, sockets are attached to a filehandle after they have beencreated. Communication over the connection is then handled bystandard Perl I/O functions.</p><div class="sect1"><a name="perlnut2-CHP-15-SECT-1" /></a><h2 class="sect1">15.1. Built-in Socket Functions</h2><p><a name="INDEX-1904" /></a><a name="INDEX-1905" /></a><a name="INDEX-1906" /></a><a name="INDEX-1907" /></a>Perlprovides built-in support for sockets. The following functions aredefined specifically for socket programming. For full descriptionsand syntax, see <a href="ch05_01.htm">Chapter 5, "Function Reference"</a>.</p><dl><dt><b><tt class="literal">socket</tt></b></dt><dd><a name="INDEX-1908" /></a>Initializes a socket and assigns afilehandle to it.<p></p></dd><dt><b><tt class="literal">bind</tt></b></dt><dd><a name="INDEX-1909" /></a>For servers, associates a socket with aport and address. For clients, associates a socket with a specificsource address.<p></p></dd><dt><b><tt class="literal">listen</tt></b></dt><dd><a name="INDEX-1910" /></a>(Server only.) Waits for incomingconnection with a client.<p></p></dd><dt><b><tt class="literal">accept</tt></b></dt><dd><a name="INDEX-1911" /></a>(Server only.) Accepts incomingconnection with a client.<p></p></dd><dt><b><tt class="literal">connect</tt></b></dt><dd><a name="INDEX-1912" /></a>(Client only.) Establishes a networkconnection on a socket.<p></p></dd><dt><b><tt class="literal">recv</tt></b></dt><dd><a name="INDEX-1913" /></a>Reads data from a socket filehandle.<p></p></dd><dt><b><tt class="literal">send</tt></b></dt><dd><a name="INDEX-1914" /></a>Writesdata to a filehandle.<p></p></dd><dt><b><tt class="literal">shutdown</tt> (or <tt class="literal">close</tt>)</b></dt><dd><a name="INDEX-1915" /></a>Terminates a network connection.<p></p></dd></dl><p>Regular functions that read and write filehandles can also be usedfor sockets, e.g., <tt class="literal">write</tt>,<tt class="literal">print</tt>, <tt class="literal">printf</tt>, and the diamondinput operator, <tt class="literal"><></tt>.</p><p>The socket functions tend to use hardcoded values for someparameters, which severely hurts portability. Perl solves thisproblem with a module called Socket, included in the standardlibrary. Use this module for any socket applications that you buildwith the built-in functions (e.g., <tt class="literal">use Socket</tt>).The module loads the <em class="emphasis">socket.h</em> header file, whichenables the built-in functions to use the constants and namesspecific to your system's network programming, aswell as additional functions for dealing with address and protocolnames.</p><p>The next few sections describe Perl socket programming using acombination of the built-in functions together with the Socketmodule. After that, we describe the use of the IO::Socket module.</p><a name="perlnut2-CHP-15-SECT-1.1" /></a><div class="sect2"><h3 class="sect2">15.1.1. Initializing a Socket</h3><p><a name="INDEX-1916" /></a><a name="INDEX-1917" /></a><a name="INDEX-1918" /></a>Bothclient and server use the <tt class="literal">socket</tt> call to create asocket and associate it with a filehandle. The<tt class="literal">socket</tt> function takes several arguments: the nameof the filehandle, the network domain, an indication of whether thesocket is stream-oriented or record-oriented, and the networkprotocol to be used. For example, HTTP (web) transactions requirestream-oriented connections running TCP. The following lines create asocket for this case and associates it with the filehandle<tt class="literal">SH</tt>:</p><blockquote><pre class="code">use Socket;socket(SH, PF_INET, SOCK_STREAM, getprotobyname('tcp')) || die $!;</pre></blockquote><p>The <tt class="literal">PF_INET</tt> argument indicates that the socketwill connect to addresses in the Internet domain (i.e., IPaddresses). Sockets with a Unix domain address use<tt class="literal">PF_UNIX</tt>.</p><p>Because this is a streaming connection using TCP, we specify<tt class="literal">SOCK_STREAM</tt> for the second argument. Thealternative would be to specify <tt class="literal">SOCK_DGRAM</tt> for apacket-based UDP connection.</p><p>The third argument indicates the protocol used for the connection.Each protocol has a number assigned to it by the system; that numberis passed to <tt class="literal">socket</tt> as the third argument. In thescalar context, <tt class="literal">getprotobyname</tt> returns theprotocolnumber<a name="INDEX-1919" /></a>.</p><p>Finally, if the socket call fails, the program will<tt class="literal">die</tt>, printing the error message found in<tt class="literal">$!</tt>.</p></div><a name="perlnut2-CHP-15-SECT-1.2" /></a><div class="sect2"><h3 class="sect2">15.1.2. Client Connections</h3><p><a name="INDEX-1920" /></a><a name="INDEX-1921" /></a><a name="INDEX-1922" /></a>On the client side, the next step is toconnect with a server at a particular port and host. To do this, theclient uses the <tt class="literal">connect</tt> call.<tt class="literal">connect</tt> requires the socket filehandle as itsfirst argument. The second argument is a data structure containingthe port and hostname that together specify the address. The Socketpackage provides the <tt class="literal">sockaddr_in</tt> function tocreate this structure for Internet addresses and the<tt class="literal">sockaddr_un</tt> function for Unix domain addresses.</p>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -