Your SlideShare is downloading. ×
MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking
MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking
MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking
MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking
MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking
MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking
MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking
MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking
MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking
MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking
MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking
MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking
MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking
MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking
MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking
MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking

100

Published on

MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking

MELJUN CORTES Jedi course notes mobile application devt-lesson06-networking

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
100
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. J.E.D.I. NetworkingIn 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 different connection methods • Specify connection parameters using the GCF URL addressing format • Create HTTP/HTTPS connections • Create MIDlets using TCP sockets and UDP datagrams1 The Generic Connection FrameworkThe Generic Connection Framework supports both packet-based (Sockets) and stream-based (Datagrams) connections. As the name implies, this framework provides the basicAPI for connections in CLDC. This framework provides a common foundation forconnections like HTTP, Sockets and Datagrams. Even Bluetooth and Serial I/O have aplace in this foundation. The GCF provides a generic and common set of API thatabstracts all types of connections. It should be noted that not all connection types arerequired to be implemented by the MIDP devices.1.1 The GCF Interface HierarchyThe extensible interface hierarchy of the GCF makes generalization possible. Newconnection types may be added into this framework by extending this hierarchy.Mobile Application Development 1
  • 2. J.E.D.I. Figure 1: GCF Interface HierarchyMobile Application Development 2
  • 3. J.E.D.I.1.2 The GCF Connection URLConnection parameters are specified using a common addressing format:scheme://username:password@host:port/path;parameters1. scheme is the protocol or connection method. Example of scheme are: http, ftp, https2. username is optional, but if specified, an @ must precede the host3. password is optional and can only be specified if username is present. If password is specified, it must be separated from the username by a colon (:)4. host – this parameter is required. This can be a hostname or a fully qualified domain name (FQDN) or the IP address of the target host.5. Port – This parameter is optional. If not specified, the default port for the scheme will be used.6. Path7. parameters – this is optional, but must be preceded by a semi-colon when presentIf we use square brackets to enclose optional parameters in this addressing format, wecan express it as:scheme://[username[:password]@]host[:port]/path[;parameters]The Uniform Resource Indicator (URI) as defined in RFC 2396 is the basis for thisaddressing format.In MIDP 2.0, only the "http" and "https" schemes are required to be implemented by thedevice.Mobile Application Development 3
  • 4. J.E.D.I.2 HTTP Connection2.1 The HTTP ProtocolHTTP stands for HyperText Transfer Protocol. It is the protocol used to transfer webpages 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 specifiedas: "http://hostname/index.jsp?id=100". Additional parameters are separated by anampersand (&), "http://hostname/index.jsp?id=100&page=2".When the "POST" method is used, parameters are not part of the URL but are sent onseparate lines after the POST command.Mobile Application Development 4
  • 5. J.E.D.I. Client / Web Browser HTTP ServerGET /index.jsp?id=100 HTTP/1.1 HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Content-Type: text/html;charset=ISO-8859-1 Date: Wed, 18 Jun 2005 14:09:31 GMT Connection: close <html> <head> <title>Test Page</title> </head> <body> <h1 align="center">Test Page</h1> </body> </html> Figure 2: Example of HTTP GET transactionMobile Application Development 5
  • 6. J.E.D.I. Client / Web Browser HTTP ServerGET /non-existent.html HTTP/1.0 HTTP/1.1 404 /non-existent.html Server: Apache-Coyote/1.1 Content-Type: text/html;charset=utf-8 Content-Length: 983 Date: Mon, 11 Jul 2005 13:21:01 GMT Connection: close <html><head><title>Apache Tomcat/5.5.7 - Error report</title><style>... <body><h1>HTTP Status 404</h1> ... The requested resource (non-existent.html) is not available. ... </body></html> Figure 3: Example of an HTTP GET transaction with an error response2.2 Creating an HTTP ConnectionYou can open an HTTP connection by using Connector.open() and casting it with any oneof these three interfaces: StreamConnection, ContentConnection and HTTPConnection.However, with the StreamConnection and ContentConnection, you cannot specify andderive HTTP specific parameters and results.When you use a StreamConnection, the length of the reply cannot be determinedbeforehand. With a ContentConnection or an HTTPConnection, there is a way todetermine the length of the reply. But the length is not always available, so yourprogram 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();Mobile Application Development 6
  • 7. J.E.D.I. switch (code){ 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; }...2.3 Handling HTTP RedirectsSometimes the server redirects the browser/client to another web page by replying withHTTP_MOVED_PERM (301), HTTP_MOVED_TEMP (302), HTTP_SEE_OTHER (303) orHTTP_TEMP_REDIRECT (307) instead of the usual HTTP_OK reply. Your program must beable to detect this using getResponseCose(), get the new URI from the header usinggetHeaderField( "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:Mobile Application Development 7
  • 8. J.E.D.I. case HttpConnection.HTTP_TEMP_REDIRECT: String newUrl = conn.getHeaderField("Location");...Mobile Application Development 8
  • 9. J.E.D.I.3 HTTPS ConnectionHTTPS is HTTP on top of a secure transport connection. Opening an HTTPS connection issimilar to opening an HTTP connection. Then only difference is the URL passed toConnector.open() and casting the result to an HttpsConnection class variable.An additional type of exception may also be thrown by Connector.open() aside fromIllegalArgumentException, ConnectionNotFoundException, java.io.IOExceptionand SecurityException. A CertificateException may be reported back caused bycertificate failures.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: ... }}Mobile Application Development 9
  • 10. J.E.D.I. static byte BAD_EXTENSIONS Indicates a certificate has unrecognized critical extensions. static byte BROKEN_CHAIN Indicates a certificate in a chain was not issued by the next authority in the chain. static byte CERTIFICATE_CHAIN_TOO_LONG Indicates the server certificate chain exceeds the length allowed by an issuers policy. static byte EXPIRED Indicates a certificate is expired. static byte INAPPROPRIATE_KEY_USAGE Indicates a certificate public key has been used in way deemed inappropriate by the issuer. static byte MISSING_SIGNATURE Indicates a certificate object does not contain a signature. static byte NOT_YET_VALID Indicates a certificate is not yet valid. static byte ROOT_CA_EXPIRED Indicates the root CAs public key is expired. static byte SITENAME_MISMATCH Indicates a certificate does not contain the correct site name. static byte UNAUTHORIZED_INTERMEDIATE_CA Indicates an intermediate certificate in the chain does not have the authority to be a intermediate CA. static byte UNRECOGNIZED_ISSUER Indicates a certificate was issued by an unrecognized entity. static byte UNSUPPORTED_PUBLIC_KEY_TYPE Indicates that type of the public key in a certificate is not supported by the device. static byte UNSUPPORTED_SIGALG Indicates a certificate was signed using an unsupported algorithm. static byte VERIFICATION_FAILED Indicates a certificate failed verification. Figure 4: Reasons for a CertificateException (excerpt from MIDP 2.0 Specification - JSR 118)Mobile Application Development 10
  • 11. J.E.D.I.4 TCP SocketsMost implementations of HTTP ride on top of the TCP layer. If you send data using theTCP layer, it will be divided into smaller pieces called packets. The TCP layer guaranteesthat all packets sent by the sender are received by the recipient, in the same order as itwas sent. If a packet was not received by the recipient, it would be resent. This meansthat once you send a message, you can rest assured that it will be delivered to thereceipient in the same format as it was sent, with no omissions or insertions (barring anyextreme circumstances such as the recipient getting disconnected from the network).The TCP layer handles packet reassembly and retransmission transparently. Forexample, the HTTP protocol does not have to worry about packet disassembly andassembly 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 asingle packet (packet overhead is very high compared to the payload). Imagine manypackets traversing the network with one byte payload and multi-byte overhead (say 16bytes). This would make the network very inefficient as many packets flood the networkwith only one byte of payload.In these cases, the TCP implementation may wait for succeeding messages to be sent. Itwould then pack as many messages as possible to a packet before sending the packetaway. If this happens, there would be additional lag or latency in the connection. If yourapplication requires that there should be as little latency as possible, you should set theDELAY socket option to zero. Or, if your application can live with lost packets orunordered packets, you may want to try a UDP or Datagram connection. UDPconnections 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.0nn".getBytes());int c = 0;while((c = is.read()) != -1) { // process the recieved data ...}iStream.close();oStream.close();conn.close();Mobile Application Development 11
  • 12. J.E.D.I.5 Server SocketsIn the Client-Server model, the server continually waits for a connection from a client ona certain agreed upon port number. We also use the Connector.open method to create aserver socket. The url passed to open() is of the same format as a TCP Socket, with thehostname left blank (eg. socket://:8899).ServerSocketConnection conn = (ServerSocketConnection) Connector.open("socket://:8889");// listen for a connection from a clientSocketConnection client = (SocketConnection) conn.acceptAndOpen();client.setSocketOption(DELAY, 0);InputStream iStream = client.openInputStream();OutputStream oStream = client.openOutputStream();// read/write to input/output streams...is.close();os.close();client.close();server.close();Mobile Application Development 12
  • 13. J.E.D.I.6 DatagramsTCP Socket connections are reliable. In contrast, delivery of UDP packets are notguaranteed. There is no guarantee that a packet sent using datagram connection wouldbe 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 bereceived.UDP Datagrams or packets are used when the application can operate even when apacket 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())); } }}catch (IOException ioe) {}catch (Exception e) {}Mobile Application Development 13
  • 14. J.E.D.I....private void sendMesg(String line){ try { byte[] bytes = line.getBytes(); Datagram dgram = null; dgram = dc.newDatagram(bytes, bytes.length, url); dc.send(dgram); } catch (Exception ioe) {}}Mobile Application Development 14
  • 15. J.E.D.I.7 Exercises7.1 URL FetcherCreate a MIDlet that prompts for an HTTP url. It would then fetch the url using the GETmethod and display these connection/content properties (if available): Reponse Code,Response Message, Length, Type, Encoding, Expiration and Last Modified Date.Mobile Application Development 15
  • 16. J.E.D.I.Mobile Application Development 16

×