?? ch9.htm
字號:
<BR>public class SimpleDatagramServer<BR>{<BR> public static void main(String[] args)<BR> {<BR> DatagramSocketsocket = null;<BR> DatagramPacketrecvPacket, sendPacket;<BR> try<BR> {<BR> socket= new DatagramSocket(4545);<BR> while(socket != null)<BR> {<BR> recvPacket=new DatagramPacket(new byte[512], 512);<BR> socket.receive(recvPacket);<BR> sendPacket= new DatagramPacket(<BR> recvPacket.getData(),recvPacket.getLength(),<BR> recvPacket.getAddress(),recvPacket.getPort() );<BR> socket.send(sendPacket );<BR> }<BR> }<BR> catch (SocketExceptionse)<BR> {<BR> System.out.println("Errorin SimpleDatagramServer: " + se);<BR> }<BR> catch (IOExceptionioe)<BR> {<BR> System.out.println("Errorin SimpleDatagramServer: " + ioe);<BR> }<BR> }<BR>}</TT></BLOCKQUOTE><HR><H4>Datagram Clients</H4><P>The corresponding client uses the same process with one exception:A client must initiate the conversation. The basic recipe fordatagram clients is as follows:<OL><LI>Create the datagram socket on any available port.<LI>Create the address to send to.<LI>Send the data according to the server's protocol.<LI>Wait for receive data.<LI>Go to step 3 (send more data), 4 (wait for receive), or 6(exit).<LI>Close the datagram socket.</OL><P>Figure 9.2 summarizes the steps needed for client/server datagramapplications. The symmetry between client and server is evidentfrom this picture; compare Figure 9.2 with Figure 9.1.<P><A HREF="f9-2.gif" ><B>Figure 9.2 </B>: <I>Client and server datagram applications.</I></A><P>Listing 9.4 shows a simple datagram client. It reads user inputstrings and sends them to the echo server from Listing 9.3. Theecho server will send the data right back, and the client willprint the response to the console.<HR><BLOCKQUOTE><B>Listing 9.4. A simple datagram client.<BR></B></BLOCKQUOTE><BLOCKQUOTE><TT>import java.io.*;<BR>import java.net.*;<BR><BR>public class SimpleDatagramClient<BR>{<BR> private DatagramSocket socket = null;<BR> private DatagramPacket recvPacket, sendPacket;<BR> private int hostPort;<BR><BR> public static void main(String[] args)<BR> {<BR> DatagramSocketsocket = null;<BR> DatagramPacketrecvPacket, sendPacket;<BR> try<BR> {<BR> socket= new DatagramSocket();<BR> InetAddresshostAddress = InetAddress.getByName("merlin");<BR> DataInputStreamuserData = new DataInputStream( System.in );<BR> while(socket != null)<BR> {<BR> StringuserString = userData.readLine();<BR> if(userString == null || userString.equals(""))<BR> return;<BR> bytesendbuf[] = new byte[ userString.length() ];<BR> userString.getBytes(0,userString.length(), sendbuf, 0);<BR> sendPacket= new DatagramPacket(<BR> sendbuf,sendbuf.length, hostAddress, 4545 );<BR> socket.send(sendPacket );<BR> recvPacket=new DatagramPacket(new byte[512], 512);<BR> socket.receive(recvPacket);<BR> System.out.write(recvPacket.getData(),0,<BR> recvPacket.getLength());<BR> System.out.print("\n");<BR> }<BR> }<BR> catch (SocketExceptionse)<BR> {<BR> System.out.println("Errorin SimpleDatagramClient: " + se);<BR> }<BR> catch (IOExceptionioe)<BR> {<BR> System.out.println("Errorin SimpleDatagramClient: " + ioe);<BR> }<BR> }<BR>}</TT></BLOCKQUOTE><HR><P>All the examples so far have been Java applications. Running thesein an applet presents an extra complication: security.<H3><A NAME="AppletSecurityandSockets">Applet Security and Sockets</A></H3><P>When writing applications, you don't need to be concerned withsecurity exceptions. This changes when the code under developmentis executed from an applet. Netscape Navigator 2.0 uses very stringentsecurity measures where sockets are concerned. An applet may opena socket only back to the host name from which it was loaded.If any other connection is attempted, a SecurityException willbe thrown.<P>Datagram sockets don't open connections, so how is security ensuredfor these sockets? When an inbound packet is received, the hostname is checked. If the packet did not originate from the server,a SecurityException is immediately thrown. Obviously, sendingcomes under the same scrutiny. If a datagram socket tries to sendto any destination except the server, a SecurityException is thrown.These restrictions apply only to the address, not the port number.Any port number on the host may be used.<P>All the socket techniques demonstrated so far will be developedfurther in this chapter's project.<H2><A NAME="ChapterProjectHTTPServerApplication"><FONT SIZE=5 COLOR=#FF0000>ChapterProject: HTTP Server Application and Client Applet</FONT></A></H2><P>This project at first glance seems a bit ambitious, but writinga rudimentary Web server is not as hard as it sounds. Client appletsneed an HTTP Web server so they can open sockets. If an appletis loaded into Netscape from a hard drive, then no socket activityis allowed to take place. A simple solution is to write an HTTPserver application. Once written, additional server threads canbe added to provide all types of back-end connectivity. This projectwill add a multipurpose datagram protocol that will be used forlive data in both <A HREF="ch10.htm" >Chapter 10</A>, "NativeMethods and Java," and 11, "Building a Live Data Applet."<H3><A NAME="ChapterProjectHTTPServeApplication">Chapter Project:HTTP Server Application and Client Applet</A></H3><P>Before diving into the project, you need some background informationon the HTTP protocol. The Hypertext Transfer Protocol (HTTP) hasbeen in use on the World Wide Web since 1990. All applet-bearingWeb pages are sent over the net with HTTP. The server will supporta subset of version 1.0 in that only file requests will be handled.As long as Netscape page requests can be fulfilled, the serverwill have accomplished its goal.<P>HTTP uses a stream-oriented (TCP) socket connection. Typically,port 80 is used, but other port numbers can be substituted. Allthe protocol is sent in plain-text format. An example of a conversationwas demonstrated in Listings 9.1 and 9.2. The server listens onport 80 for a client request, which takes this format:<BLOCKQUOTE><TT>GET FILE HTTP/1.0</TT></BLOCKQUOTE><P>The first word is referred to as the "method" of therequest. Table 9.2 lists all the request methods for HTTP/1.0.<BR><P><CENTER><B>Table 9.2. HTTP/1.0 request methods.</B></CENTER><P><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD WIDTH=77><I>Method</I></TD><TD WIDTH=314><I>Use</I></TD></TR><TR VALIGN=TOP><TD WIDTH=77>GET</TD><TD WIDTH=314>Retrieve a file</TD></TR><TR VALIGN=TOP><TD WIDTH=77>HEAD</TD><TD WIDTH=314>Retrieve only file information</TD></TR><TR VALIGN=TOP><TD WIDTH=77>POST</TD><TD WIDTH=314>Send data to the server</TD></TR><TR VALIGN=TOP><TD WIDTH=77>PUT</TD><TD WIDTH=314>Send data to the server</TD></TR><TR VALIGN=TOP><TD WIDTH=77>DELETE</TD><TD WIDTH=314>Delete a resource</TD></TR><TR VALIGN=TOP><TD WIDTH=77>LINK</TD><TD WIDTH=314>Link two resources</TD></TR><TR VALIGN=TOP><TD WIDTH=77>UNLINK</TD><TD WIDTH=314>Unlink two resources</TD></TR></TABLE></CENTER><P><P>The second parameter of a request is a file path. Each of thefollowing URLs is followed by the request that will be formulatedand sent:<BLOCKQUOTE><TT>HTTP://www.qnet.com/<BR>GET / HTTP/1.0<BR><BR>HTTP://www.qnet.com/index.html<BR>GET /index.html HTTP/1.0<BR><BR>HTTP://www.qnet.com/classes/applet.html<BR>GET /classes/applet.html HTTP/1.0</TT></BLOCKQUOTE><P>The request does not end until a blank line containing only acarriage return (\r) and a line feed (\n) is received. After themethod line, a number of optional lines can be sent. NetscapeNavigator 2.0 will produce the following request:<BLOCKQUOTE><TT>GET / HTTP/1.0<BR>Connection: Keep-Alive<BR>User-Agent: Mozilla/2.0 (Win95; I)<BR>Host: merlin<BR>Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*</TT></BLOCKQUOTE><P>Responses use a header similar to the request:<BLOCKQUOTE><TT>HTTP/1.0 200 OK<BR>Content-type: text/html<BR>Content-Length: 128</TT></BLOCKQUOTE><P>Like the request, the response header is not complete until ablank line is sent containing only a carriage return and a linefeed. The first line contains a version identification string,followed by a status code indicating the results of the request.Table 9.3 lists all the defined status codes. The server willsend only two of these: 200 and 404. The text that follows thestatus code is optional. It may be omitted, or, if present, itmight not match the definitions given in the table.<BR><P><CENTER><B>Table 9.3. HTTP response status codes.</B></CENTER><P><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD WIDTH=151><CENTER><I>Status Code</I></CENTER></TD><TD WIDTH=240><I>Optional Text Description</I></TD></TR><TR VALIGN=TOP><TD WIDTH=151><CENTER>200</CENTER></TD><TD WIDTH=240>OK</TD></TR><TR VALIGN=TOP><TD WIDTH=151><CENTER>201</CENTER></TD><TD WIDTH=240>Created</TD></TR><TR VALIGN=TOP><TD WIDTH=151><CENTER>202</CENTER></TD><TD WIDTH=240>Accepted</TD></TR><TR VALIGN=TOP><TD WIDTH=151><CENTER>204</CENTER></TD><TD WIDTH=240>No Content</TD></TR><TR VALIGN=TOP><TD WIDTH=151><CENTER>300</CENTER></TD><TD WIDTH=240>Multiple Choices</TD></TR><TR VALIGN=TOP><TD WIDTH=151><CENTER>301</CENTER></TD><TD WIDTH=240>Moved Permanently</TD></TR><TR VALIGN=TOP><TD WIDTH=151><CENTER>302</CENTER></TD><TD WIDTH=240>Moved Temporarily</TD></TR><TR VALIGN=TOP><TD WIDTH=151><CENTER>304</CENTER></TD><TD WIDTH=240>Not Modified</TD></TR><TR VALIGN=TOP><TD WIDTH=151><CENTER>400</CENTER></TD><TD WIDTH=240>Bad Request
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -