Back Contents Next


  
  FAQ
  Java Tutorial
  Questions by Topic
  Sample test
  Other Certification sites
  Certification Tips
  Exam Objectives
  Java jobs
  Java News
  About Java Prepare
   Books
  Certification Books
  SCEA Books
  Online Books
   Tutorial Topics
  Language Fundamentals
  Operator and Assignments
  Declaration and Access Control
  Classes in Java
  AWT
  Event classes
  Threads
  Layout Managers
  Collections
  Files
   Advertisements
cover
   Feedback
  Please let us know your feedback
 
StoreBusters Marketing
javaprepare.com
your tool for Java Certification
home | tutorial | questions | test 1

5.1 Connectionless Protocol Classes

One mechanism for transferring data between a two programs is called the connectionless protocol. With this protocol, a given packet is sent without any guarantee that it will be delivered to the recipient, and without any way for the sender to determine whether or not it has arrived. The connectionless protocol has a performance advantage over the connection-oriented protocol and is therefore useful for applications where increased performance can be traded off against the risk of losing some data, such as when transferring video data. The connectionless protocol class hierarchy is shown in the figure below.

 

 

 

A schematic showing the mechanism for transferring data between two programs using the connectionless protocol is shown below. The sender and recipient programs each create a DatagramPacket object and a DatagramSocket object.

 

The sender's DatagramPacket object contains some data, and a destination IP address and port number. The send() method of the DatagramSocket object is then used to send the DatagramPacket object to its destination.

 

The recipient, meanwhile, has created a DatagramSocket object that is associated with the appropriate port number at which it wishes to listen. The receive() method of the DatagramSocket object is used to place whatever data it receives into the servers DatagramPacket object.

 

 

5.1.1 DatagramPacket Class

public final class DatagramPacket extends Object

 

Object

  DatagramPacket

 

A DatagramPacket object represents a packet of data consisting of an array of bytes. It is used to transfer data between a client machine and a server using the connectionless protocol. The DatagramPacket object also has associated with it an IP address and a port number to which it is being sent, or from which it was received.

DatagramPacket() Constructor

Constructor

Syntax

DatagramPacket()

public DatagramPacket(byte[] data, int length)

 

public DatagramPacket(byte[] data, int offset,
                      int length)

 

public DatagramPacket(byte[] data, int length,
                      InetAddress addr, int port)

 

public DatagramPacket(byte[] data, int offset,
                      int length, InetAddress addr,
                      int port)

 

Creates a DatagramPacket object. These constructors actually define two different types of DatagramPacket objects:

 

q       The first two create DatagramPacket objects that are intended to receive data, and don't require an InetAddress object.

q       The third and fourth versions create DatagramPacket objects that are intended to send data.

 

The length variable is the number of bytes to read or send and must be less than or equal to the length of the byte array. Specifying an offset allows some of the data to be skipped over when reading or sending. The port number must be between 0 and 65535. Port numbers between 1 and 511 are reserved for well-known services. For instance, port 21 is reserved for FTP and port 23 is reserved for telnet. Port numbers between 512 and 1023 are also reserved and on some systems require super-user privileges to use them. Port numbers between 1024 and 65535 are available for general use.

Methods to Return DatagramPacket Properties

Method

Syntax

getAddress()

public InetAddress getAddress()

getData()

public byte[] getData()

getLength()

public int getLength()

getOffset()

public int getOffset()

getPort()

public int getPort()

 

getAddress() returns the IP address of the either the machine that sent the packet or the destination address, depending on whether the invoking DatagramPacket object is intended to receive or send data.

 

getData() returns a byte array containing the data associated with the invoking DatagramPacket object.

 

getLength() returns the number of bytes to be sent or received by the invoking DatagramPacket object.

 

getOffset() returns the offset, if any.

 

getPort() returns the port number of either the machine that sent the packet or the destination address, depending on whether the invoking DatagramPacket object is intended to send or receive data.

Methods to Set DatagramPacket Properties

Method

Syntax

setAddress()

public void setAddress(InetAddress addr)

setData()

public void setData(byte[] data)

 

public void setData(byte[] data, int offset, int length)

setLength()

public void setLength(int length)

setPort()

public void setPort(int portNumber)

 

setAddress() is used to set or change the destination IP address of the invoking DatagramPacket object.

 

setData() sets the data associated with the invoking DatagramPacket object.

 

setLength() specifies the number of bytes to be sent by the invoking DatagramPacket object.

 

setPort() sets the destination port number of the invoking DatagramPacket object.

 

Example: Using DatagramPacket

 

See example Using the Connectionless Protocol on page 8, where DatagramPacket objects are used to send and receive data in a simple client-server program using the connectionless protocol.

 

5.1.2 DatagramSocket Class

public class DatagramSocket extends Object

 

Object

  DatagramSocket

 

A DatagramSocket object represents the mechanism by which packets of data are sent and received using the connectionless protocol.

DatagramSocket() Constructor

Constructor

Syntax

DatagramSocket()

public DatagramSocket() throws SocketException

 

public DatagramSocket(int port) throws SocketException

 

public DatagramSocket(int port, InetAddress localHostMachine) throws SocketException

 

Creates a DatagramSocket object. The port number and IP address of the local machine can be specified. The port number must be between 0 and 65535. Some of the lower numbers are reserved for system use. (See DatagramPacket() Constructor on page 3.) If no port number is provided, the DatagramSocket object will be assigned any available port on the local machine.

close() Method

Method

Syntax

close()

public void close()

 

close() closes the invoking DatagramSocket object and releases any resources assigned to it.

Connection Methods

Method

Syntax

connect()

public void connect(InetAddress address, int port)

disconnect()

public void disconnect()

getInetAddress()

public InetAddress getInetAddress()

getPort()

public int getPort()

 

A DatagramSocket object may be connected, if desired, to a particular address and port number, so that it can only send or receive data from that address and port. (This is a completely different type of 'connection' to that of the connection-oriented protocol.) By default, a DatagramSocket object is not connected, and can send or receive data from any source.

 

connect() connects the DatagramSocket object to the specified address and port.

 

disconnect() disconnects the invoking DatagramSocket object. It does nothing if the DatagramSocket object is not connected.

 

getInetAddress() returns an InetAddress object representing the IP address of the remote machine, if the invoking DatagramSocket object is connected, or null if it object is not connected.

 

getPort() returns the port number to which the invoking DatagramSocket object is connected, or 1 if the DatagramSocket object is not connected.

Methods to Return DatagramSocket Properties

Method

Syntax

getLocalAddress()

public InetAddress getLocalAddress()

getLocalPort()

public int getLocalPort()

getReceiveBufferSize()

public int getReceiveBufferSize()
  throws SocketException

getSendBufferSize()

public int getSendBufferSize()
  throws SocketException

getSoTimeout()

public int getSoTimeout()
  throws SocketException

 

getLocalAddress() returns an InetAddress object containing the local address to which the invoking DatagramSocket object is bound.

 

getLocalPort() returns the port number to which the invoking DatagramSocket object is bound.

 

getReceiveBufferSize() and getSendBufferSize() return the size of the input and output buffers used by the local machine for this socket.

 

getSoTimeout() returns the time in milliseconds that the invoking DatagramSocket object will wait for an incoming packet of data.

Methods to Set DatagramSocket Properties

Method

Syntax

setReceiveBufferSize()

public void setReceiveBufferSize(int size)
  throws SocketException

setSendBufferSize()

public void setSendBufferSize(int size)
  throws SocketException

setSoTimeout()

public void setSoTimeout(int time)
  throws SocketException

 

setReceiveBufferSize() and setSendBufferSize() change the size of the input and output buffers used by the local machine for this socket. The local machine may or may not accept the size specified by these methods.

 

setSoTimeout() changes the time in milliseconds that the invoking DatagramSocket object will wait for an incoming packet of data. Setting the value to 0 indicates that the DatagramSocket object will wait indefinitely.

receive() Method

Method

Syntax

receive()

public void receive(DatagramPacket pkt) throws IOException

 

receive() receives a DatagramPacket object from the socket. This method blocks other activity until a packet is received or until the time-out time has elapsed. Once a packet has been received, the method returns. The received packet contains a byte array containing data, the length of the byte array, the sender's IP address, and the sender's port number.

send() Method

Method

Syntax

send()

public void send(DatagramPacket pkt) throws IOException

 

send() sends a DatagramPacket object into the socket. The DatagramPacket object must contain a byte array containing the data to be transmitted, the length of the byte array, the destination IP address, and the destination port number.

 

Example: Using the Connectionless Protocol8

 

This example sets up a simple client-server application, comprising separate client and server programs. When the user clicks on a button, the client sends a DatagramPacket to the server requesting information. The server recieves the request, and returns a DatagramPacket to the client containing a byte array representation of an Info object, which holds information about a ski resort. The client receives the DatagramPacket from the server, converts its data back into an Info object, and displays the information.

 

Each of the three classes is kept in a separate file. To run this example, open up two windows on the same machine. Run the server in one window and the client in the other.

Info Class

An Info object encapsulates some information about a ski resort. This class is used by both the client and server classes.

 

import java.io.*;

 

public class Info implements Serializable {

  private String name, base;

  private int runs;

 

  public Info(String n, int r, String b) {

    name = n;

    runs = r;

    base = b;

  }

 

  public String getName() {

    return name;

  }

 

  public int getRuns() {

    return runs;

  }

 

  public String getBase() {

    return base;

  }

}

Server program

The ServerCLP class sets up a server to receive and transmit data using the connectionless protocol. A DatagramSocket object is created that will send and receive data packets. The listening and transmitting code is placed in an infinite loop. Thus, the server will keep listening for packets from client machines as long as sever program keeps running.

 

Two separate DatagramPacket objects are created. The first, named pktReceive, is used to listen for a signal from a client machine. Once the signal is received, this DatagramPacket contains no data, but does contain the IP address and port number of the client machine. Once a signal from a client machine is received, an Info object containing information about a ski resort is sent back to the client machine.

 

To send the data through the socket, the Info object must be converted into a byte array. This is accomplished using ByteArrayOutputStream and ObjectOutputStream objects. The writeObject() method from the ObjectOutputStream class is used to write the Info object to an output stream. The toByteArray() method returns a byte array containing the contents of the output stream. For the writeObject() method to work properly, the Info object must implement either the Serializable or Externalizable interfaces.

 

Once the Info object has been written to a byte array, the outgoing DatagramPacket object can be created using the IP address and port number obtained from the incoming DatagramPacket.

 

import java.net.*;

import java.io.*;

 

public class ServerCLP {

  static DatagramSocket ds;

  static int portNumber = 8888;

  static DatagramPacket pktReceive, pktSend;

 

  public static void main(String args[]) {

 

    // Create DatagramSocket to send and receive data packets

    try {

      ds = new DatagramSocket(portNumber);

    } catch (SocketException se) {}

 

    // Create a packet to receive data from the client

    pktReceive = new DatagramPacket(new byte[1], 1);

 

    while (true) {

      try {

        // Wait for a packet

        ds.receive(pktReceive);

 

        // Create ObjectOutputStream to convert Info object to

        // stream of bytes

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        ObjectOutputStream oos = new ObjectOutputStream(bos);

 

        // Create Info object ready to send to client

        Info info = new Info("NorthStar", 18, "72 inches");

 

        // Convert Info object into array of bytes

        oos.writeObject(info);

        byte[] data = bos.toByteArray();

 

        // Create packet and send to client

        pktSend = new DatagramPacket(data, data.length,

                                     pktReceive.getAddress(),

                                     pktReceive.getPort());

        ds.send(pktSend);

      } catch (IOException ioe) {}

    }

  }

}

Client program

The ClientCLP class creates a simple user interface by placing a JButton object and three JLabel objects in a screen window using a JFrame. When the JButton object is clicked, the actionPerformed() method is called.

 

Inside the actionPerformed() method, a DatagramSocket object is created to send and receive data packets. A DatagramPacket object is created and sent to the server. This object contains no data, but does contain the IP address and port number of the client machine, so that the server knows where to return its response.

 

The client then waits until it receives a DatagramPacket object from the server. Once it receives the incoming DatagramPacket object, it must convert the byte array of data to an Info object. It does this using a ByteArrayInputStream and ObjectInputStream object. The readObject() method from the ObjectInputStream class converts the byte array to an Object object which is then cast to an Info object.

 

The information contained in the Info object is then extracted and displayed in the JLabel components.

 

import java.net.*;

import java.io.*;

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

 

public class ClientCLP extends JFrame implements ActionListener {

  DatagramSocket ds;

  int portNumber = 8888;

  DatagramPacket pktReceive, pktSend;

  JButton button;

  JLabel lblName, lblRuns, lblBase;

  Info info = null;

  JPanel p1, p2;

 

  public ClientCLP() {

 

    // Create the user interface

    button = new JButton("download");

    button.setFont(new Font("Serif", Font.PLAIN, 12));

    button.setBorder(BorderFactory.createRaisedBevelBorder());

    button.addActionListener(this);

 

    lblName = new JLabel("");

    lblName.setForeground(Color.black);

    lblName.setFont(new Font("Serif", Font.PLAIN, 12));

 

    lblRuns = new JLabel("");

    lblRuns.setForeground(Color.black);

    lblRuns.setFont(new Font("Serif", Font.PLAIN, 12));

 

    lblBase = new JLabel("");

    lblBase.setForeground(Color.black);

    lblBase.setFont(new Font("Serif", Font.PLAIN, 12));

 

    p1 = new JPanel();

    p1.setLayout(new GridLayout(3, 1));

    p1.add(lblName);

    p1.add(lblRuns);

    p1.add(lblBase);

 

    p2 = new JPanel();

    p2.add(button);

 

    getContentPane().add(p2, BorderLayout.NORTH);

    getContentPane().add(p1, BorderLayout.CENTER);

 

    addWindowListener(new WinClosing());

    setBounds(100, 100, 300, 300);

    setVisible(true);

  }

 

  public void actionPerformed(ActionEvent ae) {

 

    // React to pressing of button on user interface

    pktReceive = new DatagramPacket(new byte[1024], 1024);

 

    // Create DatagramSocket to send and receive data packets

    try {

      ds = new DatagramSocket();

    } catch (SocketException se) {}

 

    // Create and send DatagramPacket to ask server for information

    try {

      ds.send(new DatagramPacket(new byte[1], 1,

              InetAddress.getLocalHost(), portNumber));

 

      // Wait for and receive response packet from server

      ds.receive(pktReceive);

 

      // Create ObjectInputStream to convert stream of bytes in

      // packet back into an Info object

      ByteArrayInputStream bis =

        new ByteArrayInputStream(pktReceive.getData());

      ObjectInputStream ois = new ObjectInputStream(bis);

 

      // Convert the packet into an Info object

      try {

        info = (Info) ois.readObject();

      } catch (ClassNotFoundException ce) {}

    } catch (IOException ioe) {}

 

    // If successful, display the information on the user interface

    if (info != null) {

      lblName.setText("Name: " + info.getName());

      lblRuns.setText("Number of runs open: " + info.getRuns());

      lblBase.setText("Snow Depth: " + info.getBase());

      p1.revalidate();

    }

  }

 

  public static void main(String args[]) {

    ClientCLP clp = new ClientCLP();

  }

}

 

class WinClosing extends WindowAdapter {

  public void windowClosing(WindowEvent we) {

    System.exit(0);

  }

}

Output

The user interface of the client program is shown below. After pressing the download button, the information obtained from the server (the name, number of runs open and snow depth) is displayed.

 

 

 

5.1.3 MulticastSocket Class

public class MulticastSocket extends DatagramSocket

 

Object

  DatagramSocket

    MulticastSocket

 

The MulticastSocket class is used to implement multicast data communication using the connectionless protocol. It can be used to send a message to multiple machines, those that are part of the sending machines group. The MulticastSocket object can join or leave groups of other multicast hosts on the Internet. A multicast group is specified by an IP address in a particular range, and by a standard UDP port number.

 

When a MulticastSocket joins a particular multicast group, it receives DatagramPacket objects sent to the group by other hosts (which do not themselves need to be members of the group), as do all other members of the group.

MulticastSocket() Constructor

Constructor

Syntax

MulticastSocket()

public MulticastSocket() throws IOException

 

public MulticastSocket(int port) throws IOException

 

Creates a MulticastSocket object. The MulticastSocket object can be bound to a port on the local host machine by providing the port number to the constructor.

joinGroup() Method

Method

Syntax

joinGroup()

public void joinGroup(InetAddress multicastAddress)
  throws IOException

 

joinGroup() causes the invoking MulticastSocket object to join a multicast group. An IOException is thrown if the specified address is not a multicast address.

leaveGroup() Method

Method

Syntax

leaveGroup()

public void leaveGroup(InetAddress multicastAddress)
  throws IOException

 

leaveGroup() causes the invoking MulticastSocket object to leave a multicast group. An IOException is thrown if the specified address is not a multicast address.

Methods to Return MulticastSocket Properties

Method

Syntax

getInterface()

public InetAddress getInterface()
  throws SocketException

getTimeToLive()

public int getTimeToLive() throws IOException

 

getInterface() returns an InetAddress object containing the IP address the invoking MulticastSocket object will use to send packets to multicast destinations.

 

getTimeToLive() returns the time-to-live (TTL) value of the invoking MulticastSocket object. The TTL value is the number of hops an outgoing packet can experience before it dies.

send() Method

Method

Syntax

send()

public void send(DatagramPacket pkt, byte ttl)
  throws IOException

 

send() sends the specified DatagramPacket object from the invoking MulticastSocket using the specified TTL value. A MulticastSocket object can use this method in addition to the the send() method defined in the DatagramSocket class.

Methods to Set MulticastSocket Properties

Method

Syntax

setInterface()

public void setInterface(InetAddress addr)
  throws SocketException

setTimeToLive()

public void setTimeToLive(int timeToLive)
  throws IOException

 

setInterface() specifies the IP address the invoking MulticastSocket object will use to send packets to multicast destinations.

 

setTimeToLive() changes the time-to-live (TTL) value of the invoking MulticastSocket object.

Deprecated Methods

Method

Syntax

getTTL()

public byte getTTL() throws IOException

setTTL()

public void setTTL(byte ttl) throws IOException

 

These methods have been deprecated as of Java 2 and should not be used for new code.

 

getTTL() returns the time-to-live (TTL) value of the invoking MulticastSocket object as a byte.

 

setTTL() method changes the TTL value of the invoking MulticastSocket object.

 


BackContentsNext
©1999 Wrox Press Limited, US and UK.
home | tutorial | questions | test 1