- Overview
- Network Programming with J2SE Versus J2ME
- The Generic Connection Framework
- Wireless Network Programming Using Sockets
- Wireless Network Programming Using Datagrams
- Wireless Network Programming Using HttpConnection
- Summary
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 datagrammoreover, 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:
Establish a datagram connection.
Construct a send datagram object with a message body and a destination address.
Send the datagram message out through the established datagram connection.
Construct a receive datagram object with a pre-allocated buffer.
Wait to receive the message through the established connection using the allocated datagram buffer.
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.