home *** CD-ROM | disk | FTP | other *** search
/ ftp.pasteur.org/FAQ/ / ftp-pasteur-org-FAQ.zip / FAQ / computer-lang / java / network-programming < prev   
Encoding:
Text File  |  2004-04-18  |  39.7 KB  |  1,058 lines

  1. Path: senator-bedfellow.mit.edu!dreaderd!not-for-mail
  2. Message-ID: <computer-lang/java/network-programming_1082200966@rtfm.mit.edu>
  3. Supersedes: <computer-lang/java/network-programming_1079601013@rtfm.mit.edu>
  4. Expires: 31 May 2004 11:22:46 GMT
  5. X-Last-Updated: 2000/05/02
  6. Organization: none
  7. From: dodo@fan.net.au (David Reilly)
  8. Newsgroups: comp.lang.java.programmer,comp.answers,news.answers 
  9. Approved: news-answers-request@MIT.EDU
  10. Subject: Java Network Programming FAQ
  11. Followup-To: poster
  12. Summary: This document answers frequently asked questions about Java 
  13.          Network Programming
  14. Originator: faqserv@penguin-lust.MIT.EDU
  15. Date: 17 Apr 2004 11:28:18 GMT
  16. Lines: 1037
  17. NNTP-Posting-Host: penguin-lust.mit.edu
  18. X-Trace: 1082201298 senator-bedfellow.mit.edu 576 18.181.0.29
  19. Xref: senator-bedfellow.mit.edu comp.lang.java.programmer:597041 comp.answers:56878 news.answers:269970
  20.  
  21. Archive-name: computer-lang/java/network-programming
  22. Posting-Frequency: monthly
  23. Last-modified: May 2, 1999
  24. Copyright: Copyright 1998-2000 David Reilly. All Rights Reserved.
  25. Maintainer: David Reilly (dodo@fan.net.au)
  26. URL: http://www.davidreilly.com/java/java_network_programming/
  27.  
  28. Java Network Programming FAQ.
  29. Copyright 1998, 1999 David Reilly. All Rights Reserved.
  30. ------------------------------------------------------------
  31.  
  32. Last modification date : May 2, 1999
  33.  
  34. This document contains the answers to commonly asked network
  35. programming questions posed by Java developers. Copies of
  36. this document mirrored at other sites may be out of date,
  37. please ensure that you're looking at a current version. The
  38. latest version of this document can be found at
  39. http://www.davidreilly.com/java/java_network_programming/
  40.  
  41. ------------------------------------------------------------
  42.  
  43. Table of contents
  44.  
  45. Overview
  46.   Legal
  47.   Comments
  48.   Books
  49.   Websites
  50.  
  51. Basic programming questions
  52.  
  53.   1. Socket Questions
  54.  
  55.   1.1 Should I use ServerSocket or DatagramSocket in my
  56.       applications?
  57.   1.2 How do I get the IP address of a machine from its
  58.       hostname?
  59.   1.3 How do I perform a hostname lookup for an IP address?
  60.   1.4 How can I find out who is accessing my server?
  61.   1.5 How can I find out the current IP address for my
  62.       machine?
  63.   1.6 Why can't my applet connect via sockets, or bind to a
  64.       local port?
  65.   1.7 What are socket options, and why should I use them?
  66.   1.8 When my client connects to my server, why does no data
  67.       come out?
  68.   1.9 What is the cause of a NoRouteToHost exception?
  69.  
  70.   2. HTTP Questions
  71.  
  72.   2.1 How do I display a particular web page from an applet?
  73.   2.2 How do I display more than one page from an applet?
  74.   2.3 How can I fetch files using HTTP?
  75.   2.4 How do I use a proxy server for HTTP requests?
  76.   2.5 What is a malformed URL, and why is it exceptional?
  77.   2.6 How do I URL encode the parameters of a CGI script?
  78.   2.7 Why is a security exception thrown when using java.net.URL or
  79.       java.net.URLConnection from an applet?
  80.   2.8 How do I prevent caching of HTTP requests?
  81.  
  82.  
  83. Advanced programming questions
  84.  
  85.   3. Advanced networking concepts
  86.  
  87.   3.1 How do I handle timeouts in my networking
  88.       applications?
  89.   3.2 How do I control the amount of time a socket will
  90.       linger before resetting?
  91.   3.3 What does the java.net.Socket.setTcpNoDelay method do,
  92.       and what is Nagle's algorithm?
  93.   3.4 How do I implement a (FTP/HTTP/Telnet/Finger/SMTP/POP
  94.       /IMAP/..../) client/server?
  95.   3.5 How do I implement PING in Java?
  96.   3.6 How can I send/receive email from Java?
  97.  
  98.   4. Remote method invocation
  99.  
  100.   4.1 What is remote method invocation?
  101.   4.2 When should I use remote method invocation?
  102.   4.3 Why can't I access RMI from C++?
  103.   4.4 Why won't my RMI implementation compile under JDK1.1?
  104.   4.5 Why won't my RMI implementation run under Java 2?
  105.  
  106.   5. Common Object Request Broker Architecture
  107.  
  108.   5.1 What is CORBA?
  109.   5.2 When should I use CORBA?
  110.   5.3 What support does Java have for CORBA?
  111.   5.4 How do I start the CORBA nameservice for Java 2?
  112.  
  113.   6. Servlets
  114.  
  115.   6.1 What are Java Servlets?
  116.   6.2 What do I need to develop servlets?
  117.   6.3 Where can I get more information on servlets?
  118.   6.4 How does servlet performance compare to applets?
  119.   6.5 How does servlet performance compare to CGI?
  120.   6.6 Should I use single-threaded, or multi-threaded
  121.       servlets?
  122.   6.7 How do I send cookies from a servlet?
  123.   6.8 How do I read browser cookies from a servlet?
  124.   6.9 How do I make cookies expire after a set time period?
  125.   6.10 Why aren't cookies stored by my servlets accessible
  126.        to my CGI scripts or ASP pages?
  127.   6.11 How can I void a cookie, and delete it from the
  128.        browser?
  129.   
  130. ------------------------------------------------------------
  131.  
  132. Overview
  133.  
  134. This document contains the answers to commonly asked network
  135. programming questions posed by Java developers. If you have
  136. a question not addressed by this document, feel free to ask.
  137. My email is jnpfaq@davidreilly.com.
  138.  
  139. Legal
  140.  
  141. This document is Copyright 1998, David Reilly. All Rights are
  142. Reserved. No unauthorized mirroring or archiving of this FAQ
  143. is permitted, other than for personal use such as offline
  144. reading. Print distribution, or distribution on CD-ROM,
  145. WWW sites (personal or commercial), or other electronic
  146. distribution is strictly prohibited without prior permission.
  147. For redistribution rights, contact jnpfaq@davidreilly.com.
  148.  
  149. This FAQ is no way connected with two books (published by
  150. Manning & O'Reilly) by the same name. Java is a trademark of
  151. Sun Microsystems, and this document is no no way connected
  152. with Sun Microsystems.
  153.  
  154. Comments
  155.  
  156. This document is by no means complete, though hopefully it is
  157. error free :-). Anyone wishing to submit a question, or provide
  158. comments, can send email to jnpfaq@davidreilly.com
  159.  
  160. Books
  161.  
  162. Most good Java books contain at least one chapter of
  163. information on networking topics. However, for the network
  164. programmer, this is invariably not enough information! A trip
  165. to your local bookstore or library should turn up a few books
  166. on the topic. If not, the following resources might help you.
  167.  
  168. Java Network Programming
  169. Author : Hughes, et al
  170. ISBNáá : 188477749X
  171.  
  172. This book is one of the best books to begin network programming
  173. in Java with. Not to be confused with an O'Reilly book of the
  174. same name, Java Network Programming covers a wide range of topics,
  175. from datagrams to sockets, from message streams and encryption to
  176. remote method invocation (RMI), CORBA, Java servlets, and a heavy
  177. dose of cryptography and security. Packed full of code, this is
  178. the ultimate reference. A second edition of this book, covering
  179. Java Platform 2, has just been released, and is highly
  180. recommended.
  181.  
  182. [more information]
  183. http://www.davidreilly.com/goto.cgi?isbn=188477749X
  184.  
  185. Java Network Programming
  186. Author : Elliotte Rusty Harold
  187. ISBNáá : 1565922271
  188. O'Reilly & Associates, in 1997 published a book by the name of 
  189. "Java Network Programming". This book received favorable reviews
  190. in online stores like Amazon for the first couple of years,
  191. but is now woefully out of date, and not really a good choice.
  192. I've flicked through the title, and it doesn't cover newer
  193. topics like CORBA, new RMI features, or the revised servlet
  194. system development kit. A second edition of this title, bringing
  195. it up to speed, is in order.
  196.  
  197. [more information]
  198. http://www.davidreilly.com/goto.cgi?isbn=1565922271
  199.  
  200. The Java Tutorial
  201. Author : Mary Campione and Kathy Walrath
  202. ISBNáá : 0201310074
  203. Published by Addison-Wesley, and available on-line from Sun, the
  204. Java Tutorial provides a great introduction to the Java language,
  205. as well as advanced material on both basic networking topics,
  206. and advanced issues, such as RMI/CORBA.
  207.  
  208. http://java.sun.com/docs/books/tutorial/
  209.  
  210.  
  211. Websites
  212.  
  213. The official source of any Java related information is Sun
  214. Microsystem's Java site, located at http://java.sun.com/.
  215. Other recommended sites include the following
  216.  
  217. Site : Java Coffee Break
  218. URL  : http://www.javacoffeebreak.com/
  219.  
  220. Features many Java networking articles about advanced
  221. networking topics, such as RMI & CORBA, as well as an
  222. introduction to networking tutorial.
  223.  
  224. Site : Java Networking FAQ
  225. URL  : http://www.io.com/~maus/jnetfaq.html
  226. The Java Networking FAQ is an older FAQ, and doesn't
  227. cover many of the newer JDK1.1 networking features.
  228. However, its still a good reference for networking
  229. information.
  230.  
  231. Site : JavaWorld 
  232. URL  : http://www.javaworld.com/
  233. JavaWorld is an online magazine, published monthly.
  234. Covers a wide variety of topics, some of which are
  235. networking related.
  236.  
  237.  
  238. Site : Jguru 
  239. URL  : http://www.jguru.com/faq/Networking
  240. Offers a collection of networking FAQs for Java.
  241.  
  242. ------------------------------------------------------------
  243.  
  244.                  Basic programming questions
  245.  
  246. 1. Socket questions
  247.  
  248.   1.1 Should I use ServerSocket or DatagramSocket in my
  249.       applications?
  250.  
  251.   DatagramSocket allows a server to accept UDP packets,
  252.   whereas ServerSocket allows an application to accept TCP
  253.   connections. It depends on the protocol you're trying to
  254.   implement. If you're creating a new protocol, and the
  255.   choice is up to you, here's a few tips :
  256.  
  257.   DatagramSockets communciate using UDP packets. These
  258.   packets don't guarantee delivery - you'll need to handle
  259.   missing packets in your client/server
  260.  
  261.   ServerSockets communicate using TCP connections. TCP
  262.   guarantees delivery, so all you need to do is have your
  263.   applications read and write using a socket's InputStream
  264.   and OutputStream.
  265.  
  266.   1.2 How do I get the IP address of a machine from its hostname?
  267.  
  268.   The InetAddress class is able to resolve IP addresses for
  269.   you. Obtain an instance of InetAddress for the machine,
  270.   and call the getHostAddress() method, which returns a
  271.   string in the xxx.xxx.xxx.xxx address form.
  272.  
  273.   InetAddress inet =
  274.   InetAddress.getByName("www.davidreilly.com");
  275.   System.out.println ("IP  : " + inet.getHostAddress());
  276.  
  277.   1.3 How do I perform a hostname lookup for an IP address?
  278.  
  279.   The InetAddress class contains a method that can return the
  280.   domain name of an IP address. You need to obtain an
  281.   InetAddress class, and then call its getHostName() method.
  282.   This will return the hostname for that IP address. Depending
  283.   on the platform, a partial or a fully qualified hostname may
  284.   be returned.
  285.  
  286.   InetAddress inet = InetAddress.getByName("209.204.220.121");
  287.   System.out.println ("Host: " + inet.getHostName());
  288.  
  289.   1.4 How can I find out who is accessing my server?
  290.  
  291.   If you're using a DatagramSocket, every packet that you
  292.   receive will contain the address and port from which it was
  293.   sent.
  294.  
  295.   DatagramPacket packet = null;
  296.  
  297.   // Receive next packet
  298.   myDatagramSocket.receive ( packet );
  299.  
  300.   // Print address + port
  301.   System.out.println ("Packet from : " + 
  302.    packet.getAddress().getHostAddress() + ':' +
  303.    packet.getPort());
  304.  
  305.   If you're using a ServerSocket, then every socket connection
  306.   you accept will contain similar information. The Socket class
  307.   has a getInetAddress() and getPort() method which will allow
  308.   you to find the same information.
  309.  
  310.   Socket mySock = myServerSocket.accept();
  311.  
  312.   // Print address + port
  313.   System.out.println ("Connection from : " + 
  314.    mySock.getInetAddress().getHostAddress() + ':' +
  315.    mySock.getPort());    
  316.  
  317.   1.5 How can I find out the current IP address for my machine?
  318.  
  319.   The InetAddress has a static method called getLocalHost() which
  320.   will return the current address of the local machine. You can
  321.   then use the getHostAddress() method to get the IP address.
  322.  
  323.   InetAddress local = InetAddress.getLocalHost();
  324.  
  325.   // Print address
  326.   System.out.println ("Local IP : " + local.getHostAddress());
  327.  
  328.   1.6 Why can't my applet connect via sockets, or bind to a local
  329.       port?
  330.  
  331.   Applets are subject to heavy security constraints when
  332.   executing under the control of a browser. Applets are unable to
  333.   access the local file-system, to bind to local ports, or to
  334.   connect to a computer via sockets other than the computer from
  335.   which the applet is loaded. While it may seem to be an annoyance
  336.   for developers, there are many good reasons why such tight
  337.   constraints are placed on applets. Applets could bind to well
  338.   known ports, and service network clients without authorization
  339.   or consent. Applets executing within firewalls could obtain
  340.   privileged information, and then send it across the network.
  341.   Applets could even be infected by viruses, such as the Java
  342.   StrangeBrew strain. Applets might become infected without an
  343.   applet author's knowledge and then send information back that
  344.   might leave hosts vulnerable to attack.
  345.  
  346.   Signed applets may be allowed greater freedom by browsers than
  347.   unsigned applets, which could be an option. In cases where an
  348.   applet must be capable of network communication, HTTP can be
  349.   used as a communication mechanism. An applet could communicate
  350.   via java.net.URLConnection with a CGI script, or a Java servlet.
  351.   This has an added advantage - applets that use the URLConnection
  352.   will be able to communicate through a firewall.
  353.  
  354.   1.7 What are socket options, and why should I use them?
  355.  
  356.   Socket options give developers greater control over how sockets
  357.   behave. Most socket behavior is controlled by the operating
  358.   system, not Java itself, but as of JDK1.1, you can control
  359.   several socket options, including SO_TIMEOUT, SO_LINGER,
  360.   TCP_NODELAY, SO_RCVBUF and SO_SNDBUF.
  361.  
  362.   These are advanced options, and many programmers may want to
  363.   ignore them. That's OK, but be aware of their existence for the
  364.   future. You might like to specify a timeout for read operations,
  365.   to control the amount of time a connection will linger for before
  366.   a reset is sent, whether Nagle's algorithm is enabled/disabled, or
  367.   the send and receive buffers for datagram sockets.
  368.  
  369.   1.8 When my client connects to my server, why does no data
  370.       come out?
  371.  
  372.   This is a common problem, made more difficult by the fact that
  373.   the fault may lie in either the client, or the server, or both.
  374.   The first step is to try and isolate the cause of the problem,
  375.   by checking whether the server is responding correctly.
  376.  
  377.   If you're writing a TCP service, then you can telnet to the port
  378.   the server uses, and check to see if it is responding to data. If
  379.   so, then the fault is more than likely in the client, and if not,
  380.   you've found your problem. A debugger can be very helpful in
  381.   tracking down the precise location of server errors. You could
  382.   try jdb, which comes with JDK, or use an IDE's debugger like
  383.   Visual J++ or Borland JBuilder.
  384.  
  385.   If your fault looks like it is in the client, then it can often
  386.   be caused by buffered I/O. If you're using a buffered stream, or a
  387.   writer (such as PrintWriter), you may need to manually flush the
  388.   data. Otherwise, it will be queued up but not sent, causing both
  389.   client and server to stall. The problem can even be intermittent,
  390.   as the buffer will flush sometimes (when it becomes full) but not
  391.   other times.
  392.  
  393.   1.9 What is the cause of a NoRouteToHost exception?
  394.  
  395.   Usually this means that there isn't an active Internet connection
  396.   through which a socket connection may take place, or that there is
  397.   a nasty little firewall in the way. Firewalls are the bane of
  398.   users and developers alike - while useful for security, they make
  399.   legitimate networking software harder to support.
  400.  
  401.   Your best option is to try using a SOCKS proxy, or to use a
  402.   different protocol, like HTTP. If you still have firewall
  403.   problems, you can manually specify a HTTP proxy server (see
  404.   section 2.4)
  405.  
  406.   This is a common problem, made more difficult by the fact that
  407.   the fault may lie in either the client, or the server, or both.
  408.   The first step is to try and isolate the cause of the problem, by
  409.   checking whether the server is responding correctly. 
  410.  
  411. 2. HTTP Questions
  412.  
  413.   2.1 How do I display a particular web page from an applet?
  414.  
  415.   An applet can instruct a web browser to load a particular
  416.   page, using the showDocument method of the
  417.   java.applet.AppletContext class. If you want to display a
  418.   web page, you first have to obtain a reference to the
  419.   current applet context.
  420.  
  421.   The following code snippet shows you how this can be done.
  422.   The show page method is capable of displaying any URL passed
  423.   to it.
  424.  
  425.   import java.net.*;
  426.   import java.awt.*;
  427.   import java.applet.*;
  428.  
  429.   public class MyApplet extends Applet
  430.   {
  431.     // Your applet code goes here
  432.  
  433.     // Show me a page
  434.     public void showPage ( String mypage )
  435.     {
  436.         URL myurl = null;
  437.  
  438.         // Create a URL object
  439.         try
  440.         {
  441.             myurl = new URL ( mypage );
  442.         }
  443.         catch (MalformedURLException e)
  444.         {
  445.             // Invalid URL
  446.         }
  447.             
  448.         // Show URL
  449.         if (myurl != null)
  450.         {
  451.             getAppletContext().showDocument (myurl);
  452.         }
  453.  
  454.     }
  455.   }
  456.  
  457.   2.2 How do I display more than one page from an applet?
  458.  
  459.   The showDocument method of the AppletContext interface is
  460.   overloaded - meaning that it can accept more than one
  461.   parameter. It can accept a second parameter, which
  462.   represents the name of the browser window that should
  463.   display a page.
  464.  
  465.   For example,
  466.  
  467.     myAppletContext.showDocument (myurl, "frame1")
  468.  
  469.   will display the document in frame1. If there exists no
  470.   window named frame1, then a brand new window will be
  471.   created.
  472.  
  473.   2.3 How can I fetch files using HTTP?
  474.  
  475.   The easiest way to fetch files using HTTP is to use the 
  476.   java.net.URL class. The openStream() method will return an
  477.   InputStream instance, from which the file contents can be
  478.   read. For added control, you can use the openConnection()
  479.   method, which will return a URLConnection object.
  480.  
  481.   Here's a brief example that demonstrates the use of the
  482.   java.net.URL.openStream() method to return the contents of a
  483.   URL specified as a command line parameter.
  484.  
  485.   import java.net.*;
  486.   import java.io.*;
  487.  
  488.   public class URLDemo
  489.   {
  490.       public static void main(String args[])
  491.       {
  492.           try
  493.           {
  494.               // Check to see that a command parameter was  entered
  495.               if (args.length != 1)
  496.               {
  497.                  // Print message, pause, then exit
  498.                  System.err.println ("Invalid command
  499.                  parameters");
  500.                  System.in.read();
  501.                  System.exit(0);
  502.               }
  503.  
  504.               // Create an URL instance
  505.               URL url = new URL(args[0]);
  506.  
  507.               // Get an input stream for reading
  508.               InputStream in = url.openStream();
  509.  
  510.               // Create a buffered input stream for efficency
  511.               BufferedInputStream bufIn = new
  512.               BufferedInputStream(in);
  513.  
  514.               // Repeat until end of file
  515.               for (;;)
  516.               {
  517.                   int data = bufIn.read();
  518.  
  519.                   // Check for EOF
  520.                   if (data == -1)
  521.                       break;
  522.                   else
  523.                       System.out.print ( (char) data);
  524.               }
  525.           }
  526.           catch (MalformedURLException mue)
  527.           {
  528.               System.err.println ("Invalid URL");
  529.           }
  530.           catch (IOException ioe)
  531.           {
  532.               System.err.println ("I/O Error - " + ioe);
  533.           }
  534.       }
  535.   }
  536.  
  537.   2.4 How do I use a proxy server for HTTP requests?
  538.  
  539.   When a Java applet under the control of a browser (such
  540.   as Netscape or Internet Explorer) fetches content via a
  541.   URLConnection, it will automatically and transparently
  542.   use the proxy settings of the browser.
  543.  
  544.   If you're writing an application, however, you'll have
  545.   to manually specify the proxy server settings. You can
  546.   do this when running a Java application, or you can write
  547.   code that will specify proxy settings automatically for
  548.   the user (providing you allow the users to customize the
  549.   settings to suit their proxy servers).
  550.  
  551.   To specify proxy settings when running an application,
  552.   use the -D parameter :
  553.  
  554.   jre -DproxySet=true -DproxyHost=myhost
  555.       -DproxyPort=myport MyApp
  556.  
  557.   Alternately, your application can maintain a configuration
  558.   file, and specify proxy settings before using a
  559.   URLConnection :
  560.  
  561.   // Modify system properties
  562.   Properties sysProperties = System.getProperties();
  563.  
  564.   // Specify proxy settings
  565.   sysProperties.put("proxyHost", "myhost");
  566.   sysProperties.put("proxyPort", "myport");
  567.   sysProperties.put("proxySet",  "true");
  568.  
  569.   2.5 What is a malformed URL, and why is it exceptional?
  570.  
  571.   When you create an instance of the java.net.URL class, its
  572.   constructor can throw a MalformedURLException. This occurs
  573.   when the URL is invalid. When it is thrown, it isn't because
  574.   the host machine is down, or the URL path points to a missing
  575.   file; a malformed URL exception is thrown when the URL
  576.   cannot be correctly parsed.
  577.  
  578.   Common mistakes include :-
  579.     * leaving out a protocol (eg "www.microsoft.com" instead
  580.       of "http://www.microsoft.com/")
  581.     * specifying an invalid protocol (eg "www://netscape.com")
  582.     * leaving out the ':' character (eg http//www.micrsoft.com/)
  583.  
  584.   MalformedURLException will not be thrown if :-
  585.     * the host name is invalid (eg 
  586.       "www.microsoft-rules-the-world.com")
  587.     * the path is invalid (eg 
  588.       "http://www.microsoft.com/company_secrets.htm")
  589.  
  590.   2.6 How do I URL encode the parameters of a CGI script?
  591.  
  592.   This is an important question, as many Java applications and
  593.   applets interact with server side applications, servlets, and
  594.   CGI scripts. Let's take a look at how URL encoding works first
  595.   though.
  596.  
  597.   A URL can be used to invoke a server side application or
  598.   script's GET method. The first part of the URL will be the name
  599.   of the server side script, followed by a question mark '?'
  600.   character. After that will come the name of each parameter,
  601.   and '=' sign to separate name from value, and a '&' character
  602.   to indicate the next parameter. Here's a fictitious example.
  603.  
  604.      http://www.yourwebhost.com/yourcgi.cgi?name=your%20name&emai
  605.      l=email@email.com
  606.  
  607.   We can't include spaces or other high/low ASCII values, so the
  608.   space character has been substituted for %20 in this example.
  609.   Java provides a URLEncoder class to do this for us - we need only
  610.   construct the URL and pass it to the URLEncoder. Here's a quick
  611.   code example to demonstrate.
  612.  
  613.   String encodedURL = "http://www.yourwebhost.com/yourcgi?name=" +
  614.      // encode as value may have spaces or other characters
  615.        URLEncoder.encode("david reilly" );
  616.  
  617.   System.out.println ("Encoded URL - " + encodedURL);
  618.  
  619.   2.7 Why is a security exception thrown when using java.net.URL
  620.       or java.net.URLConnection from an applet?
  621.  
  622.   Web browsers impose security restrictions on applets, which
  623.   prevent applets from establishing network connections to servers 
  624.   other than that from which they were loaded. Like socket
  625.   connections, HTTP connections will cause security exceptions to
  626.   be thrown.  If you absolutely, positively, have to access other
  627.   hosts (and replacing your applet with a Java servlet is
  628.   impractical), consider using a digitally signed applet.
  629.  
  630.   2.8 How do I prevent caching of HTTP requests?
  631.  
  632.   By default, caching will be enabled. You must use a URLConnection,
  633.   rather than the URL.openStream() method, and explicitly specify that
  634.   you do not want to cache the requests. This is achieved by calling
  635.   the URLConnection.setUseCaches(boolean) method with a value of false.
  636.  
  637.  
  638.                  Advanced programming questions
  639.  
  640.  
  641. 3. Advanced networking concepts
  642.  
  643.   3.1 How do I handle timeouts in my networking applications?
  644.  
  645.   If your application is written for JDK1.1 or higher, you
  646.   can use socket options to generate a timeout after a read
  647.   operation blocks for a specified length of time. This is
  648.   by far the easiest method of handling timeouts. A call to
  649.   the java.net.Socket.setSoTimeout() method allows you to
  650.   specify the maximum amount of time a Socket I/O operation
  651.   will block before throwing an InterruptedIOException. This
  652.   allows you to trap read timeouts, and handle them correctly.
  653.   For an article on the subject, see
  654.   http://www.javacoffeebreak.com/articles/network_timeouts/.
  655.  
  656.   If you're trying to handle connection timeouts, or if your
  657.   application must support earlier versions of Java, then
  658.   another option is the use of threads. Multi-threaded
  659.   applications can wait for timeouts, and then perform some
  660.   action (such as resetting a connection or notifying the
  661.   user). However, you as a programmer should avoid writing
  662.   complex multi-threaded code - particularly in your clients.
  663.   There's usually an easy way to encapsulate the complexity
  664.   of multi-threading, and provide a simple non-blocking I/O
  665.   version. An article that demonstrates this technique for
  666.   connect operations is available at
  667.   http://www.javaworld.com/jw-09-1999/jw-09-timeout.html
  668.  
  669.   3.2 How do I control the amount of time a socket will 
  670.       linger before resetting?
  671.  
  672.   When a socket wishes to terminate a connection it can
  673.   "linger", allowing unsent data to be transmitted, or it
  674.   can "reset" which means that all unsent data will be lost.
  675.   You can explicitly set a delay before a reset is sent,
  676.   giving more time for data to be read, or you can specify a
  677.   delay of zero, meaning a reset will be sent as soon as the
  678.   java.net.Socket.close() method is invoked.
  679.  
  680.   The socket option SO_LINGER controls whether a connection
  681.   will be aborted, and if so, the linger delay. Use the
  682.   java.net.Socket.setSoLinger method, which accepts as
  683.   parameters a boolean and an int. The boolean flag will
  684.   activate/deactivate the SO_LINGER option, and the int will
  685.   control the delay time.
  686.  
  687.   3.3 What does the java.net.Socket.setTcpNoDelay method do,
  688.       and what is Nagle's algorithm?
  689.  
  690.   This method controls the socket option TCP_NODELAY, which
  691.   allows applications to enable or disable Nagle's algorithm.
  692.   Nagle's algorithm (described in RFC 896), conserves
  693.   bandwidth by minimizing the number of segments that are
  694.   sent. When applications wish to decrease network latency
  695.   and increase performance, they can disable Nagle's algorithm.
  696.   Data will be sent earlier, at the cost of an increase in
  697.   bandwidth consumption.
  698.  
  699.   3.4 How do I implement a (FTP/HTTP/Telnet/Finger/SMTP/
  700.       POP/IMAP/..../) client/server?
  701.  
  702.   Your first step towards creating such systems will be
  703.   to read the relevant Request For Comments (RFCs) document.
  704.   Not sure which one? There are specific search engines,
  705.   such as http://www.rfc-editor.org/, that will allow you
  706.   to search for the name of a protocol, and to then read
  707.   relevant documents. These RFCs describe the protocol
  708.   you wish to implement.
  709.  
  710.   3.5 How do I implement PING in Java?
  711.  
  712.   Java includes support for UDP and TCP sockets. PING
  713.   requires support for the Internet Control Message Protocol
  714.   (ICMP). Your only choice (at the moment), is to use native
  715.   code, or to use java.lang.Runtime to execute an external
  716.   ping application. You won't be able to develop a 100% Pure
  717.   implementation.
  718.  
  719.   NB - A native implementation that uses the Java Native
  720.   Interface (JNI) is available for PING, in both English and
  721.   Spanish. For more details, see
  722.   http://www.geocities.com/SiliconValley/Bit/5716/ping/
  723.  
  724.  
  725.   3.6 How can I send/receive email from Java?
  726.  
  727.   You can choose to implement Simple Mail Transfer Protocol
  728.   (SMTP), to send email, and either POP or IMAP to receive
  729.   email. However, an easier alternative is to use the
  730.   JavaMail API, which provides a set of classes for mail and
  731.   messaging applications. Royalty-free implementations of the
  732.   API are now available from Sun for SMTP, POP and IMAP - and
  733.   many other mail systems are supported by third-parties. For
  734.   more information, visit the official JavaMail page, at 
  735.   http://java.sun.com/products/javamail/
  736.   
  737.  
  738. 4. Remote method invocation
  739.  
  740.   4.1 What is remote method invocation?
  741.  
  742.   Remote method invocation (RMI), is a mechanism for
  743.   invoking an object's methods, even though the object is
  744.   executing on a foreign Java Virtual Machine (JVM). RMI is
  745.   similar to remote procedure calls (RPCs), but has an added
  746.   advantage - method signatures can contain Java objects as
  747.   well as primitive data types. Even objects that a foreign
  748.   JVM has never encountered before can be used, so new tasks
  749.   and methods can be passed across a network.
  750.  
  751.   4.2 When should I use remote method invocation?
  752.  
  753.   Here's a few rules of thumb :
  754.  
  755.    * When you wish to execute code on remote systems
  756.      (distributed systems)
  757.    * When you have a network that has machines capable of
  758.      supporting JVMs on all machines you would wish to
  759.      connect to RMI
  760.    * When you don't want your RMI applications to be used
  761.      from machines that don't support JVMs, or from
  762.      applications written in C++/Ada/Cobol/Fortran/
  763.      [insert non-java lang here]
  764.  
  765.   4.3 Why can't I access RMI from C++?
  766.  
  767.   Remote method invocation allows method signatures to
  768.   contain Java objects, and C++ isn't capable of executing
  769.   Java bytecode. If your RMI system only used primitive data
  770.   types, you might be able to write a software bridge
  771.   between the two - but this isn't direct remote method
  772.   invocation. You'd be better off investigating CORBA.
  773.  
  774.   4.4 Why won't my RMI implementation compile under JDK1.1?
  775.  
  776.   Under JDK1.02, RMI implementations extend 
  777.   java.rmi.server.UnicastRemoteServer. This changed in JDK1.1 -
  778.   you should now extend java.rmi.server.UnicastRemoteObject.
  779.  
  780.   4.5 Why won't my RMI implementation run under Java 2?
  781.  
  782.   If you're running the client or server with Java 2, then you'll
  783.   need to specify a security policy file, to prevent
  784.   SecurityExceptions being thrown. This policy file will allow
  785.   your application to bind to a local port (if a service), and
  786.   to connect to remote hosts (if a client).
  787.  
  788.   The following changes should be made when running the
  789.   cilent/server :
  790.  
  791.     java -Djava.security.policy=java.policy yourserver
  792.  
  793.   You'll also need to create a policy file (if one does not
  794.   already exist). Here's a sample policy file that will allow
  795.   you to accept conections from ports higher than 1024, but
  796.   connect to all ports as a client.
  797.  
  798.     grant { 
  799.       permission java.net.SocketPermission "*:1024-65535",
  800.           "connect,accept,resolve";
  801.       permission java.net.SocketPermission "*:1-1023", 
  802.            "connect,resolve";
  803.     };
  804.  
  805. 5. Common Object Request Broker Architecture
  806.  
  807.   5.1 What is CORBA?
  808.  
  809.   CORBA stands for Common Object Request Broker Architecture.
  810.   CORBA is a mechanism that allows applications to invoke
  811.   object methods that will execute on remote systems. CORBA
  812.   isn't limited to any single platform, or language. CORBA
  813.   systems are written in C++, Ada, Java, and other
  814.   languages. This makes it more interoperable than remote
  815.   procedure calls and remote method invocation.
  816.  
  817.   5.2 When should I use CORBA?
  818.  
  819.   Here's a few rules of thumb :
  820.  
  821.    * When you wish to use services that are running on remote
  822.      machines (distributed systems)
  823.    * When you have a heterogeneous networking environment,
  824.      containing systems that aren't capable of supporting
  825.      JVMs because a port is not yet available
  826.    * When you want your applications to be accessed by other
  827.      systems written in C, C++, Ada, Cobol, and other
  828.      languages (including Java)  
  829.  
  830.   5.3 What support does Java have for CORBA?
  831.  
  832.   Third party class libraries allow you to write CORBA
  833.   application clients and services in earlier versions of
  834.   Java, but support for CORBA is also included with the
  835.   newly released Java 2 Platform. Clients and services can be
  836.   written (though an extra download of the idltojava tool
  837.   is required).
  838.  
  839.   For more information on Java IDL, see the article
  840.   "Java and CORBA - a smooth blend", available from :
  841.   http://www.javacoffeebreak.com/articles/javaidl/javaidl.html
  842.  
  843.   5.4 How do I start the CORBA nameservice for Java 2?
  844.  
  845.   The nameservice can be started by running the tnameserv
  846.   command, which should be located in your Java 2 binaries
  847.   directory. Remember however that this service will run
  848.   continuously, so you'll need to run it in a separate
  849.   console window.
  850.  
  851. 6. Java Servlets
  852.  
  853.   6.1 What are servlets?
  854.  
  855.   Servlets are server-side Java applications, as opposed to
  856.   client-side applets or standalone applications. While
  857.   servlets are compatible with many different types of servers,
  858.   typically they are used in web servers, as a replacement for
  859.   CGI scripts or Active-Server Pages (ASP).
  860.  
  861.   Java servlets offer many advantages over other forms of
  862.   server-side processing. Apart from the obvious (they are 
  863.   written in the Java programming language, a big plus after
  864.   all), servlet based applications are far easier to write
  865.   than CGI scripts. There's no need to write code for parsing
  866.   HTTP request parameters, as this code is provided by the 
  867.   javax.servlet.http package. You have access to the entire
  868.   Java API, with no networking restrictions (making servlets
  869.   far more attractive than applets). There are also performance
  870.   increases over CGI scripts, as servlets persist over time,
  871.   and do not create a new process for every connection.
  872.  
  873.   6.2 What do I need to develop servlets?
  874.  
  875.   To develop servlets, you need a basic familiarity with Java
  876.   I/O streams, HTML, and the HyperText-Transfer Protocol (HTTP).
  877.   You'll also need to download the Java Servlet Development Kit
  878.   (JSDK) which is freely available from Sun Microsystems. Finally,
  879.   you'll need a web-server that supports servlets, or a servlet
  880.   engine which augments your server's capability.
  881.  
  882.   6.3 Where can I get more information on servlets?
  883.  
  884.   Gamelan's TechFocus recently published a two-part introductory
  885.   tutorial on servlets, which I can highly recommend. For more
  886.   information see http://www.gamelan.com/journal/techworkshop/
  887.  
  888.   I also highly recommend the book, Developing Java Servlets, by
  889.   James Goodwill. The publisher is Sams, and the ISBN is 0672316005
  890.   For more information, see 
  891.   http://www.davidreilly.com/goto.cgi?isbn=0672316005  
  892.  
  893.  
  894.   6.4 How does servlet performance compare to applets?
  895.  
  896.   Client-side Java has been dogged by performance problems due to
  897.   slow loading times, older JVMs without JIT compilation, and
  898.   inefficient coding. Applets have gained a reputation of poor
  899.   performance, which often gives Java itself a bad name.
  900.   Server-side Java, however, doesn't suffer from the same
  901.   performance problems. The speed of execution is much better, as
  902.   the server administrator can install more recent JVMs (some of
  903.   which are optimized for server-side processing). The load time
  904.   is virtually instantaneous, as there is no network latency to
  905.   contend with. You're also in a better position regarding
  906.   security restrictions - servlets can establish network
  907.   connections without the sandbox problems that plague
  908.   unsigned applets.á
  909.  
  910.   6.5 How does servlet performance compare to CGI?
  911.  
  912.   Servlet performance is often far superior to CGI. Rather than
  913.   forking a new process for each request, a pool of threads can
  914.   be used to execute servlet requests. Servlets persist across
  915.   connections, so there's no need to perform initialization
  916.   tasks repeatedly. This, when coupled with a fast JVM and
  917.   servlet engine, can offer better performance than CGI.
  918.  
  919.   6.6 Should I use single-threaded, or multi-threaded
  920.       servlets?
  921.  
  922.   By default, servlets are multi-threaded. If you specifically
  923.   require a single-threaded servlet, you should implement the
  924.   javax.servlet.SingleThreadModel interface. This guarantees
  925.   that no two threads will be operating on the same instance
  926.   of the servlet, but still allows concurrent execution of
  927.   the servlet. The servlet engine will maintain a pool of
  928.   available threads, and create new instances of the servlet
  929.   as required. This can cause performance problems however,
  930.   and should be used sparingly except on low-traffic servers.
  931.  
  932.   6.7 How do I send cookies from a servlet?
  933.   
  934.   HTTP is a stateless protocol, which makes tracking user actions
  935.   difficult. One solution is to use a cookie, which is a small
  936.   piece of data sent by a web browser every time it requests a page
  937.   from a particular site. Servlets, and CGI scripts, can send cookies
  938.   when a HTTP request is made - though as always, there is no
  939.   guarantee the browser will accept it.
  940.   
  941.   Cookies are represented by the javax.servlet.http.Cookie class.
  942.   Cookie has a single constructor, which takes two strings (a key and
  943.   a value).
  944.   
  945.   // Create a new cookie
  946.   Cookie cookie = new Cookie ("counter", "1");
  947.   
  948.   Adding a cookie to a browser is easy. Cookies are sent as part of a
  949.   HTTPServletResponse, using the addCookie( Cookie ) method. You can
  950.   call this method multiple times, but remember that most browsers
  951.   impose a limit of ten cookies, and 4096 bytes of data per hostname.
  952.   
  953.   public void doGet (HttpServletRequest request,
  954.                      HttpServletResponse response)
  955.                      throws IOException
  956.   {
  957.     response.addCookie(new Cookie("cookie_name", "cookie_value"));
  958.   }
  959.   
  960.   6.8 How do I read browser cookies from a servlet?
  961.   
  962.   Reading cookies from a servlet is quite easy. You can gain access
  963.   to any cookies sent by the browser from the
  964.   javax.servlet.http.HttpServletRequest passed to the servlet's
  965.   doGet, doPost, etc methods. HttpServletResponse offers a method,
  966.   Cookies[] getCookies() which returns an array of Cookie objects.
  967.   However, if no cookies are available, this value may be null, so be
  968.   sure to check before accessing any array elements.
  969.   
  970.   // Check for cookies
  971.   Cookie[] cookie_jar = request.getCookies();
  972.  
  973.   // Check to see if any cookies exists
  974.   if (cookie_jar != null)
  975.   {
  976.     for (int i =0; i< cookies.length; i++)
  977.     {
  978.         Cookie aCookie = cookie_jar[i];
  979.         pout.println ("Name : " + aCookie.getName());
  980.         pout.println ("Value: " + aCookie.getValue());
  981.     }
  982.   }
  983.   
  984.   6.9 How do I make cookies expire after a set time period?
  985.   
  986.   Depending on how you use the data stored in a cookie, it is
  987.   sometimes a good idea to make the cookie expire. Since anyone
  988.   using the browser will have the cookie sent on their behalf, it
  989.   may appear to be a legitimate user when in actual fact it is not.
  990.   This often happens in places like Internet cafes, school or
  991.   university computing labs, or libraries. If your cookie sends
  992.   a user identifier that facilitates access to sensitive data, or
  993.   allows changes to be made (for example, a web-based email service),
  994.   then you should expire cookies after a small time period. If the
  995.   user keeps using your servlet, you always have the option of
  996.   resending the cookie with a longer duration.
  997.   
  998.   To specify an expiration time, you can use the setMaxTime(int)
  999.   method of javax.servlet.http.Cookie. It takes as a parameter the
  1000.   number of seconds before the cookie will expire. For example,
  1001.   for a five minute expiration, we would do the following :-
  1002.   
  1003.   // Create a new cookie for userID from a fictitious
  1004.   // method called getUserID
  1005.   Cookie cookie = new Cookie ("userID", getUserID());
  1006.  
  1007.   // Expire the cookie in five minutes (5 * 60)
  1008.   cookie.setMaxTime( 300 );
  1009.   
  1010.   When the cookie is sent back to the browser, using
  1011.   HttpServletResponse.addCookie(Cookie), it will only be returned
  1012.   by the browser until the expiration date occurs. If you'd
  1013.   prefer, you can also specify a negative value for setMaxTime(int),
  1014.   and the cookie will expire as soon as the browser exits. Note
  1015.   however that not everyone will shutdown their browser, and it
  1016.   might be available for minutes, hours even days. Finally,
  1017.   specifying a value of zero will expire the cookie instantly.
  1018.   
  1019.   6.10 Why aren't cookies stored by my servlets accessible to my
  1020.        CGI scripts or ASP pages?
  1021.       
  1022.   By default, cookies are accessible to every HTTP request for
  1023.   the current directory, and any subdirectories. Now on most web
  1024.   servers and servlet engines, servlets are located in a special
  1025.   directory. For example, when using servletrunner (which ships
  1026.   with the Java Servlet Development Kit), servlets must be invoked
  1027.   under the /servlet/ directory.
  1028.   
  1029.   egáhttp://webserver/servlet/servletname
  1030.   
  1031.   If you want your cookies to be accessible elsewhere, you must
  1032.   specify the root path of your webserver, using the
  1033.   javax.servlet.Cookie.setPath( String ) method.
  1034.   
  1035.   // Create a cookie for everyone to share
  1036.   Cookie myCookie = new Cookie ("counter", "1");
  1037.  
  1038.   // Set path for cookie
  1039.   myCookie.setPath( "/" );
  1040.   
  1041.   Once you've set the path, any script (for example, stored in
  1042.   /cgi-bin/) can access the cookies stored by your servlets.
  1043.  
  1044.   6.11 How can I void a cookie, and delete it from the browser?
  1045.  
  1046.   You can specify an expiration date, using the setMaxTime(int)
  1047.   method of javax.servlet.http.Cookie. Specifying a expiration
  1048.   time of zero will void the cookie, and delete it from the browser.
  1049.  
  1050.    // Expire the cookie immediately
  1051.    cookie.setMaxTime( 0 );
  1052.  
  1053.    // Send cookie back to the browser to void it
  1054.    response.addCookie(cookie);
  1055.  
  1056. ------------------------------------------------------------
  1057. Copyright 1998, 1999 David Reilly. All Rights Reserved.
  1058.