Using Datagram Connections

Team-Fly

In this section, I'll briefly describe datagram connections. Although support for datagrams is not mandated by the MIDP specification, certain device implementations may choose to support datagram connections. Unlike stream-oriented connections, datagram connections are connectionless. This means that you can fire packets of data around the network, but you have no guarantee that they will reach their destination in the right order, or that they will even arrive at all.

Datagram communications is based on two interfaces in the javax.microedition.io package, DatagramConnection and Datagram. Figure 8-4 shows the methods in DatagramConnection.

click to expand
Figure 8-4: The DatagramConnection interface

The first step is to use the generic connection framework to obtain a DatagramConnection-something like this:

 String url = "datagram://jonathanknudsen.com:7999"; DatagramConnection dc = (DatagramConnection)Connector.open(url); 

The URL string passed to Connector's open() method contains both the host name and port of the opposite end of the datagram connection. If datagram connections are not supported by a MIDP implementation, an exception will be thrown from the open() method.

All data is exchanged using Datagrams. To send a datagram, first ask the DatagramConnection to create one for you using one of the newDatagram() methods. Then write some data into it and pass it into the send() method of DatagramConnection. Receiving a datagram is almost as easy. You just call receive(), which blocks until a datagram is received.

In essence, Datagram is a wrapper for an array of bytes that are the payload of the datagram. You can retrieve a reference to this byte array by calling getData(). Keep in mind, however, that the data for the Datagram may be only a subset of the data in the array. You can find the array offset and length of the actual data by calling getOffset() and getLength().

Interestingly, Datagram is an extension of both the DataInput and DataOutput interfaces, so it's possible to read and write data in a Datagram as though it were a stream.


Team-Fly


Wireless Java. Developing with J2ME
ColdFusion MX Professional Projects
ISBN: 1590590775
EAN: 2147483647
Year: 2000
Pages: 129

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net