📄 ch15_02.htm
字号:
<html><head><title>The IO::Socket Module (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="ch15_01.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="ch16_01.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0" /></a></td></tr></table></div><h2 class="sect1">15.2. The IO::Socket Module</h2><p><a name="INDEX-1941" /><a name="INDEX-1942" /><a name="INDEX-1943" />The IO::Socket module included in thecore Perl distribution provides an object-oriented approach to socketprogramming. This module provides a convenient way to handle thelarge number of options you have to deal with, and it handles thelaborious task of forming addresses. IO::Socket is built upon theSocket module provided in the standard library. It inherits fromIO::Handle, which supports a class of filehandle objects for much ofthe IO library. The following IO::Socket functions are simplyfrontends for the corresponding built-in functions and use the samesyntax:</p><blockquote><pre class="code">socketsocketpairbindlistensendrecvpeername (same as getpeername)sockname (same as getsockname)</pre></blockquote><p><a name="INDEX-1944" />The <tt class="literal">accept</tt> functionin IO::Socket is slightly different from the equivalent function,however, and is described later in the chapter.</p><p>IO:Socket contains two subclasses: INET and UNIX. The INET subclassis used to create and manipulate Internet-domain sockets, such asthose used in the examples. The UNIX subclass creates Unix domainsockets.</p><a name="perlnut2-CHP-15-SECT-2.1" /><div class="sect2"><h3 class="sect2">15.2.1. Client-Side Sockets</h3><p><a name="INDEX-1945" /><a name="INDEX-1946" />IO::Socket greatly simplifies theimplementation of a socket for client communications. The followingexample creates an Internet-domain socket (using the INET subclass)and attempts to connect to the specified server:</p><blockquote><pre class="code">use IO::Socket;$sock = new IO::Socket::INET (PeerAddr => 'www.ora.com', PeerPort => 80, Proto => 'tcp');die "$!" unless $sock;</pre></blockquote><p><tt class="literal">IO::Socket::INET::new</tt> creates an object containinga socket filehandle and connects it to the host and port specified in<tt class="literal">PeerAddr</tt> and <tt class="literal">PeerPort</tt>. Theobject <tt class="literal">$sock</tt> can then be written to and read fromlike other socket filehandles.</p></div><a name="perlnut2-CHP-15-SECT-2.2" /><div class="sect2"><h3 class="sect2">15.2.2. Server-Side Sockets</h3><p><a name="INDEX-1947" /><a name="INDEX-1948" />On the server side, IO::Socketprovides a nice wrapper for creating server sockets. The wrapperencompasses the <tt class="literal">socket</tt>, <tt class="literal">bind</tt>,and <tt class="literal">listen</tt> procedures, while creating a newIO::Socket object. For example, we can create an Internet-domainsocket with <tt class="literal">IO::Socket::INET</tt>:</p><blockquote><pre class="code">use IO::Socket;$sock = new IO::Socket::INET (LocalAddr => 'maude.ora.com', LocalPort => 8888, Proto => 'tcp', Listen => 5);die "$!" unless $sock;</pre></blockquote><p>The parameters for the new socket object determine whether it is aserver or a client socket. Because we're creating aserver socket, <tt class="literal">LocalAddr</tt> and<tt class="literal">LocalPort</tt> provide the address and port to bind tothe socket. The <tt class="literal">Listen</tt> parameter gives the queuesize for the number of client requests that can wait for an<tt class="literal">accept</tt> at any one time.</p><p><a name="INDEX-1949" />When the server receives a clientrequest, it calls the <tt class="literal">accept</tt> method on the socketobject. This creates a new socket object on which the rest of thecommunication can take place:</p><blockquote><pre class="code">$new_sock = $sock->accept( );</pre></blockquote><p>When communication is finished on both client and server sockets,they should be destroyed with <tt class="literal">close</tt>. If a socketis not properly closed, the next time you attempt to use a socketwith the same name, the system will complain that the socket isalready in use.</p></div><a name="perlnut2-CHP-15-SECT-2.3" /><div class="sect2"><h3 class="sect2">15.2.3. IO::Socket Methods</h3><p>The following methods are defined in IO::Socket and can be used onsocket objects of either the INET or UNIX class.</p><a name="INDEX-1950" /><div class="refentry"><table width="515" border="0" cellpadding="5"><tr><td align="left"><font size="+1"><b>accept</b></font></td><td align="right"><i></i></td></tr></table><hr width="515" size="3" noshade="true" align="left" color="black" /><pre>accept ([<em class="replaceable">pkg</em>])</pre><p><a name="INDEX-1950" />Performs the <tt class="literal">accept</tt>system call on a socket and returns a new object. The new object iscreated in the same class as the listen socket, unless<em class="replaceable"><tt>pkg</tt></em> is specified. The object can be usedto communicate with the client that tried to connect. In a scalarcontext, the new socket is returned, or <tt class="literal">undef</tt> isreturned on failure. In an array context, a two-element array isreturned containing the new socket and the peer address, or an emptylist is returned on failure.</p></div><a name="INDEX-1951" /><div class="refentry"><table width="515" border="0" cellpadding="5"><tr><td align="left"><font size="+1"><b>protocol</b></font></td><td align="right"><i></i></td></tr></table><hr width="515" size="3" noshade="true" align="left" color="black" /><pre>protocol</pre><p><a name="INDEX-1951" />Returns the protocol number for theprotocol being used on the socket, if known. If the protocol isunknown, as with an AF_UNIX socket, returns <tt class="literal">0</tt></p></div><a name="INDEX-1952" /><div class="refentry"><table width="515" border="0" cellpadding="5"><tr><td align="left"><font size="+1"><b>sockdomain</b></font></td><td align="right"><i></i></td></tr></table><hr width="515" size="3" noshade="true" align="left" color="black" /><pre>sockdomain</pre><p><a name="INDEX-1952" />Returns the number representingthe socket address domain. For example, an AF_INET socket has thevalue <tt class="literal">&AF_INET</tt>.</p></div><a name="INDEX-1953" /><div class="refentry"><table width="515" border="0" cellpadding="5"><tr><td align="left"><font size="+1"><b>sockopt</b></font></td><td align="right"><i></i></td></tr></table><hr width="515" size="3" noshade="true" align="left" color="black" /><pre>sockopt (<em class="replaceable">opt</em>, [<em class="replaceable">val</em>])</pre><p><a name="INDEX-1953" />Sets and retrieves socket option<em class="replaceable"><tt>opt</tt></em> in the SOL_SOCKET level. The value<em class="replaceable"><tt>val</tt></em> is set for the option, if given. If novalue is provided, the function returns the current setting for theoption.</p></div><a name="INDEX-1954" /><div class="refentry"><table width="515" border="0" cellpadding="5"><tr><td align="left"><font size="+1"><b>socktype</b></font></td><td align="right"><i></i></td></tr></table><hr width="515" size="3" noshade="true" align="left" color="black" /><pre>socktype</pre><p><a name="INDEX-1954" />Returns the number representingthe socket type. For example, a SOCK_STREAM socket has the value<tt class="literal">&SOCK_STREAM</tt>.</p></div><a name="INDEX-1955" /><div class="refentry"><table width="515" border="0" cellpadding="5"><tr><td align="left"><font size="+1"><b>timeout</b></font></td><td align="right"><i></i></td></tr></table><hr width="515" size="3" noshade="true" align="left" color="black" /><pre>timeout ([<em class="replaceable">val</em>])</pre><p><a name="INDEX-1955" />Sets or retrieves the timeout valueassociated with a socket. Without an argument, the current value isreturned. If a timeout of <em class="replaceable"><tt>val</tt></em> is given,the setting is changed to <em class="replaceable"><tt>val</tt></em>, and theprevious value is returned.</p></div></div><a name="perlnut2-CHP-15-SECT-2.4" /><div class="sect2"><h3 class="sect2">15.2.4. IO::Socket::INET Reference</h3><p><a name="INDEX-1956" /><a name="INDEX-1957" /><a name="INDEX-1958" />An Internet-domain socket is createdwith the <tt class="literal">new</tt> method from the IO::Socket::INETsubclass. The constructor can take the following options:</p><dl><dt><b><tt class="literal">PeerAddr =></tt> <em class="replaceable">hostname</em><tt class="literal">[</tt>:<em class="replaceable">port</em><tt class="literal">]</tt></b></dt><dd><a name="INDEX-1959" />Specifies the remote hostand optional port number for a client connection.<em class="replaceable"><tt>hostname</tt></em> can be either a name, such as<em class="emphasis">www.oreilly.com</em>, or an IP numberof the form 207.44.21.2.</p></dd><dt><b><tt class="literal">PeerPort =></tt> <em class="replaceable">port</em></b></dt><dd><a name="INDEX-1960" />Specifies the port numberon the remote host for a client connection. The name of the service(such as <tt class="literal">http</tt> or <tt class="literal">nntp</tt>) may beused for the argument if the port number is not known.</p>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -