Home > Articles > Programming > Java

Like this article? We recommend

Wireless Network Programming Using Datagrams

A datagram is an independent, self-contained message sent over the network; the datagram's arrival, arrival time, and content are not guaranteed. It is a packet-based communication mechanism. Unlike stream-based communication, packet-based communication is connectionless, which means that no dedicated open connection exists between the sender and the receiver.

Packet-switched wireless networks are more likely to support this type of communication on MIDP devices. Datagrams may not be supported by circuit-switched wireless networks, which means that wireless applications developed with datagrams might be limited to certain devices and are less likely to be portable across different networks.

UDP

Datagram communication is based on UDP. The sender builds a datagram packet with destination information (an Internet address and a port number) and sends it out. Lower-level network layers do not perform any sequencing, error checking, or acknowledgement of packets. So, there is no guarantee that a data packet will arrive at its destination. The server might never receive your initial datagram—moreover, if it does, its response might never reach your wireless device. Because UDP is a not a guaranteed-delivery protocol, it is not suitable for applications such as FTP that require reliable transmission of data. However, it is useful in the following cases:

  • When raw speed of the communication is more critical than transmitting every bit correctly. For example, in a real-time wireless audio/video application on a cell phone, lost data packets simply appear as static. Static is much more tolerable than awkward pauses (when socket data transmission is used) in the audio stream.

  • When information needs to be transmitted on a frequent basis. In this case, losing a communication packet now and then doesn't affect the service significantly.

  • When socket communication is not supported at all, which is most likely the case in a packet-switched wireless network.

Using Datagrams

Here are the typical steps for using datagram communication in MIDlet applications:

  1. Establish a datagram connection.

  2. Construct a send datagram object with a message body and a destination address.

  3. Send the datagram message out through the established datagram connection.

  4. Construct a receive datagram object with a pre-allocated buffer.

  5. Wait to receive the message through the established connection using the allocated datagram buffer.

  6. Free up the datagram connection after use.

The following are rules of thumb for choosing a datagram size:

  • Never exceed the maximum allowable packet size. The maximum allowable packet size can be obtained by using the method GetMaximumLength() in the DatagramConnection interface (discussed earlier in the section "The Generic Connection Framework"). This number varies from vendor to vendor.

  • If the wireless network is very reliable and most of the data transmitted will arrive at the destination, use a bigger packet size. The bigger the packet size, the more efficient the data transfer, because the datagram header causes significant overhead when the packet size is too small.

  • If the wireless network is not very reliable, packets will probably be dropped during transmission. Use a smaller packet size so that they are unlikely to be corrupted in transit.

DatagramConnection and Datagram Classes

J2ME network programming with datagrams is very similar to J2SE. Two classes are defined in J2ME to support datagram communication: DatagramConnection and Datagram.

DatagramConnection is one of the connection interfaces in the Generic Network framework. It defines methods to support network communication based on the UDP protocol. (These methods were discussed in the section "The Generic Connection Framework" earlier in this chapter.)

Datagram provides a placeholder for a datagram message. A Datagram object can then be sent or received through a DatagramConnection.

The Datagram class extends from the DataInput and DataOutput classes in the java.io package. These classes provide methods for the necessary read and write operations to the binary data stored in the datagram's buffer.

Datagram also defines several UDP-specific methods in addition to the methods inherited from DataInput and DataOutput. These methods are as follows:

String getAddress()

This method returns the destination address in a datagram message.

byte[] getData()

This method returns the data buffer for a datagram message.

int getLength()

This method returns the length of the data buffer.

int getOffset()

This method returns the offset position in the data buffer.

void reset()

This method resets the read/write pointer to the beginning of the data structure.

void setAddress(Datagram ref)

This method gets the destination address from ref and assigns it to the current Datagram object.

void setAddress(String addr)

This method sets the destination address using addr. The address string is in the format {protocol}://[{host}]:{port}.

void setData(byte[] buffer, int offset, int len)

This method sets the data buffer, offset, and length for the Datagram object.

void setLength(int len)

This method sets a new length for its data buffer.

 

The following methods in the Datagram class are inherited from DataInput for reading binary data from its data buffer:

boolean readBoolean()
byte readByte()
char readChar()
void readFully(byte[] b)
void readFully(byte[] b, int off, int len)
int readInt()
long readLong()
short readShort()
int readUnsignedByte() 
int readUnsignedShort() 
String readUTF() 
int skipBytes(int n)

The following methods in the Datagram class are inherited from DataOutput for writing binary data to the datagram's data buffer:

void write(byte[] b)
void write(byte[] b, int off, int len) 
void write(int b) 
void writeBoolean(boolean v) 
void writeByte(int v) 
void writeChar(int v) 
void writeChars(String s) 
void writeInt(int v) 
void writeLong(long v) 
void writeShort(int v) 
void writeUTF(String str)

Datagram Connections

To use datagram communication in a J2ME application, a datagram connection has to be opened first. Here is how to do that:

DatagramConnection dc = (DatagramConnection)
  Connector.open("datagram://localhost:9000");

Like other types of connections, a datagram connection is created with the open method in Connector. The connect string is in this format:

datagram://[{host}]:{port}

In the connect string, the port field is required; it specifies the target port with a host. The host field is optional; it specifies the target host. If the host field is missing in the connection string, the connection is created in "server" mode. Otherwise, the connection is created in "client" mode.

For example, here is how a "server" mode datagram connection is created:

DatagramConnection dc = (DatagramConnection)
 Connector.open("datagram://:9000");

This is the equivalent of the following:

DatagramConnection dc = (DatagramConnection)
 Connector.open("datagram://localhost:9000");

A "server" mode connection means that the connection can be used both for sending and receiving datagrams via the same port. In the previous example, the program can receive and send datagrams on port 9000.

A "client" mode datagram connection is created with host specified in the connect string:

DatagramConnection dc = (DatagramConnection)
 Connector.open("datagram://64.28.105.110:9000");

A "client" mode connection can be used only for sending datagram messages. The datagram to be sent must have the destination host and port; in this case, the host is 64.28.105.110 and the target port is 9000. When a datagram message is sent with a client mode connection, the reply-to port is always allocated dynamically.

Once a DatagramConnection is established, datagram messages can be sent and received using the send and receive methods.

The example in Listing 9.4 shows how to use datagrams to communicate with a remote server:

Listing 9.4 Listing4.txt

/**
 * This sample code block demonstrates how a "server" mode
 * DatagramConnection is created, and how datagram
 * messages are sent and received via the connection.
 * For demostration purpose, we assume that the remote server
 * listens to port 9000 for incoming datagrams and responses
 * back with a datagram message once the incoming datagram is
 * received.. Once the message is received.
 */

import javax.microedition.io.*;
import java.io.*;
import java.lang.*;

// more code here ...

// the destination address of the datagram message to be sent.
String destAddr = "datagram://64.28.105.110:9000";

// the message string to be sent
String messageString = "REQUEST INFO";

// the DatagramConnection to be used for exchanging message with remote server
DatagramConnection datagramConnection = null;

try {
  // create a "server" mode DatagramConnection
  datagramConnection = 
   (DatagramConnection) Connector.open("datagram://:9000");
  
  // get the length of the datagram message
  int length = messageString.length();
  
  byte[] messageBytes = new byte[length];
  
  // store the message string into a byte array
  System.arraycopy(messageString.getBytes(), 0, messageBytes, 0, length);
  
  // construct a Datagram object to be sent with the message byte array,
  // length of the byte array, and the destination address
  Datagram sendDatagram =
  datagramConnection.newDatagram(messageBytes, length, destAddr);
  
  // send the Datagram object to its destination
  datagramConnection.send(sendDatagram);
  
  // create a Datagram object as a place holder for receiving message
  receiveDatagram = datagramConnection.newDatagram(
  
  datagramConnection.getMaximumLength());
  
  // wait for Datagram sent back from remote server
  datagramConnection.receive(receiveDatagram);
  
  // do something with the received Datagram ...
  
} catch (IOException e) {
  System.err.println("IOException Caught:" + e);
} finally {
  // free up open connection
  try { if (dc != null) dc.close();
  } catch (Exception ignored) {}
}

// more code here ...

Sample Program

The following sample application demonstrates datagram communication between two cell phones. It consists of two programs: DatagramClient.java and DatagramServer.java. They are running on separate emulators. DatagramClient initiates a message, sends it out to DatagramServer using port 9000, and uses the same port to receive the response back. DatagramServer receives the message sent from the DatagramClient at port 9001, reverses the message string, and sends the reversed message back to the client. In this example, the client and server programs are running on separate emulators on the same machine. But, this process could just as easily occur across the Internet.

Figure 9.5 illustrates the program flow between two J2ME programs communicating with each other using datagrams.

Figure 9.5 The program flow of the datagram sample application.

The code of the client program can be found in Listing 9.5, and the code of the server program can be found in Listing 9.6.

Listing 9.5 DatagramClient.java

/**
 * The following MIDlet application is a datagram client program
 * that exchanges datagram with another MIDlet application acting
 * as a datagram server program.
 */

// include MIDlet class libraries
import javax.microedition.midlet.*;
// include networking class libraries
import javax.microedition.io.*;
// include GUI class libraries
import javax.microedition.lcdui.*;
// include I/O class libraries
import java.io.*;

public class DatagramClient extends MIDlet
implements CommandListener {
  // define the GUI components for entering the message text to be sent
  private Form mainScreen;
  private TextField sendingField;
  private Display myDisplay = null;
  private DatagramClientHandler client;
  
  // define the GUI components for displaying the returned message
  private Form resultScreen;
  private StringItem resultField;
  private String resultString;
  
  // the "send" button on the mainScreen
  Command sendCommand = new Command("SEND", Command.OK, 1);
  
  public DatagramClient(){
    // initialize the GUI components
    myDisplay = Display.getDisplay(this);
    mainScreen = new Form("Datagram Client");
    sendingField = new TextField(
    "Enter your message", null, 30, TextField.ANY);
    mainScreen.append(sendingField);
    mainScreen.addCommand(sendCommand);
    mainScreen.setCommandListener(this);
  }
  
  public void startApp() {
    myDisplay.setCurrent(mainScreen);
    client = new DatagramClientHandler();
  }
  
  public void pauseApp() {
  }
  
  public void destroyApp(boolean unconditional) {
  }
  
  public void commandAction(Command c, Displayable s) {
    if (c == sendCommand) {
      // get the message text from user input
      String sendMessage = sendingField.getString();
      
      // send and receive datagram messages
      try {
        resultString = client.send_receive(sendMessage);
      } catch (IOException e) {
        System.out.println("Failed in send_receive():" + e);
      }
      
      // display the returned message
      resultScreen = new Form("Message Confirmed:");
      resultField = new StringItem(null, resultString);
      resultScreen.append(resultField);
      resultScreen.setCommandListener(this);
      myDisplay.setCurrent(resultScreen);
    }
  }
  
  class DatagramClientHandler extends Object {
    private DatagramConnection dc;
    // Datagram object to be sent
    private Datagram sendDatagram;
    // Datagram object to be received
    private Datagram receiveDatagram;
    
    public DatagramClientHandler() {
      try {
        // establish a DatagramConnection at port 9000
        dc = (DatagramConnection)
         Connector.open("datagram://" + ":9000");
        
        /* Since the datagram server program runs on the same machine
         * where the client program runs on, and the server program
         * listens to port 9001, the destination address of datagram
         * to be sent is set to "localhost:9001". If the server
         * program runs on a different machine, "localhost" in the
         * connect string needs to be replaced with that machine's ip
         * address.
         */
        sendDatagram = dc.newDatagram(
        dc.getMaximumLength(), "datagram://localhost:9001");
        
        // initialize the Datagram object to be received
        receiveDatagram = dc.newDatagram(dc.getMaximumLength());
      } catch (IOException e) {
        System.out.println(e.toString());
      }
    }
    
    public String send_receive(String msg) throws IOException {
      int length = msg.length();
      byte[] message = new byte[length];
      
      // copy the send message text into a byte array
      System.arraycopy(msg.getBytes(), 0, message, 0, length);
      sendDatagram.setData(message, 0, length);
      sendDatagram.setLength(length);
      
      // use retval to store the received message text
      String retval = "";
      try {
        // send the message to server program
        dc.send(sendDatagram);
        
        // wait and receive message from the server
        dc.receive(receiveDatagram);
        
        // put the received message in a byte array
        byte[] data = receiveDatagram.getData();
        
        // transform the byte array to a string
        retval = new String(data, 0, receiveDatagram.getLength());
      } finally{
        if (dc != null) dc.close();
      }
      
      // return the received message text to the calling program
      return retval;
    }
  }
}

Listing 9.6 DatagramServer.java

/**
 * The following MIDlet application is a datagram server program
 * that waits and receives datagram message from a client program,
 * reverses the message text, then sends the reversed text back to
 * the datagram client program.
 */

// include MIDlet class libraries
import javax.microedition.midlet.*;
// include networking class libraries
import javax.microedition.io.*;
// include GUI class libraries
import javax.microedition.lcdui.*;
// include I/O class libraries
import java.io.*;

public class DatagramServer extends MIDlet{
  // define the GUI components for displaying the received message
  private Display myDisplay = null;
  private Form mainScreen;
  private StringItem resultField;
  
  // text string for storing the received message
  private String resultString;
  
  public DatagramServer() {
    // initialize the GUI components
    myDisplay = Display.getDisplay(this);
    mainScreen = new Form("Message Received");
    resultField = new StringItem(null, null);
  }
  
  public void startApp() {
    myDisplay.setCurrent(mainScreen);
    
    // perform the receive, reverse and send back tasks
    DatagramServerHandler server = new DatagramServerHandler();
    try {
      resultString = server.receive_reverse_send();
    } catch (IOException e) {
      System.out.println("Failed in receive_reverse_send():" + e);
    }
    
    // display the received message text
    resultField.setText(resultString);
    mainScreen.append(resultField);
  }
  
  public void pauseApp() {
  }
  
  public void destroyApp(boolean unconditional) {
  }
  
  class DatagramServerHandler extends Object {
    // the server program listens to port 9001
    private static final String defaultPortNumber="9001";
    private String msg;
    private DatagramConnection dc;
    
    // define the Datagram objects for messages
    private Datagram sendDatagram;
    private Datagram receiveDatagram;
    
    public DatagramServerHandler() {
      try {
        // Create a "server" mode connection on the default port
        dc = (DatagramConnection)Connector.open(
        "datagram://:" + defaultPortNumber);
        
        // construct a Datagram object for receiving message
        receiveDatagram = dc.newDatagram(dc.getMaximumLength());
        
        // construct a Datagram object for sending message
        sendDatagram = dc.newDatagram(dc.getMaximumLength());
        
      } catch (Exception e) {
        System.out.println("Failed to initialize Connector");
      }
    }
    
    public String receive_reverse_send() throws IOException {
      String receiveString = "";
      try{
        // wait to receive datagram message
        dc.receive(receiveDatagram);
        
        // extract data from the Datagram object receiveDatagram
        byte[] receiveData = receiveDatagram.getData();
        int receiveLength = receiveDatagram.getLength();
        
        // store message text in receiveString
        receiveString = (new String(receiveData)).trim();
        
        // reverse the string
        StringBuffer reversedString =
        (new StringBuffer(receiveString)).reverse();
        
        // getting the reply-to address from the Datagram object
        String address = receiveDatagram.getAddress();
        
        // construct the sendDatagram with the reversed text
        // and the reply-to address.
        int sendLength = reversedString.length();
        byte[] sendData = new byte[sendLength];
        System.arraycopy(reversedString.toString().getBytes(),
        0, sendData, 0, sendLength);
        sendDatagram.setData(sendData, 0, sendLength);
        sendDatagram.setAddress(address);
        
        // send the reversed string back to client program
        dc.send(sendDatagram);
      } finally {
        if (dc != null) dc.close();
      }
      return receiveString;
    }
  }
}

Figure 9.6 shows the client program before the message test message is sent to the server program. Figure 9.7 shows the server program after the message test message is received.

Figure 9.6 Before test message is sent to the server.

Figure 9.7 After test message is received by the server.

Figure 9.8 shows the client program after the reversed message string is received from the server program. The string test message is now egassem tset.

Figure 9.8 The reversed message egassem tset is received from the server.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020