📄 ch17_02.htm
字号:
<HTML><HEAD><TITLE>Recipe 17.1. Writing a TCP Client (Perl Cookbook)</TITLE><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen & Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly & Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:44:21Z"><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_01.htm"TITLE="17.0. Introduction"><LINKREL="next"HREF="ch17_03.htm"TITLE="17.2. Writing a TCP Server"></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_01.htm"TITLE="17.0. Introduction"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 17.0. Introduction"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_03.htm"TITLE="17.2. Writing a TCP Server"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 17.2. Writing a TCP Server"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch17-42449">17.1. Writing a TCP Client</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch17-pgfId-110">Problem<ACLASS="indexterm"NAME="ch17-idx-1000004679-0"></A><ACLASS="indexterm"NAME="ch17-idx-1000004679-1"></A><ACLASS="indexterm"NAME="ch17-idx-1000004679-2"></A></A></H3><PCLASS="para">You want to connect to a socket on a remote machine.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch17-pgfId-116">Solution</A></H3><PCLASS="para">This solution 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">Either use the standard (as of 5.004) <ACLASS="indexterm"NAME="ch17-idx-1000004680-0"></A>IO::Socket::INET class:</P><PRECLASS="programlisting">use IO::Socket;$socket = IO::Socket::INET->new(PeerAddr => $remote_host, PeerPort => $remote_port, Proto => "tcp", Type => SOCK_STREAM) or die "Couldn't connect to $remote_host:$remote_port : $@\n";# ... do something with the socketprint $socket "Why don't you call me anymore?\n";$answer = <$socket>;# and terminate the connection when we're doneclose($socket);</PRE><PCLASS="para">or create a socket by hand for better control:</P><PRECLASS="programlisting">use Socket;# create a socketsocket(TO_SERVER, PF_INET, SOCK_STREAM, getprotobyname('tcp'));# build the address of the remote machine$internet_addr = inet_aton($remote_host) or die "Couldn't convert $remote_host into an Internet address: $!\n";$paddr = sockaddr_in($remote_port, $internet_addr);# connectconnect(TO_SERVER, $paddr) or die "Couldn't connect to $remote_host:$remote_port : $!\n";# ... do something with the socketprint TO_SERVER "Why don't you call me anymore?\n";# and terminate the connection when we're doneclose(TO_SERVER);</PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch17-pgfId-194">Discussion</A></H3><PCLASS="para">While coding this by hand requires a lot of steps, the IO::Socket::INET class wraps them all in a convenient constructor. The important things to know are where you're going (the PeerAddr and PeerPort parameters) and how you're getting there (the Type parameter). IO::Socket::INET tries to determine these things from what you've given it. It deduces Proto from the Type and Port if possible, and assumes <CODECLASS="literal">tcp</CODE> otherwise.</P><PCLASS="para">PeerAddr is a string containing either a hostname (<CODECLASS="literal">"www.oreilly.com"</CODE>) or an IP address (<CODECLASS="literal">"204.148.40.9"</CODE>). PeerPort is an integer, the port number to connect to. You can embed the port number in the address by giving an address like <CODECLASS="literal">"www.oreilly.com:80"</CODE>. Type is the kind of socket to create: SOCK_DGRAM for datagrams, or SOCK_STREAM for streams.</P><PCLASS="para">If you want a SOCK_STREAM connection to a port on a particular machine with no other options, pass a single string to <CODECLASS="literal">IO::Socket::INET->new</CODE> consisting of the hostname and port separated by a colon:</P><PRECLASS="programlisting">$client = IO::Socket::INET->new("www.yahoo.com:80") or die $@;</PRE><PCLASS="para">If an error occurs, IO::Socket::INET will return <CODECLASS="literal">undef</CODE> and <CODECLASS="literal">$@</CODE> (<EMCLASS="emphasis">not</EM> <CODECLASS="literal">$!</CODE>) will be set to the error message.</P><PRECLASS="programlisting">$s = IO::Socket::INET->new(PeerAddr => "Does not Exist", Peerport => 80, Type => SOCK_STREAM ) or die $@;</PRE><PCLASS="para">If your packets are disappearing into a network void, it can take a while for your inability to connect to a port to be recognized. You can decrease this time by specifying a <CODECLASS="literal">Timeout</CODE> parameter to <CODECLASS="literal">IO::Socket::INET->new()</CODE>:</P><PRECLASS="programlisting">$s = IO::Socket::INET->new(PeerAddr => "bad.host.com", PeerPort => 80, Type => SOCK_STREAM, Timeout => 5 ) or die $@;</PRE><PCLASS="para">If you do this, though, there's no way to tell from <CODECLASS="literal">$!</CODE> or <CODECLASS="literal">$@</CODE> whether you couldn't connect or whether you timed out. Sometimes it's better to set it up by hand instead of using a module.</P><PCLASS="para"><ACLASS="indexterm"NAME="ch17-idx-1000004916-0"></A>INADDR_ANY is a special address, meaning "listen on any interface." If you want to restrict it to a particular IP address, add a <CODECLASS="literal">LocalAddr</CODE> parameter to your call to <CODECLASS="literal">IO::Socket::INET->new.</CODE> If coding by hand code, do this:</P><PRECLASS="programlisting">$inet_addr = inet_aton("208.146.240.1");$paddr = sockaddr_in($port, $inet_addr);bind(SOCKET, $paddr) or die "bind: $!";</PRE><PCLASS="para">If you know only the name, do this:</P><PRECLASS="programlisting">$inet_addr = gethostbyname("www.yahoo.com") or die "Can't resolve www.yahoo.com: $!";$paddr = sockaddr_in($port, $inet_addr);bind(SOCKET, $paddr) or die "bind: $!";<ACLASS="indexterm"NAME="ch17-idx-1000004682-0"></A><ACLASS="indexterm"NAME="ch17-idx-1000004682-1"></A><ACLASS="indexterm"NAME="ch17-idx-1000004682-2"></A></PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch17-pgfId-250">See Also</A></H3><PCLASS="para">The <ACLASS="olink"HREF="../prog/ch03_151.htm"> <CODECLASS="literal">socket</CODE></A>, <ACLASS="olink"HREF="../prog/ch03_007.htm"> <CODECLASS="literal">bind</CODE></A>, <ACLASS="olink"HREF="../prog/ch03_020.htm"> <CODECLASS="literal">connect</CODE></A>, and <ACLASS="olink"HREF="../prog/ch03_048.htm"> <CODECLASS="literal">gethostbyname</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 documentation for the standard Socket, IO::Socket, and Net::hostent modules; the section on <ACLASS="olink"HREF="../prog/ch06_02.htm#PERL2-CH-6-SECT-2.4.1"> "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>, by W. Richard Stevens, published by Prentice Hall (1992); <ACLASS="xref"HREF="ch17_03.htm"TITLE="Writing a TCP Server">Recipe 17.2</A>; <ACLASS="xref"HREF="ch17_04.htm"TITLE="Communicating over TCP">Recipe 17.3</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_01.htm"TITLE="17.0. Introduction"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 17.0. Introduction"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_03.htm"TITLE="17.2. Writing a TCP Server"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 17.2. Writing a TCP Server"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">17.0. Introduction</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.2. Writing a TCP Server</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 © 2002</a> O'Reilly & 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 + -