?? ch9.htm
字號:
has a destination and return address on the outside and containsthe data to be sent on the inside. A socket in this mode doesnot need to connect to a destination socket; it simply sends thedatagram. The UDP protocol promises only to make a best-effortdelivery attempt. Connectionless operation is fast and efficient,but not guaranteed.<P>Connection-oriented operation uses the Transport Control Protocol(TCP). A socket in this mode needs to connect to the destinationbefore sending data. Once connected, the sockets are accessedusing a streams interface: open-read-write-close. Everything sentby one socket is received by the other end of the connection inexactly the same order it was sent. Connection-oriented operationis less efficient than connectionless, but it's guaranteed.<P>Sun Microsystems has always been a proponent of internetworking,so it isn't surprising to find rich support for sockets in theJava class hierarchy. In fact, the Java classes have significantlyreduced the skill needed to create a sockets program. Each transmissionmode is implemented in a separate set of Java classes. The connection-orientedclasses will be discussed first.<H3><A NAME="JavaConnectionOrientedClasses">Java Connection-OrientedClasses</A></H3><P>The connection-oriented classes within Java have both a clientand a server representative. The client half tends to be the simplestto set up, so it will be covered first.<P>Listing 9.1 shows a simple client application. It requests anHTML document from a server and displays the response to the console.<HR><BLOCKQUOTE><B>Listing 9.1. A simple socket client.<BR></B></BLOCKQUOTE><BLOCKQUOTE><TT>import java.io.*;<BR>import java.net.*;<BR><BR>/**<BR> * An application that opens a connection to a Web server andreads<BR> * a single Web page from the connection.<BR> * NOTE: "merlin" is the name of my local machine.<BR> */<BR>public class SimpleWebClient {<BR> public static void main(String args[])<BR> {<BR> try<BR> {<BR> //Open a client socket connection<BR> SocketclientSocket1 = new Socket("merlin", 80);<BR> System.out.println("Client1:" + clientSocket1);<BR><BR> //Get a Web page<BR> getPage(clientSocket1);<BR> }<BR> catch (UnknownHostExceptionuhe)<BR> {<BR> System.out.println("UnknownHostException:" + uhe);<BR> }<BR> catch (IOExceptionioe)<BR> {<BR> System.err.println("IOException:" + ioe);<BR> }<BR> }<BR><BR> /**<BR> * Request a Web page using the passedclient socket.<BR> * Display the reply and close the clientsocket.<BR> */<BR> public static void getPage(Socket clientSocket)<BR> {<BR> try<BR> {<BR> //Acquire the input and output streams<BR> DataOutputStreamoutbound = new DataOutputStream(<BR> clientSocket.getOutputStream());<BR> DataInputStreaminbound = new DataInputStream(<BR> clientSocket.getInputStream());<BR><BR> //Write the HTTP request to the server<BR> outbound.writeBytes("GET/ HTTP/1.0\r\n\r\n");<BR><BR> //Read the response<BR> StringresponseLine;<BR> while((responseLine = inbound.readLine()) != null)<BR> {<BR> //Display each line to the console<BR> System.out.println(responseLine);<BR><BR> //This code checks for EOF. There is a bug in the<BR> //socket close code under Win 95. readLine() will<BR> //not return null when the client socket is closed<BR> //by the server.<BR> if( responseLine.indexOf("</HTML>") != -1 )<BR> break;<BR> }<BR><BR> //Clean up<BR> outbound.close();<BR> inbound.close();<BR> clientSocket.close();<BR> }<BR> catch (IOExceptionioe)<BR> {<BR> System.out.println("IOException:" + ioe);<BR> }<BR> }<BR>}</TT></BLOCKQUOTE><HR><P><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>Note</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>The examples in this chapter are coded as applications so as to avoid security restrictions. Run the code from the command line <TT>java ClassName</TT>.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P>Recall that a client socket issues a connect to a listening serversocket. Client sockets are created and connected by using a constructorfrom the Socket class. The following line creates a client socketand connects it to a host:<BLOCKQUOTE><TT>Socket clientSocket = new Socket("merlin",80);</TT></BLOCKQUOTE><P>The first parameter is the name of the host you want to connectto; the second parameter is the port number. A host name specifiesonly the destination computer. The port number is required tocomplete the transaction and allow an individual application toreceive the call. In this case, 80 was specified, the well-knownport number for the HTTP protocol. Other well-known port numbersare shown in Table 9.1. Port numbers are not mandated by any governingbody, but are assigned by convention-this is why they are saidto be "well known."<BR><P><CENTER><B>Table 9.1. Well-known port numbers.</B></CENTER><P><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=50%><TR VALIGN=TOP><TD WIDTH=73><I>Service</I></TD><TD WIDTH=48><CENTER><I>Port</I></CENTER></TD></TR><TR VALIGN=TOP><TD WIDTH=73>echo</TD><TD WIDTH=48><CENTER>7</CENTER></TD></TR><TR VALIGN=TOP><TD WIDTH=73>daytime</TD><TD WIDTH=48><CENTER>13</CENTER></TD></TR><TR VALIGN=TOP><TD WIDTH=73>ftp</TD><TD WIDTH=48><CENTER>21</CENTER></TD></TR><TR VALIGN=TOP><TD WIDTH=73>telnet</TD><TD WIDTH=48><CENTER>23</CENTER></TD></TR><TR VALIGN=TOP><TD WIDTH=73>smtp</TD><TD WIDTH=48><CENTER>25</CENTER></TD></TR><TR VALIGN=TOP><TD WIDTH=73>finger</TD><TD WIDTH=48><CENTER>79</CENTER></TD></TR><TR VALIGN=TOP><TD WIDTH=73>http</TD><TD WIDTH=48><CENTER>80</CENTER></TD></TR><TR VALIGN=TOP><TD WIDTH=73>pop3</TD><TD WIDTH=48><CENTER>110</CENTER></TD></TR></TABLE></CENTER><P><P>Because the Socket class is connection oriented, it provides astreams interface for reads and writes. Classes from the java.iopackage should be used to access a connected socket:<BLOCKQUOTE><TT>DataOutputStream outbound = new DataOutputStream(clientSocket.getOutputStream() );<BR>DataInputStream inbound = new DataInputStream( clientSocket.getInputStream());</TT></BLOCKQUOTE><P>Once the streams are created, normal stream operations can beperformed:<BLOCKQUOTE><TT>outbound.writeBytes("GET / HTTP/1.0\r\n\r\n);<BR>String responseLine;<BR>while ( (responseLine = inbound.readLine()) != null)<BR>{<BR> System.out.println(responseLine);<BR>}</TT></BLOCKQUOTE><P>The above code snippet requests a Web page and echoes the responseto the screen. When the program is done using the socket, theconnection needs to be closed:<BLOCKQUOTE><TT>outbound.close();<BR>inbound.close();<BR>clientSocket.close();</TT></BLOCKQUOTE><P>Notice that the socket streams are closed first. All socket streamsshould be closed before the socket is closed. This applicationis relatively simple, but all client programs follow the samebasic script:<OL><LI>Create the client socket connection.<LI>Acquire read and write streams to the socket.<LI>Use the streams according to the server's protocol.<LI>Close the streams.<LI>Close the socket.</OL><P>Using a server socket is only slightly more complicated, as explainedin the following section.<H4>Server Sockets</H4><P>Listing 9.2 is a partial listing of a simple server application.The complete server example can be found on the CD-ROM in SimpleWebServer.java.<HR><BLOCKQUOTE><B>Listing 9.2. A simple server application.<BR></B></BLOCKQUOTE><BLOCKQUOTE><TT>/**<BR> * An application that listens for connections and serves a simple<BR> * HTML document.<BR> */<BR>class SimpleWebServer {<BR> public static void main(String args[])<BR> {<BR> ServerSocket serverSocket= null;<BR> Socket clientSocket= null;<BR> int connects =0;<BR> try<BR> {<BR> //Create the server socket<BR> serverSocket= new ServerSocket(80, 5);<BR><BR> while(connects < 5)<BR> {<BR> //Wait for a connection<BR> clientSocket= serverSocket.accept();<BR><BR> //Servicethe connection<BR> ServiceClient(clientSocket);<BR> connects++;<BR> }<BR> serverSocket.close();<BR> }<BR> catch (IOException
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -