JavaEnterprise JavaJava Internet Programming: Level 2

Java Internet Programming: Level 2

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


This is part two of a three part series on writing Java programs that use and implement Internet services. In part one (see
Java and Internet Programming: Introduction
) , I covered protocols, sockets, and ports, and showed a simple client program. In this part, I show you some more client programs, some server programs, and the basics of using UDP.

Tools

The tools that you will need are:

  • The Java Development Kit (JDK)
  • Your favorite text editor.

Also, you will need access to a Simple Mail Transfer Protocol (SMTP) server. Most likely, you can use the mail server at your Internet service provider (ISP), your company, or your school.

Daytime too

Daytime, shown in
Listing 1
, is the simple client program that was shown in part one of this series. It is a program that uses TCP and the daytime protocol to get the date and time from a daytime server. UdpDaytime, shown in
Listing 2
, is an implementation of Daytime that uses Universal Datagram Protocol (UDP) instead of TCP.

Here is the algorithm for UdpDaytime:

  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. Create a datagram (UDP) socket.
  4. Create a datagram packet to send to the host and one to receive from the host.
  5. Set the socket I/O timeout to 5 seconds.
  6. Send the outgoing packet to the host.
  7. Receive the packet that comes back from the host.
  8. Print the data that was received.
  9. Close the socket and exit.

Notice the following differences between the UDP implementation of the daytime program and the TCP implementation:

  1. In the UDP program, you don’t have to specify a host and port when you open a datagram socket. Those are specified in the datagram packet that is sent out.
  2. With UDP, you don’t use the I/O streams of the socket to send and receive data. Instead, you send and receive packets; the data is in buffers that are associated with those packets.

Echo, Echo

Echo is a simple Net protocol that is used for testing. Any data that is sent to an echo server is sent back to the client. TcpEcho, shown in
Listing 3
, is a TCP echo client. Here is the algorithm for it:

  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 on port 7.
  4. Set the socket I/O timeout to 5 seconds.
  5. Get a reference to the socket’s I/O streams.
  6. Begin loop to send 3 requests:
    1. Start the timer.
    2. Write a request, a buffer that contains the request number as a byte, to the output stream.
    3. Read a byte from the input stream.
    4. Print the elapsed time.
  7. End loop.
  8. Close the socket and exit.

UdpEcho, shown in
Listing 4
, is a UDP implementation of an echo client. 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 datagram socket.
  4. Set the socket I/O timeout to 5 seconds.
  5. Create a request packet with a buffer than contains 32 spaces, and create a packet for the reply.
  6. Begin loop for the number of requests to send:
    1. Start the timer.
    2. Send the request packet.
    3. Receive the reply packet.
    4. Print the number of bytes received and the elapsed time.
  7. End loop.
  8. Close the socket and exit.

Got mail?

Now, let’s look at an interesting little program called MailPing, shown in
Listing 5
. I wrote it for testing purposes while working at a company that had a very flakey mail server. It will check connectivity to a mail server and send out a test message if specified. Here is the algorithm:

  1. Get the command-line parameters: host, recipient, and sender. If no parameters are specified, print an error message and exit. If sender is not specified, make it the same as the recipient.
  2. Open a socket to connect to the host on port 25.
  3. Get the input and output streams for the socket.
  4. Read the initial reply from the host.
  5. If the recipient was specified:
    1. Create a simple test message.
    2. Send a greeting to the server and read the reply.
    3. Send the sender’s address and read the reply.
    4. Send the data command and read the reply.
    5. Send the message and read the reply.
    6. Send the quit command and read the reply.
  6. Close the socket and exit.

Serving up daytime

DaytimeServer, shown in
Listing 6
, is a simple TCP daytime server. It sends the current date and time to any client that connects to it. Here is the algorithm:

  1. Open a server socket on port 13.
  2. Begin loop.
    1. Wait for a client connection, getting a reference to the client socket (the server end of the connection between client and server).
    2. Get a reference to the output stream of the client socket.
    3. Write the date & time to the output stream.
    4. Close the client socket.
  3. End loop.
  4. Close the server socket and exit.

UdpDaytimeServer, shown in
Listing 7
, is a UDP implementation of a daytime server. Here is the algorithm for it:

  1. Open a datagram socket on port 13.
  2. Begin loop.
    1. Create a reply packet and wait for data to be received.
    2. When a packet is received, get the IP and port of the sender (client).
    3. Create a reply packet containing the date & time that can be sent back to the client at its IP and port.
    4. Send the reply packet.
  3. End loop.
  4. Close the socket and exit.

Serving up Echo

TcpEchoServer, shown in
Listing 8
, is a TCP implementation of an echo server. It is similar to DaytimeServer, but I have added a twist. Each client connection is serviced in a separate thread, so that the main thread is free to do nothing but accept connections as quickly as it can. Here is the main algorithm:

  1. Get the port from command-line. If it is not specified, use port 7.
  2. Create an instance of the server and start it.
  3. Create the server socket.
  4. Begin loop.
    1. Wait for client connection, getting a reference to the client socket when the connection is received.
    2. Create and start a new client thread, passing it the client socket.
  5. End loop.
  6. Close the server socket and exit.

Here is the algorithm for the client thread:

  1. Get references to the input and output streams for the client socket.
  2. Begin loop.
  3. Read a byte from the input stream (blocking until a byte is received, or end-of-file is encountered, which will happen when the client disconnects).
  4. Write the byte that was received to the output stream (i.e. send the byte back to the client).
  5. End loop.

Writing a UDP implementation of an echo server is left as an exercise for the reader.

Summary

In this article, I have shown you the several client programs, a couple of server programs, and the basics of using UDP. Hopefully these things have given you some ideas for your own Internet programs. In the next part of this series, I will show you how to work with some of the higher level protocols, such as HTTP.

Related Links

About the author

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



  daytime.java
(Code Sample)

 

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

/**
* This class is a simple client that uses the Daytime internet protocol to get
* the date & time from a given host.
*/
public class Daytime {

// main()
//
public static void main(String[] args) {
String host;
InetAddress hostAddress;
String inBuffer;
Socket daytimeSocket;
BufferedReader socketIn;

// If number of args < 1, print usage.

if (args.length < 1) {
System.out.println("Usage: Daytime <host>");

} else {

try {
// Get the host.

host = args[0];
hostAddress = InetAddress.getByName(host);

System.out.println("Connecting to " + hostAddress.toString() + " ...");

// Open a socket on port 13.

daytimeSocket = new Socket(hostAddress, 13);

// Send the requests and read the replies.

try {
// Set the socket timeout to 5 seconds.

daytimeSocket.setSoTimeout(5 * 1000);

// Get the I/O streams.

socketIn = new BufferedReader(
new InputStreamReader(daytimeSocket.getInputStream()));

// Read the reply from the server.

inBuffer = socketIn.readLine();
System.out.println("Reply received: " + inBuffer);

} finally {
// Close the socket.

daytimeSocket.close();
}

// If there is an exception, print it.

} catch(Exception ex) {
System.out.println(ex);
}
}

System.exit(0);
}
}

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories