JavaEnterprise JavaJava and Internet Programming: Introduction

Java and Internet Programming: Introduction

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.


This article is part one of a three-part series on writing Java programs that use and implement Internet services. In this part, I cover the tools and resources you will need, the protocols that your programs will use, the basics of sockets, and a very simple client program.

Tools and resources

There are actually only a couple of tools that you will need to write Java programs for the Internet. They are:

  • Java Development Kit (JDK), any version
  • Your favorite text editor.

Access to a Unix server (particularly one that is not secured) will make doing some things easier and more interesting, but it is not necessary. Also, having two PCs on a LAN can be helpful, but that is not necessary either. All the example programs for this series of articles can be run on a standalone PC.

Protocols

Programs that use or implement Internet services communicate with each other according to rules defined by one or more of the Net protocols. There are many of these protocols, but those that form the foundation for all the others are Internet Protocol (IP), Transport Control Protocol (TCP), and User Datagram Protocol (UDP).

IP is the lowest-level protocol. It defines the format and rules for the transmission of data in packets called datagrams. I am not going to go into any detail on this protocol, because one cannot write programs in Java that use it directly. Its primary importance is that it is the base protocol.

TCP is built on top of IP (which is where we get the common abbreviation TCP/IP). It defines the format and rules for the transport of packets from program to program on the Internet and provides mechanisms for acknowledging the delivery of IP packets, for requesting re-transmission of lost packets, and for assembling received packets in the order in which they were sent.

UDP is an unreliable counterpart to TCP. It does not guarantee packet delivery, nor does it provide packet sequencing and re-transmission. This may not seem very useful, but UDP has less overhead than TCP and is often faster.

Ports

When opening a socket, both an Internet address and a port must be specified. The port is an integer in the range 1 to 65535. If you think of the Internet address as a street address, then the port number is like an apartment number.

Here is a list of common Internet protocols and the port numbers associated with them [ref. 2]:

SERVICE/PROTOCOL PORT DESCRIPTION
echo 7 Used to verify that two machines can connect by having one echo back the other’s data.*
daytime 13 Provides an ASCII representation of the current time on the server.*
ftp 20/21 Used for file transfers. Port 21 is used for commands; port 20 is used for data.
telnet 23 Used for interactive, remote, command-line sessions.
smtp 25 Simple Mail Transfer Protocol, which is used to send email between machines.
whois 43 Simple directory service for network administrators.
finger 79 Used to get information about one or more users on the host machine.
http 80 HyperText Transfer Protocol, the underlying protocol of the World Wide Web.
pop3 110 Post Office Protocol Version 3, which is used to transfer e-mail from a host (e-mail server) to an e-mail client.
nntp 119 Network News Transfer Protocol, used to disseminate Usenet news.

*These protocols have both TCP and UDP implementations.

Sockets

Sockets are endpoints for communication between two machines [ref. 1], and subsequently between programs that use Internet protocols. Basically, they work like any other type of I/O object. You open them, read and/or write data, then close them when you are done.

In the Java API, sockets are provided via the classes in the java.net package. There are many classes in this package, to provide various levels of abstraction for the programmer, but the key classes are Socket, ServerSocket, DatagramSocket, DatagramPacket, and InetAddress. Here’s a brief synopsis of each:

CLASS DESCRIPTION
Socket Communication endpoint used by a client to connect to a server using TCP.
ServerSocket Communication endpoint on which a server accepts connections from clients.
DatagramSocket Socket for sending and receiving UDP packets.
DatagramPacket Represents a UDP packet.
InetAddress Represents an Internet address.

Simple client

By this point you are probably wondering how all the information I have presented so far can get you to writing internet programs in Java. So, let’s take a look at a very simple TCP client.

Listing 1. Here is the code for daytime.java, a simple program that uses the daytime protocol to get the date & time from a given host.

  Listing 1
HttpSessionExample.java
by David Reilly.

 

// Import I/O & servlet packages
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HttpSessionExample extends javax.servlet.http.HttpServlet
{
// Implementation of GET request
public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException
{
// Assign a content type
response.setContentType( "text/html" );

// Prevent caching of server-side responses
response.setHeader( "Cache-Control" , "no-cache" );

// Create a stream for writing HTML output
PrintStream pout = new PrintStream (response.getOutputStream());

// Get the user session, and create one if one doesn't already exist
HttpSession userSession = request.getSession(true);

// Check for presence of state data in userSession
String background = (String) userSession.getValue("background");
String foreground = (String) userSession.getValue("foreground");

if (background == null)
{
// No background stored - place default value in session
background = getDefaultBackground();
userSession.putValue("background", background);
}
if (foreground == null)
{
// No foreground stored - place default value in session
foreground = getDefaultForeground();
userSession.putValue("foreground", foreground);
}

// Next, check for a change in parameter from FORM
if ( request.getParameter("background") != null)
{
background = request.getParameter("background");
userSession.putValue ("background", background);
}
if ( request.getParameter("foreground") != null)
{
foreground = request.getParameter("foreground");
userSession.putValue ("foreground", foreground);
}

pout.println ("<HTML><HEAD><TITLE>HttpSessionExample</TITLE></HEAD>");
pout.println ("<BODY BGCOLOR='" + background + "' TEXT='" + foreground + "'>");
pout.println ("This is an example of a servlet that uses HttpSession to store state info <p>n");

// Print form
pout.println ("<form action='" + response.encodeUrl(request.getRequestURI()) + "' method=get>n");
pout.println ("Background : <input type=text name=background value='" + background + "'><br>n");
pout.println ("Foreground : <input type=text name=foreground value='" + foreground + "'><br>n");
pout.println ("<input type=submit>");
pout.println ("</form>");

pout.println ("<a href='" + response.encodeUrl ( request.getRequestURI() ) + "'>
Hyperlink example of URL rewriting</a> - not supported by all servers");<!--Broken Link? -->
pout.flush();

}

// Implemention of POST request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
// Pass to doGet
doGet(request,response);
}

public String getDefaultBackground() { return "white"; }
public String getDefaultForeground() { return "black"; }
}

Here is the algorithm:

  1. Get the host from the command-line. If it's blank, print an error message and exit.
  2. Get the host's IP address.
  3. Open a socket to connect to the host.
  4. Set the socket I/O timeout to 5 seconds. (This is an optional step, but the default timeout may be longer than you wish the program to wait for a response from the host.)
  5. Get a reference to the socket's input stream.
  6. Read a line from the input stream. (Note that the
    readLine()
    method blocks until either input is received or a timeout occurs.)

  7. Print the data that was received.
  8. Close the socket and exit.

When you run the Daytime program (included in the zip file linked below), you must specify the host machine (by IP or name) from which to get the date & time. If you have access to an unsecured Unix server, give it a try. If you want to run the program local, in one shell (an "MS-DOS Prompt" window on Windows) run DaytimeServer (included in the zip file linked below), then in another shell run Daytime and specify "localhost" as the host.

Ping

Some ambitious readers may want to try writing a ping program in Java. It seems like it should be a simple program, but unfortunately it's not. Ping uses the Internet Control Message Protocol (ICMP), which is treated like a high-level protocol but is a actually just a part of IP. To send ICMP messages, you have to be able to directly manipulate the IP header, which requires using what are called "raw sockets" (ICMP sockets). The Java API doesn't support raw sockets, so you would have to implement them in C/C++ as native code.

Summary

In this article, I have presented the basics of Internet protocols, ports, and sockets, and have shown you a very simple Java program that uses the Daytime protocol to get the date & time from a host machine. Hopefully, this information will help you take a solid first step toward writing your own Internet programs in Java. In the next part of this series, I'll show you some more client programs, some simple server programs, and how to use UDP.

Related links

  1. Internet RFCs, STDs, FYIs, etc.

References

  1. Java Platform 1.2 API Specification. Copyright 1993-1998 Sun Microsystems, Inc.
  2. Java Network Programming. Harold, Elliotte Rusty. Copyright 1997 O'Reilly & Associates, Inc.

About the author

Thornton Rose is a contract software developer in Atlanta, Ga. Thornton can be reached via e-mail at trose@avana.net.


Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories