Java Reference
In-Depth Information
Communicating with Sockets and Datagrams
Although the vast majority of networked mobile applications likely use HTTP to fulfill
their communications needs, some applications may still need raw socket or datagram
facilities. This includes utilities for system administrators, instant messaging clients, and
novel applications of these protocols to games or multimedia applications.
Unfortunately, support for these facilities—usually implemented over TCP for
sockets and UDP for datagrams—is not available on all devices. As Table 12-2 shows,
MIDP 2.0 optionally provides support for socket communication, while all Java ME
platforms may provide support for datagram communication. Consequently, as you
establish the business case for your application, you should consider the availability of
these protocols and do some research to determine precisely which devices will sup-
port your application, and if there are enough devices in the hands of your target
market to justify your development expense. If not, you may want to consider tunnel-
ing your data communications over another protocol such as HTTP.
Tip Resources such as the Java ME Device Table at http://developers.sun.com/mobility/
device/device and the WURFL device description repository at http://wurfl.sourceforge.net can
help you determine which devices support socket or datagram communications.
Using Sockets with the GCF
Socket programming with the GCF is easy: construct a URL to the destination of the
socket, and open it using Connector . Assuming everything goes your way—the path to the
server is available and the server is running—you can then obtain streams to perform
input and output on the connection established by the device.
When opening a socket connection, Connector.open returns an instance of
SocketConnection , which implements StreamConnection . For most socket-oriented pro-
gramming, using a StreamConnection is sufficient, as shown in Listing 12-2.
Listing 12-2. Using a StreamConnection
String url = "socket://nowhere.com:7";
StreamConnection c = null;
InputStream s = null;
OutputStream o = null;
byte[12] b;
 
Search WWH ::




Custom Search