Java Reference
In-Depth Information
Table 10-1. Optional Connection Types
Type
Interface
Example
SocketConnection
socket://jonathanknudsen.com:79
Socket
ServerSocketConnection
socket://:129
Server socket
SecureConnection
ssl://jonathanknudsen.com:79
TLS or SSL socket
CommConnection
comm:com0;baudrate=19200
Serial port
Responding to Incoming Connections
You may be used to thinking of mobile phones as client devices, but they may be full-fledged
networked citizens, with the ability to receive incoming network connections. Although
ServerSocketConnection provides the ability to listen for incoming socket connections, it can
only be active while a MIDlet is actually running.
A typical server loop, listening for incoming socket connections on port 80, looks some-
thing like this:
ServerSocketConnection ssc;
ssc = (ServerSocketConnection)Connector.open("socket://:80");
boolean trucking = true;
while (trucking) {
SocketConnection sc = (SocketConnection)ssc.acceptAndOpen();
// Handle the client connection sc.
}
MIDP allows MIDlets to be launched in response to incoming network connections. The
name for this technique is push . You could, in theory, create a web server MIDlet, although in
practice a mobile phone is probably a poor platform for a web server. A more likely example
would be an SMS MIDlet, something built using JSR 120, the Wireless Messaging API. Assuming the
MIDlet was configured correctly, incoming SMS messages would cause the MIDlet to be
launched to handle the connection.
A MIDlet may register for push connections in two ways: it can register at runtime using
static methods in javax.microedition.io.PushRegistry , or it can register at install time using
special entries in the application descriptor (JAD file). The important thing to remember is that
the push registry has a lifetime beyond your MIDlet (in fact, even beyond multiple device
reboot cycles). It is part of the MIDlet management software that runs on the device. When a
MIDlet registers for push notifications, the device software is obligated to listen for incoming
network connections and launch your MIDlet if the appropriate connection is made.
Inside your MIDlet, you don't have to do anything different to catch the incoming connec-
tion. All you do is call Connector.open() with the appropriate network listening string.
Let's say, for example, that you had created a web server in a MIDlet and called it PatchyMIDlet .
(The source code for this topic, available from http://www.apress.com/ , includes PatchyMIDlet ;
it sends a randomly selected text message in response to incoming requests.) This MIDlet
responds to incoming socket connections on port 80 (the default HTTP port). If you wanted to
register the MIDlet at runtime, you'd do this in the code somewhere:
 
Search WWH ::




Custom Search