Escolar Documentos
Profissional Documentos
Cultura Documentos
Chapter 06
Networking
In this section, we will be studying how to implement network-enabled MIDlets.
At the end of the lesson, the student should be able to:
Describe the Generic Connection Framework and how it can be used to support
6.1.1
J.E.D.I.
6.1.2
J.E.D.I.
In MIDP 2.0, only the "http" and "https" schemes are required to be implemented by the
device.
HTTP stands for HyperText Transfer Protocol. It is the protocol used to transfer web pages
from web servers (eg. www.sun.com) to web browsers. The client (web browser) requests
for a web page by specifying the path with the "GET" or "POST" commands.
For the "GET" method, parameters are specified and embedded on the URL. For example,
to pass a variable with a name "id" and value 100 to "index.jsp", the URL is specified as:
"http://hostname/index.jsp?id=100". Additional parameters are separated by an
ampersand (&), "http://hostname/index.jsp?id=100&page=2".
When the "POST" method is used, parameters are not part of the URL but are sent on
separate lines after the POST command.
J.E.D.I.
HTTP Server
<html>
<head>
<title>Test Page</title>
</head>
<body>
<h1 align="center">Test Page</h1>
</body>
</html>
Figure 2: Example of HTTP GET transaction
J.E.D.I.
HTTP Server
<html><head><title>Apache Tomcat/5.5.7
Error report</title><style>...
6.2.2
You can open an HTTP connection by using Connector.open() and casting it with any one
of these three interfaces: StreamConnection, ContentConnection and HTTPConnection.
However, with the StreamConnection and ContentConnection, you cannot specify and
derive HTTP specific parameters and results.
When you use a StreamConnection, the length of the reply cannot be determined
beforehand. With a ContentConnection or an HTTPConnection, there is a way to determine
the length of the reply. But the length is not always available, so your program should be
able to fall back to other means of getting the reply without pre-knowledge of the content
length.
import javax.microedition.io.*;
HttpConnection connection = null;
InputStream iStream = null;
byte[] data = null;
try {
connection = (HttpConnection) Connector.open("http://www.sun.com/");
int code = connection.getResponseCode();
switch (code){
J.E.D.I.
case HttpConnection.HTTP_OK:
iStream = connection.openInputStream();
int length = (int) connection.getLength();
if (length > 0){
data = new byte[length];
int totalBytes = 0;
int bytesRead = 0;
while ((totalBytes < length) && (bytesRead > 0)) {
bytesRead = iStream.read(
data, totalBytes, length - totalBytes);
if (bytesRead > 0){
totalBytes += bytesRead;
}
}
} else {
// length is not unknown, read per character
...
}
break;
default:
break;
}
...
6.2.3
Sometimes the server redirects the browser/client to another web page by replying with
HTTP_MOVED_PERM (301), HTTP_MOVED_TEMP (302), HTTP_SEE_OTHER (303) or
HTTP_TEMP_REDIRECT (307) instead of the usual HTTP_OK reply. Your program must be
able to detect this using getResponseCode(), get the new URI from the header using
getHeaderField( "Location" ), and retrieve the document from this new location.
int code = connection.getResponseCode();
switch(code){
case HttpConnection.HTTP_MOVED_PERM:
case HttpConnection.HTTP_MOVED_TEMP:
case HttpConnection.HTTP_SEE_OTHER:
case HttpConnection.HTTP_TEMP_REDIRECT:
String newUrl = conn.getHeaderField("Location");
...
J.E.D.I.
import javax.microedition.io.*;
HttpsConnection connection = null;
InputStream iStream = null;
byte[] data = null;
try {
connection = (HttpsConnection) Connector.open("https://www.sun.com/");
int code = connection.getResponseCode();
...
} catch (CertificateException ce){
switch (ce.getReason()){
case CertificateException.EXPIRED:
...
}
}
J.E.D.I.
J.E.D.I.
the same format as it was sent, with no omissions or insertions (barring any extreme
circumstances such as the recipient getting disconnected from the network).
The TCP layer handles packet reassembly and retransmission transparently. For example,
the HTTP protocol does not have to worry about packet disassembly and assembly because
this would be handled by the TCP layer.
Sometimes, the size of the message is too small and very inefficient to be delivered as a
single packet (packet overhead is very high compared to the payload). Imagine many
packets traversing the network with one byte payload and multi-byte overhead (say 16
bytes). This would make the network very inefficient as many packets flood the network
with only one byte of payload.
In these cases, the TCP implementation may wait for succeeding messages to be sent. It
would then pack as many messages as possible to a packet before sending the packet
away. If this happens, there would be additional lag or latency in the connection. If your
application requires that there should be as little latency as possible, you should set the
DELAY socket option to zero. Or, if your application can live with lost packets or unordered
packets, you may want to try a UDP or Datagram connection. UDP connections also uses
less packet overhead.
SocketConnection conn =
(SocketConnection) Connector.open("socket://www.sun.com:80");
client.setSocketOption(DELAY, 0);
InputStream iStream = conn.openInputStream();
OutputStream oStream = conn.openOutputStream();
os.write("GET / HTTP/1.0\n\n".getBytes());
int c = 0;
while((c = is.read()) != -1) {
// process the recieved data
...
}
iStream.close();
oStream.close();
conn.close();
ServerSocketConnection conn =
(ServerSocketConnection) Connector.open("socket://:8889");
// listen for a connection from a client
SocketConnection client = (SocketConnection) conn.acceptAndOpen();
client.setSocketOption(DELAY, 0);
J.E.D.I.
6.6 Datagrams
TCP Socket connections are reliable. In contrast, delivery of UDP packets are not
guaranteed. There is no guarantee that a packet sent using datagram connection would
be received by the peer. The order in which the packets are received is also unreliable.
The order in which packets are sent may not be the same order in which it will be received.
UDP Datagrams or packets are used when the application can operate even when a packet
is lost or packets are not delivered in order.
String url;
try {
if (isServer){
// start as server, listen at port 8888
url = "datagram://:8888";
} else {
// start as client, connect to port 8888 of host "localhost"
url = "datagram://localhost:8888";
}
dc = (DatagramConnection) Connector.open(url);
while (true) {
Datagram dgram = dc.newDatagram(128);
dc.receive(dgram);
if (isServer){
// started as server, get connection address
// for our message sending process
url = dgram.getAddress();
}
if (dgram.getLength() > 0){
String mesg =
new String(dgram.getData(), 0, dgram.getLength()));
}
}
10
J.E.D.I.
}
catch (IOException ioe) {}
catch (Exception e) {}
...
dc.send(dgram);
} catch (Exception ioe) {}
}
6.7 Exercises
6.7.1
URL Fetcher
Create a MIDlet that prompts for an HTTP url. It would then fetch the url using the GET
method and display these connection/content properties (if available): Response Code,
Response Message, Length, Type, Encoding, Expiration and Last Modified Date.
11
J.E.D.I.
12