Master Networking in J2ME for Well-connected Mobile Apps

Master Networking in J2ME for Well-connected Mobile Apps

rom the earliest days of J2ME, network connectivity has been a central focus of the design. So much so that a generic architecture, referred to as the Generic Connection Framework (GCF), was created to standardize not only how applications create network connections but the associated connection interfaces device manufacturers must implement. The GCF is a fundamental part of J2ME and is available to all application profiles including Personal Profile and the Mobile Information Device Profile (MIDP).

Figure 1. The J2ME Stack: The configuration layer forms the basis for the J2ME stack and defines the characteristics of the J2ME.

In order to make the GCF available to all J2ME application profiles, the GCF is implemented in the configuration layer. The configuration layer is a set of J2ME libraries that form the basis of any J2ME architecture. Packages such as java.lang, java.util,, and so forth can be found in the configuration layer. Figure 1 shows how the configuration layer relates to the profile layer in J2ME.

What You Need
Wireless Toolkit 2.1

J2ME Configurations
Currently, there are two J2ME configurations that support networking: the Connected Limited Device Configuration (CLDC) and the Connected Device Configuration (CDC). The CLDC is designed for more limited devices that require a smaller API footprint. MIDP is based on the CLDC. The CDC is designed for devices with more power and API footprint but are still too small to support standard Java. The Personal Profile is based on the CDC.

In order to enhance the upward compatibility of J2ME applications from the CLDC range of devices to the CDC range of devices, the CLDC and CDC have a strict superset-subset relationship. Figure 2 shows the relationship between the CLDC, CDC, and J2SE. Note that the CLDC and CDC contain APIs that are unique to J2ME and not part of standard Java. Libraries that are unique to J2ME exist in the javax.microedition.* packages.

Figure 2. Concentric Circles. The CDC and CLDC have a strict subset-superset relationship. Note also that J2ME configurations contain APIs that extend beyond what standard Java (J2SE) provides.

Configurations and Connectivity
The GCF is implemented in the CLDC, thereby making it available to any J2ME application since, by definition, the CDC must include everything defined by the CDLC. This has the effect of standardizing network connectivity throughout the J2ME environment, regardless of the profile or the device?a big advantage for J2ME developers.

Creating Network Connections using the GCF
Before discussing the architecture any further, I want to look at some code. At the heart of the GCF is the Connector class and a set of interfaces that are defined in the package. The Connector class is a factory that creates connection instances. The interfaces define the types of connections supported. How the implementer actually provides the network connectivity is not of concern, to either the GCF or the application developer, as long as the connection returned supports the behaviors defined by the GCF interface. An example of an HTTP connection is shown below.

HttpConnection c = (HttpConnection)"",    Connector.READ_WRITE, true);

The Connector class figures out what type of connection to create by parsing the connection string (“” in this case). The connection string is composed of three parts: the scheme, target, and parameters. The scheme is required but the latter two are optional. All connection strings follow the pattern noted below.

{scheme}: [{target}] [{parameters}]

In the HTTP example the scheme is “http” and the target is “” There are no parameters.

Although the connection string looks a lot like a URL, it can be used to create many different types of connections, not just HTTP connections. Table 1 shows examples of different types of connections that may be created using the GCF. Note however, the actual support for a specific connection is subject to the J2ME profile requirements and what a vendor chooses to implement. If the connection is not supported by the J2ME implementation a ConnectionNotFoundException is thrown.

HTTP 8080
Socket Listenersocket://:1234
Datagram Senderdatagram://
Datagram Listenerdatagram://: 9001
Comm Portcomm:com0;baudrate=19200;parity=odd

Table 1. Examples of different types of connections that may be created using the GCF. Support for the actual connection type, however, is implementation dependent.Digging into Datagrams
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)"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)"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.

Socket To Me
Another type of connection commonly available on J2ME devices is the TCP-based socket connection. Sockets are different than datagrams because they use a connection-based paradigm to transmit data. This means that both a sender and a receiver must be running and establish a communication channel for data to be exchanged. To use a real-world analogy, a socket connection is like calling a friend on the telephone. If the friend does not answer, a conversation cannot take place. Datagrams on the other hand are more like sending a letter to a friend, where a note is placed into an envelope, addressed, and mailed.

The following code demonstrates how to set up a listener to monitor a port for an inbound socket connection.

try{  ServerSocketConnection ssc = (ServerSocketConnection)"socket://:9002");  StreamConnection sc = null;  InputStream is = null;  try{    sc = ssc.acceptAndOpen();    is = sc.openInputStream();    int ch = 0;    StringBuffer sb = new StringBuffer();    while ((ch = != -1){      sb.append((char)ch);    }    System.out.println(sb.toString());  } finally{      ssc.close();      sc.close();      is.close();  }} catch (IOException x) {    x.printStackTrace();}

In this example a ServerSocketConnection is opened on port 9002. This type of connection is used for sole purpose of listening for an inbound socket connection. The code goes into a wait state when the acceptAndOpen() method is called. When a socket connection is established, the acceptAndOpen() method returns with an instance of a SocketConnection. Opening an input stream on this connection allows data to be read from the transmission.

The next example demonstrates the code required by the client to initiate the socket connection.

try{  SocketConnection sc = (SocketConnection)"socket://localhost:9002");  OutputStream os = null;  try{    os = sc.openOutputStream();    byte[] data = "Hello from a socket!".getBytes();    os.write(data);  } finally{      sc.close();      os.close();  }} catch (IOException x){	x.printStackTrace();}

In this example a SocketConnection is established on port 9002 of the local machine. When using sockets, this is the point on the server side that the acceptAndOpen() method returns. If the connection is successfully opened, the OutputStream is obtained and a message is written to the stream. Note that because sockets are connection based, if there is no server listening for an incoming socket connection an exception will be thrown.

Reading Web Content
The last example will cover reading data using the MIDP HttpConnection. Note that this connection interface is not part of the CLDC or CDC, but is defined rather in the MIDP and Personal Profiles themselves. The behavior of HttpConnection is one that combines an InputStream and an OutputStream into a single connection. A single HttpConnection may open and use exactly one OutputStream and exactly one InputStream. The order in which the streams are used is important as well. The OutputStream, if used, must be used before the InputStream. Once the streams have been used the connection should be closed and a new HttpConnection should be opened to continue communications if necessary. This follows the HTTP request-response paradigm.

The HttpConnection is a bit more tricky to use than the socket or datagram connections because there is a lot that happens behind the scenes. There are three states to an HttpConnection:

  • Setup
  • Connected
  • Closed

The setup state is the first state encountered after a connection is opened. While in this state, connection parameters can be set such as the request method (GET, POST or HEAD) using the setRequestMethod() method or any header properties using the setRequestProperty() method.

The transition from setup to connected is triggered by any methods that cause data to be sent to the server. The following is a list of methods that cause this transition.

  • openInputStream
  • openDataInputStream
  • getLength
  • getType
  • getEncoding
  • getHeaderField
  • getResponseCode
  • getResponseMessage
  • getHeaderFieldInt
  • getHeaderFieldDate
  • getExpiration
  • getDate
  • getLastModified
  • getHeaderField
  • getHeaderFieldKey

Once the connection transitions to the connected state, any calls to setRequestMethod() and setRequestProperty() will throw an IOException. The state transition from setup to connected reflects the underlying handshake of the HttpConnection as headers are sent to the server and the connection prepares to send data. The following example demonstrates reading Web content from an HttpConnection.

HttpConnection c = null;InputStream is = null;StringBuffer sb = new StringBuffer();try {  c = (HttpConnection)     "”,      Connector.READ_WRITE, true);  c.setRequestMethod(HttpConnection.GET); //default  is = c.openInputStream(); // transition to connected!  int ch = 0;  for(int ccnt=0; ccnt < 150; ccnt++) { // get the title.    ch =;    if (ch == -1){      break;    }    sb.append((char)ch);  }}catch (IOException x){	x.printStackTrace();}finally{     try     {       is.close();          c.close();     } catch (IOException x){          x.printStackTrace();     }}System.out.println(sb.toString());

In this example, the server at is contacted. Because this is an HttpConnection and no port is specified, port 80 is used by default. The request method is set to GET (note GET is the default and is explicitly set here only for the example).

Knowing When to Use Which Protocol
As I've just explained, the GCF makes a number of networking options available to applications, but there are a few things you need to know in order to decide which to use when. In the case of MIDP, the specification only requires support for HTTP, although many devices support datagrams and sockets as well, because these protocols are needed to implement HTTP. However, before making commitments to datagrams or sockets it is a good idea to make sure they are supported on the platforms you are targeting.

Because HTTP is guaranteed to be supported by MIDP this is usually the best protocol choice due to portability. HTTP moves through firewalls easily since it generally operates over port 80. However, of the three protocols discussed, HTTP incurs the most overhead, which may drive up the user's cost of using the application on the network.

Datagrams, on the other hand, tend to have far less overhead and can be easier on the end-user's budget. The caveat, as discussed previously, is that the application must take on the task of ensuring that all data arrived at the other end and that the order of that data received is correct.

Finally, sockets fall somewhere in the middle of HTTP and datagrams in that data sent over a socket is managed by the protocol, but requires fewer network resources than HTTP. This means that the application does not have to concern itself with making sure data is received on the other end. Sockets are generally a lighter-weight option over HTTP since the application controls when the end points communicate. HTTP, on the other hand, must make several trips between the end points to exchange header information as well as the data.

The GCF provides a lot of functionality and standardizes how connections are established throughout the J2ME architecture. The GCF is extensible as well, allowing manufacturers to support their own interfaces and connection types. In some cases a manufacturer may use the GCF to support streaming multimedia content with a special connection or for establishing connections to a GPS receiver. Having this kind of flexibility prevents J2ME from being constrained to a common set of protocols while maintaining consistency throughout the architecture.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist