Java Network Programming FAQ

---
From: dodo@fan.net.au (David Reilly)
Newsgroups: comp.lang.java.programmer,comp.answers,news.answers
Subject: Java Network Programming FAQ
Supersedes: <computer-lang/java/network-programming_920036934@rtfm.mit.edu>
Followup-To: poster
Date: 29 Mar 1999 14:07:24 GMT
Organization: none
Expires: 12 May 1999 13:56:05 GMT
Message-ID: <computer-lang/java/network-programming_922715765@rtfm.mit.edu>
Summary: This document answers frequently asked questions about Java
         Network Programming
X-Last-Updated: 1999/03/09

Archive-name: computer-lang/java/network-programming
Posting-Frequency: monthly
Last-modified: March 10, 1999
Copyright: Copyright 1998, David Reilly. All Rights Reserved.
Maintainer: David Reilly (dodo@fan.net.au)
URL: http://www.davidreilly.com/java/java_network_programming/

Java Network Programming FAQ.
Copyright 1998, 1999 David Reilly. All Rights Reserved.
------------------------------------------------------------

Last modification date : March 10, 1999

This document contains the answers to commonly asked network
programming questions posed by Java developers. Copies of
this document mirrored at other sites may be out of date,
please ensure that you're looking at a current version. The
latest version of this document can be found at
http://www.davidreilly.com/java/java_network_programming/

------------------------------------------------------------

Table of contents

Overview
  Legal
  Comments
  Books
  Websites

Basic programming questions

  1. Socket Questions

  1.1 Should I use ServerSocket or DatagramSocket in my
      applications?
  1.2 How do I get the IP address of a machine from its
      hostname?
  1.3 How do I perform a hostname lookup for an IP address?
  1.4 How can I find out who is accessing my server?
  1.5 How can I find out the current IP address for my
      machine?
  1.6 Why can't my applet connect via sockets, or bind to a
      local port?
  1.7 What are socket options, and why should I use them?

  2. HTTP Questions

  2.1 How do I display a particular web page from an applet?
  2.2 How do I display more than one page from an applet?
  2.3 How can I fetch files using HTTP?
  2.4 How do I use a proxy server for HTTP requests?
  2.5 What is a malformed URL, and why is it exceptional?
  2.6 How do I URL encode the parameters of a CGI script?

Advanced programming questions

  3. Advanced networking concepts

  3.1 How do I handle timeouts in my networking
      applications?
  3.2 How do I control the amount of time a socket will
      linger before resetting?
  3.3 What does the java.net.Socket.setTcpNoDelay method do,
      and what is Nagle's algorithm?
  3.4 How do I implement a (FTP/HTTP/Telnet/Finger/SMTP/POP
      /IMAP/..../) client/server?
  3.5 How do I implement PING in Java?
  3.6 How can I send/receive email from Java?

  4. Remote method invocation

  4.1 What is remote method invocation?
  4.2 When should I use remote method invocation?
  4.3 Why can't I access RMI from C++?
  4.4 Why won't my RMI implementation compile under JDK1.1?
  4.5 Why won't my RMI implementation run under JDK1.2?

  5. Common Object Request Broker Architecture

  5.1 What is CORBA?
  5.2 When should I use CORBA?
  5.3 What support does Java have for CORBA?

------------------------------------------------------------

Overview

This document contains the answers to commonly asked network
programming questions posed by Java developers. If you have
a question not addressed by this document, feel free to ask.
My email is jnpfaq@davidreilly.com.

Legal

This document is Copyright 1998, David Reilly. All Rights are
Reserved. No unauthorized mirroring or archiving of this FAQ
is permitted, other than for personal use such as offline
reading. Print distribution, or distribution on CD-ROM,
WWW sites (personal or commercial), or other electronic
distribution other than USENET archives is strictly
prohibited without prior permission. For redistribution
rights, contact jnpfaq@davidreilly.com.

This FAQ is no way connected with two books (published by
Manning & O'Reilly) by the same name. Java is a trademark of
Sun Microsystems, and this document is no no way connected
with Sun Microsystems.

Comments

This document is by no means complete, though hopefully it is
error free. Anyone wishing to submit a question, or provide
comments, can send email to jnpfaq@davidreilly.com

Books

Most good Java books contain at least one chapter of
information on networking topics. However, for the network
programmer, this is invariably not enough information! A trip
to your local bookstore or library should turn up a few books
on the topic. If not, the following resources might help you.

Java Network Programming
Author : Hughes, et al
ISBN   : 0138412065
This book is one of the best books to begin network programming
in Java with. Not to be confused with an O'Reilly book of the
same name, Java Network Programming covers a wide range of
topics, from datagrams to sockets, from message streams and
encryption to remote method invocation (RMI) and a little CORBA.

Note - A second edition of this book is scheduled for release soon!

Java Network Programming
Author : Elliotte Rusty Harold
ISBN   : 1565922271
O'Reilly & Associates, has also published a book by the name of
"Java Network Programming". In all honesty, I've never read it,
but it has received favourable reviews, and should be a good
reference.

The Java Tutorial
Author : Mary Campione and Kathy Walrath
ISBN   : 0201310074
Published by Addison-Wesley, and available on-line from Sun, the
Java Tutorial provides a great introduction to the Java language,
as well as advanced material on both basic networking topics,
and advanced issues, such as RMI/CORBA.

http://java.sun.com/docs/books/tutorial/


Websites

The official source of any Java related information is Sun
Microsystem's Java site, located at http://java.sun.com/.
Other recommended sites include the following

Site : Java Coffee Break
URL  : http://www.davidreilly.com/jcb/

Features many Java networking articles about advanced
networking topics, such as RMI & CORBA, as well as an
introduction to networking tutorial.

Site : Java Networking FAQ
URL  : http://www.io.com/~maus/jnetfaq.html
The Java Networking FAQ is an older FAQ, and doesn't
cover many of the newer JDK1.1 networking features.
However, its still a good reference for networking
information.

Site : JavaWorld
URL  : http://www.javaworld.com/
JavaWorld is an online magazine, published monthly.
Covers a wide variety of topics, some of which are
networking related.

------------------------------------------------------------

                 Basic programming questions

1. Socket questions

  1.1 Should I use ServerSocket or DatagramSocket in my
      applications?

  DatagramSocket allows a server to accept UDP packets,
  whereas ServerSocket allows an application to accept TCP
  connections. It depends on the protocol you're trying to
  implement. If you're creating a new protocol, and the
  choice is up to you, here's a few tips :

  DatagramSockets communciate using UDP packets. These
  packets don't guarantee delivery - you'll need to handle
  missing packets in your client/server

  ServerSockets communicate using TCP connections. TCP
  guarantees delivery, so all you need to do is have your
  applications read and write using a socket's InputStream
  and OutputStream.

  1.2 How do I get the IP address of a machine from its hostname?

  The InetAddress class is able to resolve IP addresses for
  you. Obtain an instance of InetAddress for the machine,
  and call the getHostAddress() method, which returns a
  string in the xxx.xxx.xxx.xxx address form.

  InetAddress inet = InetAddress.getByName("www.davidreilly.com");
  System.out.println ("IP  : " + inet.getHostAddress());

  1.3 How do I perform a hostname lookup for an IP address?

  The InetAddress class contains a method that can return the
  domain name of an IP address. You need to obtain an
  InetAddress class, and then call its getHostName() method.
  This will return the hostname for that IP address. Depending
  on the platform, a partial or a fully qualified hostname may
  be returned.

  InetAddress inet = InetAddress.getByName("209.204.220.121");
  System.out.println ("Host: " + inet.getHostName());

  1.4 How can I find out who is accessing my server?

  If you're using a DatagramSocket, every packet that you
  receive will contain the address and port from which it was
  sent.

  DatagramPacket packet = null;

  // Receive next packet
  myDatagramSocket.receive ( packet );

  // Print address + port
  System.out.println ("Packet from : " +
   packet.getAddress().getHostAddress() + ':' + packet.getPort());

  If you're using a ServerSocket, then every socket connection
  you accept will contain similar information. The Socket class
  has a getInetAddress() and getPort() method which will allow
  you to find the same information.

  Socket mySock = myServerSocket.accept();

  // Print address + port
  System.out.println ("Connection from : " +
   mySock.getInetAddress().getHostAddress() + ':' + mySock.getPort());

  1.5 How can I find out the current IP address for my machine?

  The InetAddress has a static method called getLocalHost() which
  will return the current address of the local machine. You can
  then use the getHostAddress() method to get the IP address.

  InetAddress local = InetAddress.getLocalHost();

  // Print address
  System.out.println ("Local IP : " + local.getHostAddress());

  1.6 Why can't my applet connect via sockets, or bind to a local
      port?

  Applets are subject to heavy security constraints when
  executing under the control of a browser. Applets are unable to
  access the local file-system, to bind to local ports, or to
  connect to a computer via sockets other than the computer from
  which the applet is loaded. While it may seem to be an annoyance
  for developers, there are many good reasons why such tight
  constraints are placed on applets. Applets could bind to well
  known ports, and service network clients without authorization
  or consent. Applets executing within firewalls could obtain
  privileged information, and then send it across the network.
  Applets could even be infected by viruses, such as the Java
  StrangeBrew strain. Applets might become infected without an
  applet author's knowledge and then send information back that
  might leave hosts vulnerable to attack.

  Signed applets may be allowed greater freedom by browsers than
  unsigned applets, which could be an option. In cases where an
  applet must be capable of network communication, HTTP can be
  used as a communication mechanism. An applet could communicate
  via java.net.URLConnection with a CGI script, or a Java servlet.
  This has an added advantage - applets that use the URLConnection
  will be able to communicate through a firewall.

  1.7 What are socket options, and why should I use them?

  Socket options give developers greater control over how sockets
  behave. Most socket behavior is controlled by the operating
  system, not Java itself, but as of JDK1.1, you can control
  several socket options, including SO_TIMEOUT, SO_LINGER,
  TCP_NODELAY, SO_RCVBUF and SO_SNDBUF.

  These are advanced options, and many programmers may want to
  ignore them. That's OK, but be aware of their existence for the
  future. You might like to specify a timeout for read operations,
  to control the amount of time a connection will linger for before
  a reset is sent, whether Nagle's algorithm is enabled/disabled, or
  the send and receive buffers for datagram sockets.


2. HTTP Questions

  2.1 How do I display a particular web page from an applet?

  An applet can instruct a web browser to load a particular
  page, using the showDocument method of the
  java.applet.AppletContext class. If you want to display a
  web page, you first have to obtain a reference to the
  current applet context.

  The following code snippet shows you how this can be done.
  The show page method is capable of displaying any URL passed
  to it.

  import java.net.*;
  import java.awt.*;
  import java.applet.*;

  public class MyApplet extends Applet
  {
 // Your applet code goes here

 // Show me a page
 public void showPage ( String mypage )
 {
  URL myurl = null;

  // Create a URL object
  try
  {
   myurl = new URL ( mypage );
  }
  catch (MalformedURLException e)
  {
   // Invalid URL
  }

  // Show URL
  if (myurl != null)
  {
   getAppletContext().showDocument (myurl);
  }

 }
  }

  2.2 How do I display more than one page from an applet?

  The showDocument method of the AppletContext interface is
  overloaded - meaning that it can accept more than one
  parameter. It can accept a second parameter, which
  represents the name of the browser window that should
  display a page.

  For example,

    myAppletContext.showDocument (myurl, "frame1")

  will display the document in frame1. If there exists no
  window named frame1, then a brand new window will be
  created.

  2.3 How can I fetch files using HTTP?

  The easiest way to fetch files using HTTP is to use the
  java.net.URL class. The openStream() method will return an
  InputStream instance, from which the file contents can be
  read. For added control, you can use the openConnection()
  method, which will return a URLConnection object.

  Here's a brief example that demonstrates the use of the
  java.net.URL.openStream() method to return the contents of a
  URL specified as a command line parameter.

  import java.net.*;
  import java.io.*;

  public class URLDemo
  {
      public static void main(String args[])
      {
          try
          {
              // Check to see that a command parameter was entered
              if (args.length != 1)
              {
                 // Print message, pause, then exit
                 System.err.println ("Invalid command parameters");
                 System.in.read();
                 System.exit(0);
              }

              // Create an URL instance
              URL url = new URL(args[0]);

              // Get an input stream for reading
              InputStream in = url.openStream();

              // Create a buffered input stream for efficency
              BufferedInputStream bufIn = new BufferedInputStream(in);

              // Repeat until end of file
              for (;;)
              {
                  int data = bufIn.read();

                  // Check for EOF
                  if (data == -1)
                      break;
                  else
                      System.out.print ( (char) data);
              }
          }
          catch (MalformedURLException mue)
          {
              System.err.println ("Invalid URL");
          }
          catch (IOException ioe)
          {
              System.err.println ("I/O Error - " + ioe);
          }
      }
  }

  2.4 How do I use a proxy server for HTTP requests?

  When a Java applet under the control of a browser (such
  as Netscape or Internet Explorer) fetches content via a
  URLConnection, it will automatically and transparently
  use the proxy settings of the browser.

  If you're writing an application, however, you'll have
  to manually specify the proxy server settings. You can
  do this when running a Java application, or you can write
  code that will specify proxy settings automatically for
  the user (providing you allow the users to customize the
  settings to suit their proxy servers).

  To specify proxy settings when running an application,
  use the -D parameter :

  jre -DproxySet=true -DproxyHost=myhost
      -DproxyPort=myport MyApp

  Alternately, your application can maintain a configuration
  file, and specify proxy settings before using a
  URLConnection :

  // Modify system properties
  Properties sysProperties = System.getProperties();

  // Specify proxy settings
  sysProperties.put("proxyHost", "myhost");
  sysProperties.put("proxyPort", "myport");
  sysProperties.put("proxySet",  "true");

  2.5 What is a malformed URL, and why is it exceptional?

  When you create an instance of the java.net.URL class, its
  constructor can throw a MalformedURLException. This occurs
  when the URL is invalid. When it is thrown, it isn't because
  the host machine is down, or the URL path points to a missing
  file; a malformed URL exception is thrown when the URL
  cannot be correctly parsed.

  Common mistakes include :-
    * leaving out a protocol (eg "www.microsoft.com" instead
      of "http://www.microsoft.com/")
    * specifying an invalid protocol (eg "www://netscape.com")
    * leaving out the ':' character (eg http//www.micrsoft.com/)

  MalformedURLException will not be thrown if :-
    * the host name is invalid (eg
      "www.microsoft-rules-the-world.com")
    * the path is invalid (eg
      "http://www.microsoft.com/company_secrets.htm")

  2.6 How do I URL encode the parameters of a CGI script?

  This is an important question, as many Java applications and
  applets interact with server side applications, servlets, and CGI
  scripts. Let's take a look at how URL encoding works first
  though.

  A URL can be used to invoke a server side application or script's
  GET method. The first part of the URL will be the name of the
  server side script, followed by a question mark '?' character.
  After that will come the name of each parameter, and '=' sign to
  separate name from value, and a '&' character to indicate the next
  parameter. Here's a fictitious example.

     http://www.yourwebhost.com/yourcgi.cgi?name=your%20name&email=
          email@email.com

  We can't include spaces or other high/low ASCII values, so the
  space character has been substituted for %20 in this example. Java
  provides a URLEncoder class to do this for us - we need only
  construct the URL and pass it to the URLEncoder. Here's a quick
  code example to demonstrate.

  String encodedURL = URLEncoder.encode
     ( "http://www.yourwebhost.com/yourcgi.cgi?name=your name" );
  System.out.println ("Encoded URL - " + encodedURL);


                 Advanced programming questions


3. Advanced networking concepts

  3.1 How do I handle timeouts in my networking applications?

  If your application is written for JDK1.1 or higher, you
  can use socket options to generate a timeout after a read
  operation blocks for a specified length of time. This is
  by far the easiest method of handling timeouts. A call to
  the java.net.Socket.setSoTimeout() method allows you to
  specify the maximum amount of time a Socket I/O operation
  will block before throwing an InterruptedIOException. This
  allows you to trap timeouts, and handle them correctly.

  If your application must support earlier versions of Java,
  then another option is the use of threads. Multi-threaded
  applications can wait for timeouts, and then perform some
  action (such as resetting a connection or notifying the
  user). For more information on this topic, see "Dealing
  with network timeouts in Java", Java Developers Journal
  Volume 3, Issue 5.

  3.2 How do I control the amount of time a socket will
      linger before resetting?

  When a socket wishes to terminate a connection it can
  "linger", allowing unsent data to be transmitted, or it
  can "reset" which means that all unsent data will be lost.
  You can explicitly set a delay before a reset is sent,
  giving more time for data to be read, or you can specify a
  delay of zero, meaning a reset will be sent as soon as the
  java.net.Socket.close() method is invoked.

  The socket option SO_LINGER controls whether a connection
  will be aborted, and if so, the linger delay. Use the
  java.net.Socket.setSoLinger method, which accepts as
  parameters a boolean and an int. The boolean flag will
  activate/deactivate the SO_LINGER option, and the int will
  control the delay time.

  3.3 What does the java.net.Socket.setTcpNoDelay method do,
      and what is Nagle's algorithm?

  This method controls the socket option TCP_NODELAY, which
  allows applications to enable or disable Nagle's algorithm.
  Nagle's algorithm (described in RFC 896), conserves
  bandwidth by minimizing the number of segments that are
  sent. When applications wish to decrease network latency
  and increase performance, they can disable Nagle's algorithm.
  Data will be sent earlier, at the cost of an increase in
  bandwidth consumption.

  3.4 How do I implement a (FTP/HTTP/Telnet/Finger/SMTP/
      POP/IMAP/..../) client/server?

  Your first step towards creating such systems will be
  to read the relevant Request For Comments (RFCs) document.
  Not sure which one? There are specific search engines,
  such as http://www.rfc-editor.org/, that will allow you
  to search for the name of a protocol, and to then read
  relevant documents. These RFCs describe the protocol
  you wish to implement.

  3.5 How do I implement PING in Java?

  Java includes support for UDP and TCP sockets. PING
  requires support for the Internet Control Message Protocol
  (ICMP). Your only choice (at the moment), is to use native
  code, or to use java.lang.Runtime to execute an external
  ping application. You won't be able to develop a 100% Pure
  implementation.

  3.6 How can I send/receive email from Java?

  You can choose to implement Simple Mail Transfer Protocol
  (SMTP), to send email, and either POP or IMAP to receive
  email. However, an easier alternative is to use the
  JavaMail API, which provides a set of classes for mail and
  messaging applications. Royalty-free implementations of the
  API are now available from Sun for SMTP, POP and IMAP - and
  many other mail systems are supported by third-parties. For
  more information, visit the official JavaMail page, at
  http://java.sun.com/products/javamail/


4. Remote method invocation

  4.1 What is remote method invocation?

  Remote method invocation (RMI), is a mechanism for
  invoking an object's methods, even though the object is
  executing on a foreign Java Virtual Machine (JVM). RMI is
  similar to remote procedure calls (RPCs), but has an added
  advantage - method signatures can contain Java objects as
  well as primitive data types. Even objects that a foreign
  JVM has never encountered before can be used, so new tasks
  and methods can be passed across a network.

  4.2 When should I use remote method invocation?

  Here's a few rules of thumb :

   * When you wish to execute code on remote systems
     (distributed systems)
   * When you have a network that has machines capable of
     supporting JVMs on all machines you would wish to
     connect to RMI
   * When you don't want your RMI applications to be used
     from machines that don't support JVMs, or from
     applications written in C++/Ada/Cobol/Fortran/
     [insert non-java lang here]

  4.3 Why can't I access RMI from C++?

  Remote method invocation allows method signatures to
  contain Java objects, and C++ isn't capable of executing
  Java bytecode. If your RMI system only used primitive data
  types, you might be able to write a software bridge
  between the two - but this isn't direct remote method
  invocation. You'd be better off investigating CORBA.

  4.4 Why won't my RMI implementation compile under JDK1.1?

  Under JDK1.02, RMI implementations extend
  java.rmi.server.UnicastRemoteServer. This changed in JDK1.1 -
  you should now extend java.rmi.server.UnicastRemoteObject.

  4.5 Why won't my RMI implementation run under JDK1.2?

  If you're running the client or server with JDK1.2, then you'll
  need to specify a security policy file, to prevent
  SecurityExceptions being thrown. This policy file will allow
  your application to bind to a local port (if a service), and
  to connect to remote hosts (if a client).

  The following changes should be made when running the cilent/server :

    java -Djava.security.policy=java.policy yourserver

  You'll also need to create a policy file (if one does not
  already exist). Here's a sample policy file that will allow
  you to accept conections from ports higher than 1024, but
  connect to all ports as a client.

    grant {
      permission java.net.SocketPermission "*:1024-65535",
          "connect,accept,resolve";
      permission java.net.SocketPermission "*:1-1023",
           "connect,resolve";
    };

5. Common Object Request Broker Architecture

  5.1 What is CORBA?

  CORBA stands for Common Object Request Broker Architecture.
  CORBA is a mechanism that allows applications to invoke
  object methods that will execute on remote systems. CORBA
  isn't limited to any single platform, or language. CORBA
  systems are written in C++, Ada, Java, and other
  languages. This makes it more interoperable than remote
  procedure calls and remote method invocation.

  5.2 When should I use CORBA?

  Here's a few rules of thumb :

   * When you wish to use services that are running on remote
     machines (distributed systems)
   * When you have a heterogeneous networking environment,
     containing systems that aren't capable of supporting
     JVMs because a port is not yet available
   * When you want your applications to be accessed by other
     systems written in C, C++, Ada, Cobol, and other
     languages (including Java)

  5.3 What support does Java have for CORBA?

  Third party class libraries allow you to write CORBA
  application clients and services in earlier versions of
  Java, but support for CORBA is also included with the
  newly released JDK1.2. Clients and services can be written
  (though an extra download of the idltojava tool is required).

  For more information on Java IDL, see the article
  "Java and CORBA - a smooth blend", available from :
  http://www.davidreilly.com/jcb/articles/javaidl/javaidl.html

------------------------------------------------------------
Copyright 1998, 1999 David Reilly. All Rights Reserved.


------------------------------------------------
[ By Archive-name | By Author | By Category | By Newsgroup ]
[ Home | Latest Updates | Archive Stats | Search | Usenet References | Help ]

------------------------------------------------

Send corrections/additions to the FAQ Maintainer:
dodo@fan.net.au (David Reilly)

Last Update April 22 1999 @ 02:10 AM

faq-admin@faqs.org