Trail: Custom Networking
The Java platform is highly regarded in part because of its suitability for writing programs that use and interact with the resources on the Internet and the World Wide Web. In fact, Java-compatible browsers use this ability of the Java platform to the extreme to transport and run applets over the Internet.
This trail walks you through the complexities of writing Java applications and applets that can be used on the Internet.
Overview of Networking has two sections. The first describes the networking capabilities of the Java platform that you may already be using without realizing that you are using the network. The second provides a brief overview of networking to familiarize you with terms and concepts that you should understand before reading how to use URLs, sockets, and datagrams.
Working With URLs discusses how your Java programs can use URLs to access information on the Internet. A URL (Uniform Resource Locator) is the address of a resource on the Internet. Your Java programs can use URLs to connect to and retrieve information over a network. This lesson provides a more complete definition of a URL and shows you how to create and parse a URL, how to open a connection to a URL, and how to read from and write to that connection.
All About Sockets explains how to use sockets so that your programs can communicate with other programs on the network. A socket is one endpoint of a two-way communication link between two programs running on the network. This lesson shows you how a client can connect to a standard server, the Echo server, and communicate with it via a socket. It then walks you through the details of a complete client/server example, which shows you how to implement both the client side and the server side of a client/server pair.
All About Datagrams takes you step by step through a simple client/server example that uses datagrams to communicate. It then challenges you to rewrite the example using multicast socket instead.
Programmatic Access to Network Parameters explains why you might want to access network interface parameters and how to do so. It gives examples of how to list all the IP addresses assigned to the machine as well as other useful information such as whether the interface is running.
Working With Cookies discusses how cookies are used to create a session between a client and server, and how you can take advantage of cookies in your HTTP URL connections.
Note that communications over the network are subject to approval by the current security manager. The Security Manager describes what a security manager is and how it impacts your applications. For general information about the security features provided by the JDK, refer to Security Features in Java SE .
The example programs in the following lessons that cover URLs, sockets, and datagrams are standalone applications, which, by default, have no security manager. If you convert these applications to applets, they may be unable to communicate over the network, depending on the browser or viewer in which they are running. See What Applets Can and Cannot Do for information about the security restrictions placed on applets.
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:
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
// 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 («
pout.println («»);
pout.println («This is an example of a servlet that uses HttpSession to store state info
n»);
// Print form
pout.println («
«);
pout.println (»
Hyperlink example of URL rewriting — not supported by all servers»);
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"; >
>
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
References
- Java Platform 1.2 API Specification. Copyright 1993-1998 Sun Microsystems, Inc.
- 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.