Newsletter sign-up
View all newsletters

Sign up for our technology specific newsletters.

Enterprise Java
Email Address:

Java Tip 40: Object transport via datagram packets

Transport Java objects over the network with datagram packets

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

Page 2 of 3

It is conceivable that in order to construct a datagram packet, the object must be converted into a byte array. This conversion can be very difficult to achieve if the object is involved in a complicated object graph. A number of published articles have discussed ways in which to implement the object serialization -- that is to pickle (to serialize or to marshal) and unpickle (unmarshal) Java objects into (from) byte stream. However, because the object graph can be very complex, converting a general object graph into a byte array will likely require substantial coding efforts.

So, how do we avoid writing complex pickling code? Here is a way to transmit objects in datagram packets without coding for pickling.

The above figure illustrates the data flow when transmitting an object through a datagram. Following the seven steps given below, you will be able to implement this data flow that transmits an object, myObject, of any object type.

  • Step 1. Preparation: Make your object, let's say myObject, serializable by implementing serializable interface.

  • Step 2. Create a ByteArrayOutputStream object, called, for example, baoStream

  • Step 3. Construct an ObjectOutputStream, say ooStream, using baoStream.

  • Step 4. Write the object myObject to baoStream by calling the method writeObject() of ooStream.

  • Step 5. Retrieve the byte array buffer from baoStream, using its method toByteArray().

  • Step 6. Construct a DatagramPacket, say, dPacket, using the array buffer retrieved from Step 5.

  • Step 7. Send dPacket through the DatagramSocket by calling its method send().


To receive an object, go through the steps listed above but in reverse order, replacing ObjectOutputStream with ObjectInputStream and ByteArrayOutputStream with ByteArrayInputStream.

When programming with a socket, sendTo is a standard function used in the connectionless protocol. I rewrote this function so as to be able to transmit objects. The following code example shows how to implement the send method in a Sender class:

import java.io.*;
import java.net.*;
public class Sender
{  public void sendTo(Object o, String hostName, int desPort)  
{    try    
{      InetAddress address = InetAddress.getByName(hostName);
      ByteArrayOutputStream byteStream = new
          ByteArrayOutputStream(5000);
      ObjectOutputStream os = new ObjectOutputStream(new
                              BufferedOutputStream(byteStream));
      os.flush();
      os.writeObject(o);
      os.flush();
      //retrieves byte array
      byte[] sendBuf = byteStream.toByteArray();
      DatagramPacket packet = new DatagramPacket(
                          sendBuf, sendBuf.length, address, desPort);
      int byteCount = packet.getLength();
      dSock.send(packet);
      os.close();
    }
    catch (UnknownHostException e)
    {
      System.err.println("Exception:  " + e);
      e.printStackTrace();    }
    catch (IOException e)    { e.printStackTrace();
 }
  }
}


The code listing below demonstrates how to implement a receive method in a Receiver class. Method recvObjFrom is for the receiver to receive the object. You can include this method in your code to receive runtime objects.

import java.io.*;
import java.net.*;
public class Receiver
{  public Object recvObjFrom()  
{    try
    {
      byte[] recvBuf = new byte[5000];
      DatagramPacket packet = new DatagramPacket(recvBuf,
                                                 recvBuf.length);
      dSock.receive(packet);
      int byteCount = packet.getLength();
      ByteArrayInputStream byteStream = new
                                  ByteArrayInputStream(recvBuf);
      ObjectInputStream is = new
           ObjectInputStream(new BufferedInputStream(byteStream));
      Object o = is.readObject();
      is.close();
      return(o);
    }
    catch (IOException e)
    {
      System.err.println("Exception:  " + e);
      e.printStackTrace();
    }
    catch (ClassNotFoundException e)
    { e.printStackTrace(); }
    return(null);  }
}


One may worry about the size of the byte array -- because when you construct ByteArrayOutputStream or ByteArrayInputStream, you have to specify the size of the array. Since you don't know the size of a runtime object, you will have trouble specifying that size. The size of a runtime object is often unpredictable. Fortunately, Java's ByteArrayInputStream and ByteArrayOutputStream classes can extend their sizes automatically whenever needed.

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comments (5)
Login
Forgot your account info?

12 Years and no comment that this example never workedBy Anonymous on November 17, 2009, 12:35 amAfter 12 years , no one has actually tried to compile this and comment that it does not work. Where is dSock defined? In the first example, it will not compile...

Reply | Read entire comment

Very helpfulBy Anonymous on October 31, 2009, 4:03 pmThanks this is a very clear article. Good job

Reply | Read entire comment

ThanksBy Anonymous on June 12, 2009, 1:39 amCongratulations Shengxi Zhou. It's a very well written article. It was simple to follow and up to the point. Warm Regards, ghd

Reply | Read entire comment

Thank you very much! I am going to implement the same...By Anonymous on March 23, 2009, 8:59 pmThank you very much! I am going to implement the same. I am sure this must work.

Reply | Read entire comment

thanks heaps for ur helpBy Anonymous on October 5, 2008, 11:55 amthat was avery comprehensive description of how serialisation works in sockets. At many other places they give no idea about serialising using datagram sockets. Thanks...

Reply | Read entire comment

View all comments

Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources