home account info subscribe login search My ITKnowledge FAQ/help site map contact us


 
Brief Full
 Advanced
      Search
 Search Tips
To access the contents, click the chapter and section titles.

Platinum Edition Using HTML 4, XML, and Java 1.2
(Publisher: Macmillan Computer Publishing)
Author(s): Eric Ladd
ISBN: 078971759x
Publication Date: 11/01/98

Bookmark It

Search this book:
 
Previous Table of Contents Next


Listing 40.3 shows a client designed to work with the server in Listing 40.2. This client has four steps:

1.  Connect to the server.
2.  Wait for a message.
3.  Display the message to the user.
4.  Tear down the connection.

Listing 40.3 TClient.javaThis Class Will Help You Design Your Client Program


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

 public class TClient {
   private static final int PORTNUMBER = 8013;
   public static void main(String args[]) {
     Socket theSocket;
     BufferedReader theReader;
     String theAddress = “”;

     // check the command line for a host address
     if (args.length != 1) {
      System.out.println(“Usage: java TClient <address>”);
      System.exit(1);
     }
     else
       theAddress = args[0];

     // connect to the server
     try {
       theSocket = new Socket(theAddress, PORTNUMBER);
       theReader =
         new BufferedReader(new
            InputStreamReader(theSocket.getInputStream()));

       // wait for a message
       StringBuffer theStringBuffer = new StringBuffer(128);
       String theLine;
       int c;
       while ((theLine = theReader.readLine()) != null) {

         // show the message to the user
         System.out.println(“Server: ” + theLine);
         break;
       }

       // Tear down the connection
       theReader.close();
       theSocket.close();
     } catch (IOException e) {
       System.err.println(“Exception: ” + e.getMessage());
     }
   }
 }


NOTE:  As long as you keep the server on the machine that hosts your applet, you can put the code from Listing 40.3 into an applet. Just move the code in main() into init(). You don’t have to look for the server’s address in a parameter. Just use the Applet method getCodeBase(); it returns the complete URL of the applet itself.

To test this code, first start the server:

java TServer

Now run the client. Note that “localhost” is a common name for a TCP/IP machine to use for itself—this invocation specifies that the server is running on the same machine as the client. We could also have used 127.0.0.1, the local loopback address.

java TClient “localhost”
Server: someDateandTime

To fault-isolate between the client and the server, use your computer’s Telnet client to access the server by port number. Figure 40.1 shows this step. If you’re able to connect and the server works as you expect, you have a problem with your client. Otherwise, you have a problem with the server.


FIGURE 40.1  Use your platform’s Telnet client to attempt to connect to your new server’s well-known port.

Communicating with Datagram Sockets

Communicating using datagram sockets is simpler than using the TCP-based sockets (Socket and ServerSocket) that you used for the TServer. Communication is also faster because no connection overhead exists. There is also no attempt to send packets again if an error occurs or sequencing of multiple packets, as occurs in TCP/IP transmissions.

A datagram packet is sent as an array of bytes to a receiving program, presumably listening at a particular IP address and port. If the receiving program gets the datagram and wants to send a reply, it becomes the sender, addressing a datagram back to a known IP address and port. The conversation style is a bit like those two-way radios in airplanes in which the pilot sends a message, says “Over,” and waits for the controller to respond.

You might use datagram socket communication if you are writing an interactive game—returning a small piece of information such as the time. You don’t want the overhead of establishing a connection, or perhaps the communication takes place locally.

Sending a Datagram Packet

Listing 40.4 shows a prototype program for sending a datagram packet. It sends a 27-byte message (“I’m a datagram and I’m O.K.”) to the IP address mapped to “localhost” at port number 6969. When you try this, use an IP address and port that you know is available. These values should work on most machines.

Listing 40.4 DatagramSend.java—A Prototype Program to Transmit a Datagram Packet


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

public class TDatagramSend {
  static final int PORT = 6969;
  public static void main( String args[] ) throws Exception {
    String theStringToSend = “I’m a datagram and I’m O.K.”;
    byte[] theByteArray = new byte[ theStringToSend.length() ];
    theByteArray = theStringToSend.getBytes();

    // Get the IP address of our destination...
    InetAddress theIPAddress = null;
    try {
      theIPAddress = InetAddress.getByName( “localhost” );
    } catch (UnknownHostException e) {
      System.out.println(“Host not found: “ + e);
      System.exit(1);
    }

    // Build the packet...
    DatagramPacket thePacket = new DatagramPacket( theByteArray,
      theStringToSend.length(),
      theIPAddress,
      PORT );

    // Now send the packet
    DatagramSocket theSocket = null;
    try {
      theSocket = new DatagramSocket();
    } catch (SocketException e) {
        System.out.println(“Underlying network software has failed: ” + e);
        System.exit(1);
    }
    try {
      theSocket.send( thePacket );
    } catch (IOException e) {
      System.out.println(“IO Exception: ” + e);    }
    theSocket.close();
    }
}

You need to use only one socket: the DatagramSocket. There is no concept of the server listening for client requests. The idea is to establish a DatagramSocket object and then send and receive messages. The messages are sent in a DatagramPacket object. An additional object—InetAddress—is needed to construct the IP address to send the packet.

The DatagramSend class has only one method—main()—so it is a standalone Java program. This demonstration program sends only one message. You can, of course, modify main() to pass any message to any IP address and port.

The DatagramPacket constructor used here has the following four arguments:

  theByteArray—An array of bytes containing the message to send
  theStringToSend.length()—The length of the string you are going to send
  theIPAddress—the InetAddress object containing the resolved IP address of your destination
  PORT—An integer specifying the port number

Another form of the constructor requires only the first two arguments. It is designed for local communication when the IP address and port are already known. You will see it in action in the following section, “Receiving a Datagram Packet.”


Previous Table of Contents Next


Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc.
All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.