⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch17_04.htm

📁 By Tom Christiansen and Nathan Torkington ISBN 1-56592-243-3 First Edition, published August 1998
💻 HTM
字号:
<HTML><HEAD><TITLE>Recipe 17.3. Communicating over TCP (Perl Cookbook)</TITLE><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen &amp; Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly &amp; Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:44:24Z"><METANAME="DC.type"CONTENT="Text.Monograph"><METANAME="DC.format"CONTENT="text/html"SCHEME="MIME"><METANAME="DC.source"CONTENT="1-56592-243-3"SCHEME="ISBN"><METANAME="DC.language"CONTENT="en-US"><METANAME="generator"CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0"><LINKREV="made"HREF="mailto:online-books@oreilly.com"TITLE="Online Books Comments"><LINKREL="up"HREF="ch17_01.htm"TITLE="17. Sockets"><LINKREL="prev"HREF="ch17_03.htm"TITLE="17.2. Writing a TCP Server"><LINKREL="next"HREF="ch17_05.htm"TITLE="17.4. Setting Up a UDP Client"></HEAD><BODYBGCOLOR="#FFFFFF"><img alt="Book Home" border="0" src="gifs/smbanner.gif" usemap="#banner-map" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Perl Cookbook"><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><p><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch17_03.htm"TITLE="17.2. Writing a TCP Server"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 17.2. Writing a TCP Server"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"><ACLASS="chapter"REL="up"HREF="ch17_01.htm"TITLE="17. Sockets"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch17_05.htm"TITLE="17.4. Setting Up a UDP Client"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 17.4. Setting Up a UDP Client"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch17-32506">17.3. Communicating over TCP</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch17-pgfId-418">Problem<ACLASS="indexterm"NAME="ch17-idx-1000004697-0"></A><ACLASS="indexterm"NAME="ch17-idx-1000004697-1"></A></A></H3><PCLASS="para">You want to read or write data over a TCP connection.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch17-pgfId-424">Solution</A></H3><PCLASS="para">This recipe assumes you're using the Internet to communicate. For TCP-like communication within a single machine, see <ACLASS="xref"HREF="ch17_07.htm"TITLE="Using UNIX Domain Sockets">Recipe 17.6</A>.</P><PCLASS="para">Use <CODECLASS="literal">print</CODE> or &lt; &gt; :</P><PRECLASS="programlisting">print SERVER &quot;What is your name?\n&quot;;chomp ($response = &lt;SERVER&gt;);</PRE><PCLASS="para">Or, use <CODECLASS="literal">send</CODE> and <CODECLASS="literal">recv</CODE> :</P><PRECLASS="programlisting">defined (send(SERVER, $data_to_send, $flags))    or die &quot;Can't send : $!\n&quot;;recv(SERVER, $data_read, $maxlen, $flags)    or die &quot;Can't receive: $!\n&quot;;</PRE><PCLASS="para">Or, use the corresponding methods on an IO::Socket object:</P><PRECLASS="programlisting">use IO::Socket;$server-&gt;send($data_to_send, $flags)    or die &quot;Can't send: $!\n&quot;;$server-&gt;recv($data_read, $flags)    or die &quot;Can't recv: $!\n&quot;;</PRE><PCLASS="para">To find out whether data can be read or written, use the <CODECLASS="literal">select</CODE> function, which is nicely wrapped by the standard IO::Socket class:</P><PRECLASS="programlisting">use IO::Select;$select = IO::Select-&gt;new();$select-&gt;add(*FROM_SERVER);$select-&gt;add($to_client);@read_from = $select-&gt;can_read($timeout);foreach $socket (@read_from) {    # read the pending data from $socket}</PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch17-pgfId-486">Discussion</A></H3><PCLASS="para">Sockets handle two completely different types of I/O, each with attendant pitfalls and benefits. The normal Perl I/O functions used on files (except for <CODECLASS="literal">seek</CODE> and <CODECLASS="literal">sysseek</CODE>) work for stream sockets, but datagram sockets require the system calls <CODECLASS="literal">send</CODE> and <CODECLASS="literal">recv</CODE>, which work on complete records.</P><PCLASS="para">Awareness of <ACLASS="indexterm"NAME="ch17-idx-1000004710-0"></A><ACLASS="indexterm"NAME="ch17-idx-1000004710-1"></A>buffering issues is particularly important in socket programming. That's because buffering, while designed to enhance performance, can interfere with the interactive feel that some programs require. Gathering input with &lt; &gt; may try to read more data from the socket than is yet available as it looks for a record separator. Both <CODECLASS="literal">print</CODE> and &lt; &gt; use <CODECLASS="literal">stdio</CODE> buffers, so unless you've changed autoflushing (see the Introduction to <ACLASS="xref"HREF="ch07_01.htm"TITLE="File Access">Chapter 7, <CITECLASS="chapter">File Access</CITE></A>) on the socket handle, your data won't be sent to the other end as soon as you <CODECLASS="literal">print</CODE> it. Instead, it will wait until a buffer fills up.</P><PCLASS="para">For line-based clients and servers, this is probably okay, so long as you turn on autoflushing for output. Newer versions of IO::Socket do this automatically on the anonymous filehandles returned by <CODECLASS="literal">IO::Socket-&gt;new</CODE>.</P><PCLASS="para">But stdio isn't the only source of buffering. Output (<CODECLASS="literal">print,</CODE> <CODECLASS="literal">printf</CODE>, or <CODECLASS="literal">syswrite</CODE>&nbsp;- or <CODECLASS="literal">send</CODE> on a TCP socket) is further subject to buffering at the operating system level under a strategy called <ICLASS="firstterm">The Nagle Algorithm</I><ACLASS="indexterm"NAME="ch17-idx-1000005813-0"></A>. When a packet of data has been sent but not acknowledged, further to-be-sent data is queued and is sent as soon as another complete packet's worth is collected or the outstanding acknowledgment is received. In some situations (mouse events being sent to a windowing system, keystrokes to a real-time application) this buffering is inconvenient or downright wrong. You can disable the Nagle Algorithm with the <ACLASS="indexterm"NAME="ch17-idx-1000005814-0"></A>TCP_NODELAY socket option:</P><PRECLASS="programlisting">use Socket;require &quot;sys/socket.ph&quot;;    # for &amp;TCP_NODELAYsetsockopt(SERVER, SOL_SOCKET, &amp;TCP_NODELAY, 1)    or die &quot;Couldn't disable Nagle's algorithm: $!\n&quot;;</PRE><PCLASS="para">Re-enable it with:</P><PRECLASS="programlisting">setsockopt(SERVER, SOL_SOCKET, &amp;TCP_NODELAY, 0)    or die &quot;Couldn't enable Nagle's algorithm: $!\n&quot;;</PRE><PCLASS="para">In most cases, TCP_NODELAY isn't something you need. TCP buffering is there for a reason, so don't disable it unless your application is one of the few real-time packet-intensive situations that need to.</P><PCLASS="para">Load in TCP_NODELAY from <EMCLASS="emphasis">sys/socket.ph</EM>, a file that isn't automatically installed with Perl, but can be easily built. See <ACLASS="xref"HREF="ch12_15.htm"TITLE="Using h2ph to Translate C #include Files">Recipe 12.14</A> for details.</P><PCLASS="para"><ACLASS="indexterm"NAME="ch17-idx-1000005971-0"></A>Because buffering is such an issue, you have the <CODECLASS="literal">select</CODE><ACLASS="indexterm"NAME="ch17-idx-1000004717-0"></A> function to determine which filehandles have unread input, which can be written to, and which have "exceptional conditions" pending. The <CODECLASS="literal">select</CODE> function takes three strings interpreted as binary data, each bit corresponding to a filehandle. A typical call to <CODECLASS="literal">select</CODE> looks like this:</P><PRECLASS="programlisting">$rin = '';                          # initialize bitmaskvec($rin, fileno(SOCKET), 1) = 1;   # mark SOCKET in $rin# repeat calls to vec() for each socket to check$timeout = 10;                      # wait ten seconds$nfound = select($rout = $rin, undef, undef, $timeout);if (vec($rout, fileno(SOCKET),1)){    # data to be read on SOCKET}</PRE><PCLASS="para">The four arguments to <CODECLASS="literal">select</CODE> are: a bitmask indicating which filehandles to check for unread data; a bitmask indicating which filehandles to check for safety to write without blocking; a bitmask indicating which filehandles to check for exceptional conditions on; and a time in seconds indicating the maximum time to wait (this can be a floating point number).</P><PCLASS="para">The function changes the bitmask arguments passed to it, so that when it returns, the only bits set correspond to filehandles ready for I/O. This leads to the common strategy of assigning an input mask (<CODECLASS="literal">$rin</CODE> above) to an output one (<CODECLASS="literal">$rout</CODE> about), so that <CODECLASS="literal">select</CODE> can only affect <CODECLASS="literal">$rout</CODE>, leaving <CODECLASS="literal">$rin</CODE> alone.</P><PCLASS="para">You can specify a timeout of 0 to <ICLASS="firstterm">poll</I> (check without blocking). Some beginning programmers think that blocking is bad, so they write programs that "busy wait"&nbsp;- they poll and poll and poll and poll. When a program blocks, the operating system recognizes that the process is pending on input and gives CPU time to other programs until input is available. When a program busy-waits, the system can't let it sleep because it's always doing something&nbsp;- checking for input! Occasionally, polling is the right thing to do, but far more often it's not. A timeout of <CODECLASS="literal">undef</CODE> to <CODECLASS="literal">select</CODE> means "no timeout," and your program will patiently block until input becomes available.</P><PCLASS="para">Because <CODECLASS="literal">select</CODE> uses bitmasks, which are tiresome to create and difficult to interpret, we use the standard IO::Select module in the Solution section. It bypasses bitmasks and is, generally, the easier route.</P><PCLASS="para">A full explanation of the exceptional data tested for with the third bitmask in <CODECLASS="literal">select</CODE> is beyond the scope of this book. Consult Stevens's <EMCLASS="emphasis">Unix Network Programming</EM> for a discussion of out-of-band and urgent data.</P><PCLASS="para"><ACLASS="indexterm"NAME="ch17-idx-1000005979-0"></A>Other <CODECLASS="literal">send</CODE> and <CODECLASS="literal">recv</CODE> flags are listed in the manpages for those system calls.<ACLASS="indexterm"NAME="ch17-idx-1000004699-0"></A><ACLASS="indexterm"NAME="ch17-idx-1000004699-1"></A></P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch17-pgfId-552">See Also</A></H3><PCLASS="para">The <ACLASS="olink"HREF="../prog/ch03_139.htm">&#13;<CODECLASS="literal">send</CODE></A>, <ACLASS="olink"HREF="../prog/ch03_119.htm">&#13;<CODECLASS="literal">recv</CODE></A>, <ACLASS="olink"HREF="../prog/ch03_038.htm">&#13;<CODECLASS="literal">fileno</CODE></A>, <ACLASS="olink"HREF="../prog/ch03_188.htm">&#13;<CODECLASS="literal">vec</CODE></A>, <ACLASS="olink"HREF="../prog/ch03_142.htm">&#13;<CODECLASS="literal">setsockopt</CODE></A>, and <ACLASS="olink"HREF="../prog/ch03_135.htm">&#13;<CODECLASS="literal">select</CODE></A> functions in <ACLASS="olink"HREF="../prog/ch03_01.htm">Chapter 3</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A> and in <ICLASS="filename">perlfunc </I>(1); the sections on "I/O Operators" and on "Bitwise String Operators" in <ICLASS="filename">perlop </I>(1); your system's <ICLASS="filename">setsockopt </I>(2) manpage (if you have one); the documentation for the standard Socket and IO::Socket modules; the section on <ACLASS="olink"HREF="../prog/ch06_02.htm#PERL2-CH-6-SECT-2.4.1">&#13;"Internet TCP clients and servers"</A> in <ACLASS="olink"HREF="../prog/ch06_01.htm">Chapter 6</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A> and in <ICLASS="filename">perlipc </I>(1); <CITECLASS="citetitle">Unix Network Programming</CITE>; <ACLASS="xref"HREF="ch17_02.htm"TITLE="Writing a TCP Client">Recipe 17.1</A>; <ACLASS="xref"HREF="ch17_03.htm"TITLE="Writing a TCP Server">Recipe 17.2</A></P></DIV></DIV><DIVCLASS="htmlnav"><P></P><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch17_03.htm"TITLE="17.2. Writing a TCP Server"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 17.2. Writing a TCP Server"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="book"HREF="index.htm"TITLE="Perl Cookbook"><IMGSRC="../gifs/txthome.gif"ALT="Perl Cookbook"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch17_05.htm"TITLE="17.4. Setting Up a UDP Client"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 17.4. Setting Up a UDP Client"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">17.2. Writing a TCP Server</TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="index"HREF="index/index.htm"TITLE="Book Index"><IMGSRC="../gifs/index.gif"ALT="Book Index"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228">17.4. Setting Up a UDP Client</TD></TR></TABLE><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><FONTSIZE="-1"></DIV<!-- LIBRARY NAV BAR --> <img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p> <a href="copyrght.htm">Copyright &copy; 2002</a> O'Reilly &amp; Associates. All rights reserved.</font> </p> <map name="library-map"> <area shape="rect" coords="1,0,85,94" href="../index.htm"><area shape="rect" coords="86,1,178,103" href="../lwp/index.htm"><area shape="rect" coords="180,0,265,103" href="../lperl/index.htm"><area shape="rect" coords="267,0,353,105" href="../perlnut/index.htm"><area shape="rect" coords="354,1,446,115" href="../prog/index.htm"><area shape="rect" coords="448,0,526,132" href="../tk/index.htm"><area shape="rect" coords="528,1,615,119" href="../cookbook/index.htm"><area shape="rect" coords="617,0,690,135" href="../pxml/index.htm"></map> </BODY></HTML>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -