Network with J2ME

xiaoxiao2021-03-06  126

[Reprinted to IBM DeveloperWorks] Content: J2ME I / O Network: Overview Connection Framework J2ME URL Processes a Currency Exchange Application Conclusion Get Java Network Application on Small Device Soma Ghosh (Sghosh@ntigo.com) application development Personnel, Entigo 2002 In December 2002 If you have been paying attention to Soma Ghosh's article in the wireless zone, you already know how to use your Java skills to build a simple application for handheld devices. Then how do you connect those devices to the outside world? In this article, GHOSH discussed the Javax.microedition.IO class and Java.IO class in J2ME networking. You will learn how J2ME applications handle URL and accept input, this article also takes you to complete a sample program, this program downloads the currency exchange information to the network accessible and follows the J2ME. J2ME I / O and Network: Overview Java 2 platform, Pocket Edition (Java 2 Platform, Micro Edition (J2ME) provides networking features available on the network to mobile space. It is possible to get real-time stock quotes or the latest loan exchange rates in mobile phones or palms. The networked features of the Mobile Information Framework (MIDP) in javax.microedition.IO, MIDP is a platform for developing mobile device applications. (To learn more about MIDP, please visit the following reference section, link to the article I have previously published on this topic on developerWorks.) On the other hand, java.io package provides input / output to MIDP (Input / Output (I / O)) function. Its individual classes and interfaces provide system input and output for data streams. This J2ME package is a subset of Java 2 platform, standard version (Java 2 Platform, Standard Edition (J2SE)) java.io package, which handles low-level data I / O. The most critical aspect of J2ME network connectivity is the communication between the mobile device and the web server. This kind of communication is essentially a client / server mechanism, with mobile devices act as a web client's role and capacity to establish an interface with enterprise systems, databases, corporate internal networks and Internet. J2ME networking activities can be divided into many types in accordance with the communication protocol. We will discuss each category in the following sections. This category of low-level IP networks involves sockets, datagrams, serial ports, and file I / O communications. Communication based on socket follows the connected TCP / IP protocol. On the other hand, the data report-based communication follows the unconnected UDP / IP protocol. UDP provides the application with a method of sending a packaged original IP datagram that does not have to establish a connection. The connection-oriented protocol requires the source address and destination address, which is different from this, and the datagram only needs the destination address. Below is a URI: DataGram: //: 1234 here is a Datagram: //: 1234 This is a URI that the datagram connection is used to send the datagram to the server in a certain port. : 1234 Low level IP networking can also handle file I / O and allow MIDlet to register to network access to local serial ports. Security Networks in Security Network J2ME involves some additional interfaces provided to securely communicate with web-based network services. These security interfaces are provided by HTTPS and SSL / TLS protocols on IP networks.

The HTTP networking mobile device and the web server are communicating based on HTTP (Hypertext Transfer Protocol, Hypertext Transfer Protocol). HTTP is a connection-oriented request-response (REQEST-RESPONSE) protocol, in which each parameter must be set before sending requests. Figure 1 illustrates the communication mechanism between the mobile device and the web server. Figure 1. The connection mechanism connection framework J2ME network is intended to process the wide spectrum of mobile devices. At the same time, the networked system must be devices. In order to cope with these requirements, the J2ME network introduces the concept of the General Connection Framework. The idea of ​​the general connection framework is to define some universal abstraction of the network and file I / O in the form of a Java interface. This architecture has widely supported various handheld devices, and the actual implementation of these interfaces is left to each device manufacturer. Equipment manufacturers can select which interface to implement in its specific MIDP according to the actual functionality of its device. The general aspects defined by the Java interface are divided into the following forms of basic communication type: Basic Serial Enter (Downloaded by Javax.microedition.io.InputConnection) Basic Serial Output (Defined by javax.microedition.io.outputConnection) Data Communication (defined by javax.microedition.io.DataGramConnection) Socket communication notification mechanism for client-server (Client-Server) (by javax.microedition.io.StreamConnectionNotifier definition) Basic HTTP communication with the web server (Defined by javax.microedition.io.httpConnection) The URL process in the J2ME processes the URL process involves opening a connection from the mobile device to the web server and processes data I / O between the mobile device to the web server. This process occurs in the following stage: setup, this is not established to the server connection. The mobile device prepares a bunch of request parameters and is ready to accept and explain the subsequent response. Connected, at which point the connection has been established, the request parameter has been sent and is expected to respond. Closed (closed), at which point the connection has been turned off. J2ME defines the Javax.microedition.io.Connector class, which contains each static (STIC) method for creating all connection objects. This task is done by dynamically identifying a class based on the protocol of the platform name and the requested connection. In URL processing, Connector.Open () is used to open the URL; it returns an HTTPConnection object. The string parameter of the Connector.Open () method is a valid URL. The URL string differs depending on the communication protocol. The following list 1 is demonstrated in Listing 5.

Listing 1. Calling HTTP-based communication conne = connector.open ("http://www.yahoo.com"); Listing 2. Calling stream-based socket communication Connection conn = connector.open ("Socket: / / localhost: 9000 "); Listing 3. Calling a datagram based socket communication connection conn = connector.open (" DataGram: //: 9000 "); Listing 4. Call serial communication connection conn = connector.open (" Comm: 0; baudrate = 9000 "); Listing 5. Call file I / O communication Connection conn = connector.open (" file: //myfile.dat "); connection can also accept access mode (value) For the READ, WRITE, and READ_WRITE and one sign used to indicate the caller to get the timeout notification. In a secure network, when the https: // Connection string is accessed, Connector.Open () returns httpsconnection. When the SSL: / / Connection string is accessed, Connector.Open () will return SecureConnection. No matter which type of URL is used, call connector.Open () opens a stream of byte input from the Connection to Java.Io.inputStream. This method uses to read each character of the file, always read the end of the file (marked with -1). If an exception is thrown, the connection and flow will be turned off. Similarly, in order to perform output, Java.io.OutputStream representing byte output stream will be opened from Connection. InputStream and OutputStream are corresponding to java.io.DataInputStream and Java.io.DataoutputStream. DataInputStream allows the application to read the basic Java data type from the underlying input stream from the underlying manner. Java.io.DataOutputStream allows applications to write basic Java data types to output streams in portable ways. Listing 6 illustrates how to use HTTPConnection from the URL input data.

Listing 6. HttpConnection input data from the URL String getViaHttpConnection (String url) throws IOException {HttpConnection c = null; InputStream is = null; StringBuffer str = new StringBuffer (); try {c = (HttpConnection) Connector.open (url); // Getting the InputStream will open the connection // and read the HTTP headers They are stored until // requested is = c.openInputStream ();.. // Get the length and process the data int len ​​= (int) c. GetLength (); int Ch; while ((ch = is.read ())! = -1) {str.append ((char) ch);}} finally {if (is! = null) Is.Close () IF (c! = Null) c.close ();} A looan exchange application we will explain the concepts outlined so far through a loan currency exchange application, which will display the US dollar (US Dollar) , USD) and the latest exchange rate between the British Pound, GBP. This app also displays information related to the current date and current time. The UI of this application consists of a form (Form) and an exit command that embeds the StringItem representing a string that only the string is displayed, and the exit command is used to complete the call to exit. Once the application is started, the URL request is ready. Basic currency symbols are provided to the request. Next, we need to open a mobile device and the URL connection between the web server. Open an HTTPConnection and create an InputStream for the data input. The data obtained is a character stream that is attached to the string. The resulting String represents the HTML output. Since the browser on our mobile device cannot display HTML, we will parse the HTML String to get currency values ​​and any related information. Our program will search for a specific mode in the HTML String, namedGBP. Once the location of this mode is determined, the search finds the decimal value. When the position of the decimal point is obtained, each numeric value will be retrieved and arranged in an appropriate order, thereby acquiring the currency value. Listing 7 illustrates how to obtain a currency value.

Listing 7. Retrieving currency value string retval = ""; int dec = 0; int index = str.indexof ("USDGBP"); if (index! = -1) Str = str.substring (index, str.length () ); IF ((DEC = str .indexof ("))! = -1) && (! (Str.ndswith ("))) && character.isdigit (str.charat (dec.Charat (DEC 1)) ) {String front = ""; int found = DEC-1; while (character.isdigit (str.charat (find))) {front = str.charat (find); find-;} RetVal = new stringbuffer (Front) .reverse (). Tostring (); RetVal = "; String back =" "; int bind = dec 4; while (character.isdigit (str.charat (bind))) {back = Str.Charat (bind); bind-;} RetVal = new stringbuffer () .Reverse (). TOSTRING ();} Related information is also obtained by looking for some specific string modes. Once the location of the data is in the HTML String, an offset will be applied to obtain the date and time. This information is attached to the string mode originally used for search. Listing 8 illustrates how to obtain relevant information. Listing 8. Search related information // get the time of currency Exchange and research information int todayIndex = str.indexof ("US Markets Closed."); String Rettime = ""; if (TimeIndex! = -1) {Rettime = STR .substring (TimeIndex-34, TimeIndex); Rettime = "US Markets Closed";} Listing 9 includes all code for currency exchange applications.

Listing 9. Complete currency exchange example import javax.microedition.midlet. *; Import javax.microedition.lcdui. *; Import javax.microedition.io. *; Import java.io. *; Import java.lang. *; Import java.lang. *; Import java.lang. *; Import java.lang. *; Import java.lang. *; Import java.lang. *; Import java.util *;. // A first MIDlet with simple text and a few commands.public class CurrencyExchange extends MIDlet implements CommandListener {// The exit commands private Command exitCommand; // The display for this MIDlet private Display display; form displayform; public CurrencyExchange () {display = Display.getDisplay (this); exitCommand = new Command ( "Exit", Command.SCREEN, 1);} // Start the MIDlet by creating the form and // associating the exit command and listener. public void startApp () {displayform = new form ( "Exchange Rate"); displayform.addCommand (exitCommand); displayform.setCommandListener (this); try {String result = getViaHttpConnection ( "http://finance.yahoo.com/m5 ? a = 1 & S = USD & T = GBP "); DisplayForm.Append (" result);} catch (Exception EXC) {EXC.PrintStackTrace (); DISPLAY.SETCURRENT (Displas yform);} // Pause is a no-op because there is no background // activities or record stores to be closed public void pauseApp () {} // Destroy must cleanup everything not handled // by the garbage collector /.. / In this case there is nothing to cleanup. public void destroyApp (boolean unconditional) {} // Respond to commands. Here we are only implementing // the exit command. In the exit command, cleanup and // notify that the MIDlet has BEEN DESTROYED. PUBLIC VOID COMMANDACTION (Command C, Displayable S) {if (c == exitcommand) {destroyApp (false); notifyDestroyed ();

}}}} String Parse (String Str) {// Get The Time of Currency Exchange and Related Information Int TimeIndex = Str.Indexof ("US Markets Closed."); String Rettime = ""; if (TimeIndex! = -1) { Rettime = Str.Substring (TimeIndex-34, TimeIndex); Rettime = "US Markets Closed";} String Retval = ""; INT DEC = 0; int index = str.indexof ("USDGBP"); if (INDEX! = -1) Str = str.substring (index, str.length ()); if (((DEC = str.indexof ("))! = -1) && (! (Str.endswith (". " ))) && character.isdigit (Str.Charat (DEC 1))) {string front = ""; int Find = DEC-1; while (character.isdigit (str.charat (find)) {front = Str.Charat (Find); Find-;} retval = new stringbuffer (front) .reverse (). TOSTRING (); RetVal = "; string back ="; int bind = dec 4; while (Character.Indigit (str.charat (bind))) {back = str.charat (bind); bind-;} RetVal = new stringbuffer (back) .Reverse (). Tostring ();} system.out .println (retval); Return "USD / GBP" RETVAL "AT" rettime;} Strin g getViaHttpConnection (String url) throws IOException {HttpConnection c = null; InputStream is = null; StringBuffer str = new StringBuffer (); try {c = (HttpConnection) Connector.open (url); // Get the ContentType String type = c .gettype (); // getting the input // and read the http headers. The Http headers. The http headers.. IS =

转载请注明原文地址:https://www.9cbs.com/read-101959.html

New Post(0)