Datagrams in J2ME (UDP Programming sample)

By: David Hemphill Emailed: 1606 times Printed: 2075 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

It is quite possible for someone to have worked with Java for some time without ever needing to understand or use datagrams. For mobile devices, however, datagrams offer some advantages in that they are rather lightweight when compared to TCP-based connections such as sockets. User Datagram Protocol, UDP, is one of the more common datagram protocols. However, because most datagram protocols follow the same basic principals as to their usage, the GCF is able to support datagrams generically.

Datagrams are based on a connection-less paradigm, which means that a conversation is not established between two systems. Instead, datagrams are blindly transmitted across a network connection. To transmit a datagram from one system to another, an application creates a datagram and sends it to the intended target. This is a rather simple process in J2ME. However, there is a caveat to using datagrams in that they offer no guarantee or acknowledgement as to whether the datagram actually reached the intended recipient. As a result, a datagram implementation must either not care if the recipient actually receives the data 100 percent of the time, or an acknowledgement/handshake must be implemented manually by the application.

Using Datagrams
The following example shows how to create a datagram and send it to a specific IP address.


try	{
  DatagramConnection dgc = (DatagramConnection)
    Connector.open("datagram://localhost:9001");
  try {
    byte[] payload = "Test Message".getBytes();
    Datagram datagram = 
      dgc.newDatagram(payload, payload.length);
    dgc.send(datagram);
  } finally {
      dgc.close();
  }
} catch (IOException x) {
  x.printStackTrace();
}
In this example, a MIDlet creates a Datagram containing the text "Hello from a Datagram" and sends it to an application listening for datagrams on the local machine on port 9001. This example will execute just fine even if there is no application running to receive the datagram, thus demonstrating the connection-less nature of datagrams. The sender has no indication that the datagram was consumed by the target system.

Next I show how an application might receive the datagram sent by the previous code snippet.


try {
  DatagramConnection dgc = (DatagramConnection) 
    Connector.open("datagram://:9001");
  try {
    int size = 100;
    Datagram datagram = dgc.newDatagram(size);
    dgc.receive(datagram);
    System.out.println(
      new String(datagram.getData()).trim());
  } finally {
      dgc.close();
  }
} catch (IOException x){
  x.printStackTrace();
}
In the receive example, a datagram connection is established on port 9001. A datagram is created with a size of 100 bytes; if a received datagram contains more than 100 bytes, any data beyond the 100-byte mark is ignored. Once the datagram is created the receive() method is called, putting the thread in a wait state until a datagram is received. When a datagram is received, the payload is extracted from the datagram container and printed to the console.

In order to run the send and the receive examples, two instances of a MIDlet can be run from the Wireless Toolkit, one to perform the receive and one to perform the send.


J2ME Home | All J2ME Tutorials | Latest J2ME Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(2)


1. View Comment

hi i want to know
can i sent picture of size 900 bytes using this approach.
if u have any help regarding to this kidnly mail me at mr.nauman9@gmail.com


regards,
Nauman Khalid


View Tutorial          By: Nauman Khalid at 2011-12-10 11:50:39
2. View Comment

i am getting this error how to erase it please tel about this how to execute this program
Warning: To avoid potential deadlock, operations that may block, such as
networking, should be performed in a different thread than the
commandAction() handler.


View Tutorial          By: laxmibvsn at 2012-10-16 15:45:05

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by David Hemphill
Using HTTP vs UDP vs Socket in J2ME
Using HttpConnection in J2ME (Retrieve web content from a website to a phone)
Client Server in J2ME (Socket Programming sample)
Datagrams in J2ME (UDP Programming sample)

More Tutorials in J2ME
Code sample to Send SMS from a J2ME application.
Adding your own Application icon for your J2ME application (jar file)
Play a multimedia file in J2ME Program (Audio/Video) using MMAPI
Datagrams in J2ME (UDP Programming sample)
Client Server in J2ME (Socket Programming sample)
Using HttpConnection in J2ME (Retrieve web content from a website to a phone)
Using HTTP vs UDP vs Socket in J2ME
RMSCookieConnector - Using Cookies in J2ME
POST UTF-8 encoded data to the server in J2ME
lists, forms, choices, gauges, text fields, text boxes in J2ME
Using List to create a Menu and Menu items in J2ME
Using alerts and tickers in J2ME
J2ME Canvas sample to show games programming in J2ME
Timer and TimerTask example in J2ME
List of GPRS Access points for all countries

More Latest News
Most Viewed Articles (in J2ME )
GUI components and menu based J2ME Applications.
'LINK.EXE' is not recognized as an internal or ext
Code sample to Send SMS from a J2ME application.
What is J2ME?
Your first J2ME program and a midlet lifecycle explained.
RMS Basics in J2ME
List of GPRS Access points for all countries
Y.S. Sun Green Building Research Center
Sample J2ME code that shows various functionality of RMS.
A sample J2ME midlet that shows an example of using a Timer and a TimerTask.
Gauge sample program in J2ME
Ticker sample program in J2ME
Sample program to draw a arc in J2ME
The MIDP Networking Model in J2ME
Using List to create a Menu and Menu items in J2ME
Most Emailed Articles (in J2ME)
Using HttpConnection in J2ME (Retrieve web content from a website to a phone)
What is J2ME?
DateField sample program in J2ME
Gauge sample program in J2ME
RMS Basics in J2ME
Y.S. Sun Green Building Research Center
Play a multimedia file in J2ME Program (Audio/Video) using MMAPI
Code sample to Send SMS from a J2ME application.
Download a file over a network in J2ME midlet
How to load J2ME applications to the IDEN handsets
Sample Java program shows how to Read a file over a network using J2ME midlet
Sample J2ME code that shows various functionality of RMS.
GUI components and menu based J2ME Applications.
java.lang.SecurityException: MIDP lifecycle does not support system exit.
Ticker sample program in J2ME