Chapter 4. Wireless Standards: How Data Goes To And Fro

IN THIS CHAPTER

Micro Java is a pretty advanced beast. However, J2ME would not have been possible without older mobile technologies. J2ME is built atop and within other standards that relegate such things as network communication, voice communication, data transfer, and text display.

These standards are often used in creating Micro Java games. For example, a multiplayer game will often involve players being matched up and chatting in a sort of lobby. This lobby may not be written in Java at all, but rather in a simpler text protocol such as WAP. Other games may want to send out standard mobile messages, or even call up special voice numbers.

The standards we will look at in this chapter include the following:

In Chapter 5, “Let's Talk: Instant Wireless Messaging,” and Chapter 6, “Wireless in Asia: i-mode and cHTML,” we'll go on to discuss other major standards, such as SMS Instant Messages and Japan's popular i-mode service.

Wireless Networks

It would be overkill, in a book about Micro Java games, to delve into too much detail about all the various types of wireless networks currently available. However, when designing micro games, it is essential to know not only your target hardware platform, but also the makeup of the networks you plan to support.

Multiplayer game developers, in particular, must understand a little about the networks that their games run upon in order to design servers that can accommodate them.

First Generation (1G)

When people talk about the first generation of wireless networks, they are usually referring to the analog voice-centric systems of the 1980's.

The most popular types of these networks include Advanced Mobile Phone Services (AMPS) and NMT.

Although the wireless world could never have gotten off the ground without analog technology, these were very primitive systems relative to today's standards, limited in both functionality and capacity.

Second Generation (2G)

Second generation networks are digital and circuit-switched. In a circuit-switched network, Phone A will find a free physical path to Phone B. This path then becomes dedicated to these phones, and is kept free from outside interference for the duration of the phones' connection.

Because all data that goes across the network is compressed into bits and bytes, the networks can support better voice quality without static, deal with a higher capacity of callers, require less power, and offer global roaming.

More importantly, the data sent over 2G networks does not have to be voice at all. Short messages or other electronic data—such as game moves—are perfectly valid.

While the data rates of 2G networks are usually good enough to support voice communications, full back-and-forth Internet access is still extremely slow (on the order of 9.6Kbps).

Briefly, here's a description of the major wireless 2G wireless networks around the world:

  • Code Division Multiple Access (CDMA)—This technology uses digital encoding and special routines to divide a given chunk of the radio spectrum into different slots. This technique allows many people to share the same radio channel. Existing CDMA systems can handle data speeds from 9.6Kbps to 14.4Kbps. In the United States, Sprint PCS and Verizon Wireless run on CDMA networks.

  • Time Division Multiple Access (TDMA)—This was the first digital standard in the United States, beginning in 1993. TDMA divides a radio channel into time slots, each of which is a fraction of a second long, and allocates different phone calls within each slot. In the United States, Cingular is the largest TDMA carrier.

  • Global System for Mobile Communications (GSM)—This is the first digital standard developed in Europe, and a variant of TDMA. Different versions of this operate anywhere from the 900MHz to 1.9GHz frequency radio bands. GSM allows mobile phone users to roam across different networks, so that the same phone can work in more than 170 different countries. The data speeds can reach 9.6Kbps. In the Unites States, VoiceStream Wireless is one of the biggest GSM carriers.

  • Personal Digital Cellular (PDC)—A Japanese standard based on TDMA. PDC operates in the 800Mhz and 1500MHz bands.

  • Integrated Digital Enhanced Network (iDEN)—This network, created by Motorola in 1994, works on the 800MHz, 900Mhz, and 1.5GHz bands. It is based on TDMA and allows for more walkie-talkie–like functionality, such as dispatching, as well as paging, data, and fax. In the United States, Nextel is the largest iDEN carrier.

Second (and a Half) Generation (2.5G)

GSM technologies have been enhanced to create an expanded set of standards called the General Packet Radio Services (GPRS), specially designed to work with the Internet and multimedia services such as music and video. This network is optimized for data speeds ranging from 114Kbps to 170Kbps, and will support roaming.

The biggest difference with this new packet-switched system is that cell phones are always online and connected. Users are typically charged depending on how much data is actually shipped back and forth. The system also allows voice calls to be made simultaneously to data transfer.

Because the network is packet-switched, a physical connection is not held and dedicated between two phones. Rather, network packets are routed as quickly as possible across logical paths. This also allows the same data to easily and efficiently be shared among many users at the same time.

The idea with GPRS is to take standard GSM service and transition it into third generation systems such as UMTS (see the next section). In fact, GPRS is sometimes referred to as GSM-IP, since it is a more robust version of GSM based on Internet Protocols (IPs).

Third Generation (3G)

We are now entering the era of 3G. Third generation systems are intended to serve high-speed Internet data, complex teleconferencing, flicker-free video, and CD-quality music. Data speeds are designed to range from 144Kbps to 2Mbps (megabits per second).

Some of the major standards supporting 3G networks include the following:

  • Wideband Code Division Multiple Access (W-CDMA)—W-CDMA is mostly used in Japan. NTT DoCoMo's brand name for 3G services is Freedom of Mobile Multimedia Access (FOMA).

  • Universal Mobile Telecoms Network (UMTS)—A standard deployed throughout Europe.

  • International Mobile Telecommunications 2000 (IMT 2000) —A global standard created by the International Telecommunication Union.

  • Code Division Multiple Access 2000 (CDMA 2000)—This is a radio transmission technology bringing narrowband CDMA into the third generation.

The Wireless Application Protocol (WAP)

URL: http://www.wapforum.org

The Wireless Application Protocol (WAP) is a set of standards based on the Internet Protocols (IP) and the Extensible Markup Language (XML). WAP is an open and global standard for wireless applications. WAP was designed to operate seamlessly over CMDA, CDPD, and all other major wireless network types.

WAP's primary technology—the Wireless Markup Language (WML)—is based on HDML and was developed by Unwired Planet (which became Phone.com and is now Openwave), Motorola, Nokia, and Ericsson. These companies and others have formed an open organization devoted to WAP called the WAP Forum.

WAP content is accessed using standard Uniform Resource Locators (URLs), just as Web pages are. Pages written in WML have the .WML extension, just as most HTML pages end with .HTML.

NOTE

Most modern mobile phones support some version of WAP. Many phones come preloaded with the Openwave (Phone.com) Mobile Browser.

The following section is not intended to be a full WAP primer. Rather, it will provide a brief overview of most WML tags and attributes, allowing you to create simple WAP structures in which to support your Micro Java games.

The WAP Protocol Stack

The protocols that make up WAP are based strongly on the Internet Protocols. The Web protocol stack includes old favorites such as HTML, HTTP, SSL, UDP/IP, and TCP/IP. This is a very robust and efficient suite of protocols, to be sure. However, the Web stack itself is quite large, and provides more functionality than most mobile phones need.

Because of this, a special WAP protocol stack was created. The stack includes, in order

  • An application layer—The actual application used to display things to the user. This uses the Wireless Application Environment (WAE) displaying pages written with WML.

  • A session layer—How connections are made. This layer uses the Wireless Session Protocol (WSP).

  • A transaction layer—How data is divided. This layer uses the Wireless Transaction Protocol (WTP).

  • A security layer—Encrypts the data. This layer uses Wireless Transport Layer Security (WTLS).

  • A datagram layer—How the data is packaged and sent across the network. This is done using the Wireless Datagram Protocol (WDP). The WDP can use different bearers, such as CDPD, SMS, and so on.

Wireless carriers and cell phone manufacturers need to worry about implementing all these protocols properly. Lowly game developers need only focus on writing the actual applications using WML and WMLScript.

WAP Architecture

A WAP browser works very similarly to a Web browser, and a WAP server works similarly to a Web server. As in the Web world, the client requests a page from a server. The server then responds with the page data. There is no continual connection. If the server has more data to send to the client, then another client request must first be made.

In the world of WAP, a phone is known as a user agent. In fact, most WAP pages come to the phone from a standard Web server, directed through a special server called a WAP gateway.

Figure 4.1 shows the typical WAP architecture.

The WAP architecture.

Figure 4.1. The WAP architecture.

Gateway machines are typically housed and maintained by wireless service providers. The process works as follows:

  1. A mobile phone user asks for a specific URL.

  2. The request is sent over a proprietary wireless network, using WAP protocols, to a gateway machine.

  3. The gateway translates the request to HTTP and sends it to a standard Web server.

  4. The Web server will grab or dynamically generate the content (usually a WML document) and send this response back to the gateway.

  5. The gateway encodes the WML and WMLScript into byte code and sends it to the phone.

  6. The phone processes the byte code and displays the first card to the user.

This process, shown in Figure 4.2, allows a Sprint PCS game player and a Verizon Wireless user to communicate via a central Web server even though they are using different wireless networks.

The WAP process.

Figure 4.2. The WAP process.

The Wireless Markup Language (WML)

The Wireless Markup Language is very similar, in concept, to the Hyper Text Markup Language (HTML) used to create most Web pages. Obviously, a rich HTML Web site with snazzy animations, tons of colors, and fantastic music won't look quite so snazzy on a postage-stamp-sized black and white screen. WML was built to address the typical mobile phone's limitations:

  • The screen is 20 or fewer characters across, and only three to six lines tall. As such, WML needs only very basic text formatting and layout abilities.

  • Most phones have only a small amount of memory and rudimentary processor power. As such, the object model of how WMLScript can dynamically access a WML deck is vastly simplified.

  • Typically, a phone only has only a numeric keypad. As such, all of WML's input methods are basic edit fields and option selections. Nothing that might rely on mouse or keyboard input is supported.

  • Data transfer rates are extremely slow, which means latency is extremely high. As such, WML applications are not sent as separate pages requiring many separate requests and responses, but as one big deck separated into individual cards.

  • Bandwidth, or the amount of data that can be uploaded or downloaded per second, is extremely limited. WML and WMLScript are usually compressed into tight runnable byte code, which means that a heavy WML file doesn't need to be parsed on the phone, but rather on the gateway server.

WML is currently released as version 1.3. However, most phones only support WML 1.1. The WML tags in this chapter should work with WAP 1.1 browsers and up.

There is also an almost-complete WAP 2.0 specification, which we will discuss later in this chapter.

WML Basics

Every WML file must begin with a standard prologue, including an XML header and a document definition tag:

<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
    "http://www.wapforum.org/DTD/wml_1.1.xml">

WARNING

Since WML is based on XML, it is case sensitive—every tag and attribute should be in lowercase. Also, tags cannot be nested incorrectly. For example, the following line is illegal and will generate errors:

<p><b>Hello!</p></b>

The rest of the code must be surrounded by <WML> and </WML>.

A Game of Cards and Decks

In the world of the desktop Internet browser, there are Web sites and Web pages. On a mobile phone, there are decks and cards.

A card is a screen that a user sees and can interact with. There can only be one card visible at a time. There is no notion of various windows that can be moved around, minimized, or maximized. Each card is surrounded by the tags:

<CARD id="id" title"title">

and

</CARD>

The id attribute refers to the name of the card. This name must be a single word with no spaces or wacky characters. Every card in a deck must have a different id name.

The title attribute is a short description of the card, and is usually displayed at the top of the mobile phone's screen. Each card must have at least one paragraph in it, as designated by the tags <P> and </P>.

NOTE

Some WAP phones do not show the card title at all, so don't rely on it being there.

A deck is a set of cards. When your mobile phone downloads a WML file, it is getting an entire deck. The first card in the deck is activated. Later cards can then be activated using their id as the user selects various menu or other options.

A deck must begin with

<DECK>

and end with

</DECK>

So, taking all these rules together, the world's simplest WML file might look like this:

<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
    "http://www.wapforum.org/DTD/wml_1.1.xml">
<wml>
<card id="main" title="Welcome!">
<p>
Wow! This is one of the world's most simple WML files!
</p>
</card>
<card id="second" title="Second Page">
<p>
Wow! The second card!
</p>
</card>
</wml>

On a phone, the above file would appear as in Figure 4.3. Note that the menu command line is automatically inserted as part of the WAP browser.

A simple WML file.

Figure 4.3. A simple WML file.

Anchors Away

You can use anchors to go from one card to another, or to actually load a new deck from the server. Anchor text or images will be hypertext, and will usually appear underlined. Players will be allowed to select this hypertext using the up/down/left/right keys on their mobile phones.

The <anchor> tag contains inner tags:

  • <go href=”deck.wml#card”>Click Here</go>—. Loads a new WML deck and brings up a specific card. If you omit the # symbol in the href attribute, then the first card in the given deck will be brought up.

    Likewise, if you omit the deck name completely and only use the # symbol, then you can jump to a card within the currently active deck.

    The <go> tag is similar to the <A> hyperlink tag in HTML. It allows you to send a request to the server, asking for a specific URL.

    Note that the <go> tag can also contain a special tag called <postfield> that allows you to post parameters to the Web server:

    <postfield name="myparameter" value="myvalue"/>
    
  • <prev/>—. Goes to the previously loaded WML card.

  • <refresh>Click Here</refresh>—. Reloads the current card.

  • <noop/>—. No operation. This does nothing at all. This is usually done to show a command that is currently disabled.

So, to switch to a new card in a deck

<anchor>
  Select here to bring up a new card
  from the current deck
  <go href="#card2"/>
</anchor>

To switch to a new deck entirely

<anchor>
  Select here to bring up a new deck
  <go href="test.wml"/>
</anchor>

Most requests will return a new WML document. The WML document can be static, or created dynamically by a CGI script, Java servlet, JSP, ASP, or other server-side technology.

For example, a request to a Java servlet might look like this:

<go href="myservlet.jsp?c=getNewWMLPage"/>

The <refresh/> tag allows you to change certain variables and then reload the same or a different card:

<anchor>
  Select here to refresh variable x
  <go href="test.wml"/>
  <refresh>
   <setvar name="x" value="30"/>
  </refresh>
</anchor>

Note that you can also use the <a> tag, similar to HTML, which is the same as using the <anchor> and <go> combination:

<a href="#newcard">Select here to bring up a new card.</a>

Or

<a href="deck.wml">Select here to bring up a new deck.</a>

Text Formatting Tags

Since a mobile phone doesn't have a lot of room or a wide variety of colors and fonts, only a few tags are actually supported in WML.

The most popular tags for formatting text include the following:

  • <br/>—. Used to add a line break. Because this tag stands alone and has no closing tag, it must contain a slash.

  • <p>My Paragraph</p>—. Separates chunks of text into paragraphs.

  • <strong>I am mighty</strong>—. Used to make text stronger (usually the same as making text bold).

  • <em>Emphasize me, baby!</em>—. Used to emphasize text (usually the same as italicizing).

  • <b>I am bold</b>—. Used to make text bold.

  • <i>I am italic</i>—. Used to make text italicized.

  • <u>I am underlined</u>—. Used to underline text.

  • <small>Wee little me</small>—. Makes text smaller.

  • <large>Big bad me</large>—. Makes text larger.

So the following code might appear as in Figure 4.4:

<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
"http://www.wapforum.org/DTD/wml_1.1.xml">
<wml>
<card title="Sample Formatting">
<p>
Hello<br/>
<b>I'm bold</b><br/>
<i>I'm italic</i><br/>
<u>I'm underlined</u><br/>
<big>I'm big</big><br/>
<small>I'm small</small>
</p>
</card>
</wml>
Some formatted text.

Figure 4.4. Some formatted text.

Be aware that some phones do not support many of these tags. For example, an older WAP browser may only allow paragraph breaks and line breaks, but no bolding, italicizing, or underlining.

NOTE

You can add a comment to a WML file using the same comment tags that work in HTML:

<!—A funny little comment—>

Tables

Although using tables is discouraged because there's usually not enough room for them, standard table tags are supported similarly to HTML.

You surround your table with

<table columns=5 rows=5>

and

</table>

You can create rows and columns using the following tags:

  • <tr>Row</tr>—. Surrounds a given row of text.

  • <td>Column</td>—. Creates a given column.

The following code creates a small two-by-two column table:

<table columns="3">
<tr>
<td>Top Left</td>
<td>Top Right</td>
</tr>
<tr>
<td>Bottom Left</td>
<td>Bottom Right</td>
</tr>
</table>

For example:

Top Left Top Right
Bottom Left Bottom Right

User Input Tags

The user input controls will look different on every phone you use. You can use many of the same input elements that you'll find in an HTML form.

Input Fields

Typically, a user input field is an empty box in which a person can type in a number, word, or phrase. Because typing on a cell phone is usually an arduous task, many phones will bring up a special screen when an input field is selected.

You can create a standard input field named "test" as follows:

<input name="test"/>

An input field possesses several attributes:

  • name—. The name of the field, which will become a variable name you can access later or send to the server.

  • emptyok—. Set to true if the text field can be left blank. By default this is set to false.

  • maxlength—. The maximum length of characters that a user can enter.

  • size—. The width of the field, indicated in number of characters.

  • title—. Sets a title for the input field. This will be displayed on some phones when the user is inside this field.

  • type—. Sets the type of input field. By default this is text, but you might also have a password type of field. In password fields, anything the user enters usually appears as an asterisk, for added security.

  • value—. Sets the default value for this input field.

  • format—. The type of data that can be entered in the field. The default is *M. The types are as follows:

    A—Uppercase alphabetic characters

    a—Lowercase alphabetic characters

    N—Numeric characters

    X—Uppercase characters of any type

    x—Lowercase characters of any type

    M—All characters

    Precede any of the these types with an asterisk to indicate that any number of characters can be entered.

    Precede any of the these types with a specific number from 1 to 9 to specify that the user must enter a specific amount of the given character type.

So, to create a 10 character-wide input field that must be numeric and can contain only 10 characters, you would use the following:

<input name="test" size="10" maxlength="10" format="*N"/>

Option Groups

You can create a pull-down option list by surrounding the list with the <optgroup> and </optgroup> tags, and surrounding each individual option using the <option> and </option> tags:

<optgroup title="A Test">
 <option value ="first">First Option</option>
 <option value ="second">Second Option</option>
</optgroup>

Each option tag can take several attributes, such as:

  • value—. Sets the value for the option that will be dumped into the variable, should the option be selected.

  • onpick—. This attribute takes a URL or anchor card name as a parameter. If the given option is selected, then the given URL is requested.

Check Boxes and Radio Buttons

To create check boxes, you can use the <select multiple="true"> tag. Check boxes are a list of options preceded by boxes, and any number of the boxes can be selected or unselected.

Set the multiple attribute to false to create radio buttons. Radio buttons show the user several options. Only one of the options can be selected. If a new option is selected, then any previous selections are automatically unselected.

Other attributes for the <select> tag include:

  • name—. Name of the variable that will hold any selected value.

  • value—. Set the default value of the variable to be set.

  • iname—. Name of the initial variable that will hold the initial value.

  • ivalue—. Sets the initial value for the option that will be dumped into the variable, indicated by the option group's name.

So, the following would be used to create a simple list of radio buttons:

<select multiple="false" name="mychoices">
  <option value="choice1">First Choice</option>
  <option value="choice2">Second Choice</option>
  <option value="choice3">Third Choice</option>
</select>

This might appear as shown in Figure 4.5.

A group of radio buttons.

Figure 4.5. A group of radio buttons.

Field Sets

Finally, you can visibly group the buttons together into a sort of set. To do so, simply surround elements inside your user input forms with

<fieldset title="My Title">

and

</fieldset>

This can help group check boxes or radio buttons.

Example

So, taking all this together, you can make a form as in Figure 4.6 using the following WML file:

<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
"http://www.wapforum.org/DTD/wml_1.1.xml">
<wml>
<card title="My Input Form">
<p>
Name: <input name="Name" size="10"/><br/>

<fieldset title="A Field">
<select multiple="true">
<option value="a">A</option>
<option value="b">B</option>
</select>
</fieldset>
</p>
</card>
</wml>
Some user input fields.

Figure 4.6. Some user input fields.

The <do> Tag

The <do> tag lets the user perform some sort of global command or other task on the current card. The command will usually appear in the soft-key menus at the bottom of the mobile phone's display. Most phones allow for two soft keys. If you create more than two <do> options, then one of the soft-key commands will usually become Menu, which will lead to a special menu of additional choices. The label attribute is the label for the command that will be shown to the user.

The name attribute creates a variable name for the element.

The type attribute lets you choose what sort of command you wish to create. Various browsers will display these commands in different ways. Usually, up to two commands can be shown on the screen, mapped to the mobile phone's two command buttons. Other phones may display the commands in a nested menu, or along with a special icon.

The following are some valid <do> command types:

  • accept—. Acknowledgement of a message or event.

  • prev—. Navigate back to a previous deck.

  • help—. Help about this card.

  • reset—. Reset the WAP browser.

  • options—. A selection from a list of options.

  • delete—. Delete an item or choice.

  • unknown—. A special type, not one of the preceding types.

To perform an action, simply surround it with the <do> and </do> tags. To jump to a card in the current deck named card2, you could use

<do type="accept" label="OK!">
  <go href="#card2"/>
</do>

The following command will add a back command to the current card, allowing you to go to the previously loaded card:

<do type="prev" label="Back">
  <prev/>
</do>

Variables

WML files are capable of keeping track of and changing simple variables. This lets your WML application keep information between cards.

To explicitly set the variable i to 10, use the <setvar> tag:

<setvar name="i" value="10"/>

Whenever you create an input element, the results are stored as variables. Simply use the name of the element preceded by a dollar sign. You can surround the variable name by parentheses to separate it from any other text.

So, to create a small application that asks the user for their name and then displays it, you could use the following code:

<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
"http://www.wapforum.org/DTD/wml_1.1.xml">

<wml>
 <card id="input">
<input name="myname" size="10"/>
<select input="Name:">
</select>
<do type="accept" label="OK!">
  <go href="#result"/>
</do>
</card>

<card id="result">
<p>Your name is: $(myname)</p>
</card>
</wml>

The name is input in the first card (with the id of input). Then the card with the id result is called, as soon as the OK! button is pressed. The result is then displayed.

Images

As with HTML, WML does support an <img> tag:

<img src="me.wbmp"/ alt="Me">

The resultant image might appear as in Figure 4.7.

A beautiful WAP image.

Figure 4.7. A beautiful WAP image.

The src attribute points to an image in the WBMP format. This format is a special, tiny black-and-white bitmap created to fit snugly on wireless devices.

NOTE

The WAP 2.0 specification proposes the use of color images.

The alt attribute lets you substitute a word or phrase instead of an image, for phones or WAP browsers that do not support images.

There are several tools and plug-ins available at the following Web sites that allow you to convert GIF or BMP images to the WBMP format:

Timers

When using WAP, the connection between a mobile phone and the server does not remain persistent between requests. If the server needs to send an update to the client, it has no way to do so until the client explicitly requests a new deck.

Many games and other time-sensitive applications will need to constantly poll the server, asking for any new updates. This can be done using a simple WML timer.

Set the ontimer attribute of the <card> tag to point to the WML page you wish to update. You can then use the <timer value="10"/> tag to create the countdown, setting the value in tenths of a second.

To refresh the WML document every three seconds, simply use the following:

<card ontimer="test.wml">
<timer value="30"/>
<p>Some Message</p>
</card>

WMLScript

If you've followed along so far, you've noticed that WML has very limited interactivity on the client side. Really, all you can do is display simple text and images, collect a little information via user input forms, and send it all to the server to process.

Just as HTML has JavaScript (based on the ECMAScript standard), some WML browsers support a special client-side scripting language called WMLScript. WMLScript is a much simpler subset of ECMAScript. In addition, WMLScript is compiled into bytecode by the WAP gateway before being sent down to the phone.

WARNING

Many WAP Browsers do not support WMLScript. Be sure to research your target platform before relying on any client-side scripting. Check out the excellent table at http://www.allnetdevices.com/faq/useragents.php3 to determine what version of WAP your target device supports.

WMLScript is used, for the most part, to verify user input before wasting precious time sending it to the server. For example, if you ask your game player for his age, a simple WMLScript can be sure the input is indeed a number, isn't negative, and isn't over 200. If the results aren't valid, a dialog box can pop up telling the player to enter a new number.

In addition, some versions of WMLScript allow you to access special features of the user agent, such as the following:

  • Dialog boxes to alert the user of something or to request input

  • Make phone calls

  • Access the SIM card

  • Access or change the address book

  • Configure the phone preferences

Accessing WML Script

WMLScript files are stored separately from WML files. They usually have the .wmls extension.

You can access a WMLScript file's WML the same way you would request any other document:

<go href="test.wmls"/>

You can access specific external functions within WMLScript using the hash symbol. This allows you to pass in variables. For example, the following file requests a variable called myvar and then passes it to the process() function within a WMLScript file:

<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
"http://www.wapforum.org/DTD/wml_1.1.xml">
<wml>
<card id="Input" title="Request Variable">
<do type="options" label="Go">
<go href="test.wmls#process('myvar')"/>
</do>
<p>
Type something here:
<input type="text" name="myvar"/>
</p>
</card>
</wml>

WMLScript Example

You can make a simple guessing game entirely on the client side using WMLScript. For example, you can create a dialog box that asks the user for a random number.

A function will pick a random number and compare it the user's guess, and show a card indicating whether the user was correct.

The following is the code for GuessNumber.wml:

<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
"http://www.WAPforum.org/DTD/wml_1.1.xml">
<wml>

<card id="guess">
   <p>
   Guessing a Random Number...
   </p>
   <do type="accept">
      <go href="RandomGuess.wmls#guessrandom()" />
   </do>
</card>

<card id="right">
<p>
 You were right!
 Number was $(randresult)<br/>
</p>
</card>

<card id="wrong">
<p>
 Sorry. Wrong!
 Number was $(randresult)<br/>
</p>
</card>
</wml>

Here's the code for RandomGuess.wmls:

extern function guessrandom()
{
   // Request a number, 0 by default
   var thenum = 0;
   // Loop until a valid number is picked.
   do
   {
     var r = Dialogs.prompt("Pick a number between 1 and 10", "0");
     thenum = Lang.parseInt(r);
   }
   while (thenum < 1 || thenum > 10)

   var randnum = Lang.random(10)+1;
   // set the randresult variable
   WMLBrowser.setVar("randresult", randnum);

   if (randnum == thenum)
     WMLBrowser.go("GuessNumber.wml#right");
   else
     WMLBrowser.go("GuessNumber.wml#wrong");
} ;

The guessrandom() function is preceded by the extern modifier, meaning that it can be accessed by external WML or WMLScript documents.

Note that the variable randnum is a script variable, and can only be set and accessed within this WMLScript function.

The randresult variable, however, is set using WMLScript's setVar() method, meaning it will be an active browser variable—active and accessible as long as the player is visiting the current WAP site.

Server-Side WAP

Most any Web server can serve out WML pages. You will, however, need to modify your server using the instructions given in this section.

Server Configuration

Every response your Web server sends to a browser is tagged with a special header. One of the most important lines of the header tells the browser what the content-type of the document is. This content-type is expressed using a standard known as the Multipurpose Internet Mail Extension (MIME).

The MIME type of HTML files, for example, is text/html. For WAP documents, you need to add several new MIME types to allow for WML files, WML script files, compiled WML files, and WBMP wireless bitmaps:

  • text/vnd.wap.wml

  • application/vnd.wap.wmlc

  • text/vnd.wap.wmlscript

  • application/vnd.wap.wmlscriptc

  • image/vnd.wap.wbmp

Most Web servers make it easy to add new MIME types. Many servers have a

httpd.conf file in which these types can be added.

WAP and Java

Although some WAP pages will never change and can be written using a standard text editor or HTML authoring tool, most WAP games and game tools will involve lots of dynamic information such as game state, scores, number of users in a lobby, chat messages, and so on.

That means that the Web server will need to generate WML decks and cards on-the-fly. Server-side Java technologies, such as JavaServer Pages (JSPs) and Java Servlets, are a great way to pump out the necessary WML.

A Servlet Game Lobby

For example, here's a simple servlet that can allow an unlimited number of players to chat with each other. This can lead up to a full-featured lobby where players can match up and then be joined together to play Java games.

The WAP need only call the servlet with one parameter:

mymessage

The servlet will take that message and return the last five lines of chat.

This is obviously a very simplified version of a game lobby. A real lobby would force users to log in with a password, keep track of the user's name, keep track of which chat lines each user has already seen, match players together, and kick off game sessions.

The SimpleChatServlet.java file looks like this, and is shown in Figure 4.8:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SimpleChatServlet extends HttpServlet {

    // Store last five messages
    private static String message[] = new String[5];

    public void init() throws ServletException
    {
        // Set messages to blank for now
    for (int i=0; i < 5; i++)
       message[i] = "";
    }

    public void doGet(HttpServletRequest request,HttpServletResponse response)
      throws ServletException,IOException
    {
      // set content type as wap.wml
      response.setContentType("text/vnd.wap.wml");

      // create a print writer output
      PrintWriter out = response.getWriter();
      // get the latest message, if any
      String mymsg = request.getParameter("mymessage");

      // If the message isn't null, add it to the top of the queue
      if (mymsg != null)
      {
    for (int i=4; i > 0; i—)
        {
           // Replace message with previous message
       message[i] = message[i-1];
        }
        message[0] = mymsg;
      }

      // write the data
      out.println("<?xml version="1.0"?>");
      out.println("<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"");
      out.println(" "http://www.wapforum.org/DTD/wml_1.1.xml">");
      out.println("<wml>");
      out.println("<card title="Chatting">");

      // Send any new messages back to this servlet
      out.println("<do type="accept" label="Send">");
      out.println(" <go href="/servlet/SimpleChatServlet" method="get">");
      out.println("  <postfield name="mymessage" value="$mymsg"/>");
      out.println(" </go>");
      out.println("</do>");

      out.println(" <p>");
      // print out the last five messages
      for (int i=0; i < 5; i++)
      {
    out.println(message[i]+"<br/>");
      }
      out.println("</p>");

      // Request a new chat message
      out.println("<p>");
      out.println("Chat: <input title="Enter Chat Message" name="mymsg"/>");
      out.println("<br/>");
      out.println("</p>");
      out.println("</card>");
      out.println("</wml>");
  }
}
A WAP chat application using a servlet.

Figure 4.8. A WAP chat application using a servlet.

Any WML card that requests this servlet will send its own chat message and retrieve the last five messages that have been sent. Effectively, this servlet will pump out a WML file that looks like the following:

<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
 "http://www.wapforum.org/DTD/wml_1.1.xml">
<wml>
<card title="Chatting">
<do type="accept" label="Send">
<go href="/servlet/SimpleChatServlet" method="get">
<postfield name="mymessage" value="$mymsg"/>
</go>
</do>
<p>
Message 1<br/>
Message 2<br/>
Message 3<br/>
Message 4<br/>
Message 5<br/>
</p>
<p>
Chat: <input title="Enter Chat Message" name="mymsg"/>
<br/>
</p>
</card>
</wml>

Using JavaServer Pages (JSPs)

Similarly, JavaServer Pages (JSPs) can be used to dynamically create cards, using variables that can be created programmatically.

Here's a simple example:

<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
"http://www.wapforum.org/DTD/wml_1.1.xml">

<%
response.setContentType("text/vnd.wap.wml");
out.println("<wml>");
out.println("<card title="Today's Date">");
out.println(" <p align="center">");
out.println("Date: "+ new java.util.Date());
out.println(" </p>");
out.println("</card>");
out.println("</wml>");
%>

Development Environment

To develop WAP applications, you can use a number of different environments. Every major cell phone manufacturer offers a software development kit that allows you to create and emulate their precise WAP environment.

More information can be found at these sites:

Handheld Device Markup Language (HDML)

URL: http://www.w3.org/TR/NOTE-Submission-HDML.html

HDML is a format extremely similar to WML. Like WAP's main presentation layer protocol, it is a simplified version of HTML specially designed to work well with mobile phones.

NOTE

HDML was developed by Unwired Planet (which became Phone.com and now is owned by Openwave) before WAP came about. Some of the older phones in the United States support HDML, but the language is rapidly being phased out in favor of the more robust WML. As such, we won't concentrate on it much in this book.

HDML is based strictly on existing Web standards and protocols. In addition to defining how a cell phone screen can be visually presented and laid out, HDML has elements defining the navigation between various screens.

Some differences between WML and HDML are the following:

  • WML is based on XML. This means that people can use many popular XML authoring and parsing tools to create and deal with XML. For example, the eXtensible Style Sheet Language and associated Translations (XSL/XSLT) provide an easy way of taking the same content, putting it in XML, and popping it out as either HTML or WML.

  • Since HDML is not based on XML, you can be a lot sloppier. You can use upper or lower case tags, nest tags, and you don't need to have a closing tag for every opening tag.

  • HDML does not have a related DTD (Document Type Definition). That means you can't run an HDML document through a validator to make sure everything is in the proper format.

  • HDML does not have any form of client-side scripting.

  • HDML does not have timers.

  • HDML does not have multiple-choice selection lists. However, HDML does allow you to add custom images to labels and choice groups, such as checkboxes and radio buttons.

  • HDML has built-in bookmark functionality. Some WAP browsers offer bookmarks, but they are not part of the main specification.

  • HDML offers nested activities—a convenient way of organizing your application's commands.

  • HDML lets you set up mobile-originated pre-fetch of documents. This means you can pre-load your entire application and graphics. The user has a longer download time up front, but everything runs much more responsively afterwards.

  • HDML offers key accelerators for links. That means that you can specify exactly which keys on the mobile phone's keypad will be associated with which action.

HDML Syntax

All HDML files start with

<HDML VERSION=3.0>

The Version value, of course, depends on the version of HDML you are writing. The document ends with

</HDML>

Displays

Just like WML, HDML documents contain many screens (decks) and each screen can be shown to the mobile phone user (as a card). In HDML, however, cards are called displays and indicated using the <DISPLAY> tag.

Each display can be given a NAME attribute.

Activities

Every command that a user carries out is known as an activity. Each activity might have sub-activites. When you use the "GO" task under an <ACTION> tag, you are performing an activity.

For example, in a game lobby, the main activities might be to Join a Game or Chat. The Join a Game activity might have sub-activites such as Pick Game Name or Pick Opponents. Each step in an activity usually has its own HDML card.

You can use special attributes to indicate how the application behaves as the user navigates back and forth or cancels various tasks. You can even create sub-activities using the GOSUB attribute, to help group specific activities together under another activity.

Actions

If you don't assign an activity to a key, then it will have a default activity assigned to it. For example

The <ACTION> tag is the way you can request user input. A special command will be shown to the user.

The TYPE attribute determines what type of action you're talking about. There are several action types:

  • ACCEPT—. A standard acknowledgement of a message or event. By default, this displays the previous card.

  • HELP—. By default, this shows a message that no help is currently available.

  • PREV—. By default, this action shows the previous card. If there is no previous card, the current activity is canceled.

  • SOFT1—. The first softkey is pressed.

  • SOFT2—. The second softkey is pressed.

  • SEND—. Something is being sent.

  • DELETE—. Usually used in text-entry fields. This action deletes the character to the left of the cursor.

Set the LABEL attribute to display a specific command to the user. What happens after the user selects that command depends on the value of the TASK and DEST attribute.

The most common TASK is GO, which means you want to jump to another document or card. DEST points to the desired destination. This can be another HDML file, or a card within the current document.

So, to go from card one to card two

<HDML VERSION="3.0">
 <DISPLAY>
  <ACTION LABEL="Hit Me" TYPE=ACCEPT TASK="GO" DEST="#card2">
    This is card one!
  </DISPLAY>
  <DISPLAY NAME="card2">
    And this is card two!
  </DISPLAY>
</HDML>

Other TASK values include the following:

  • GO—. Request a specific URL or card, along with the DEST attribute.

  • GOSUB—. Just like GO, this will request a specific URL. However, a new activity is pushed on the browser stack, which means the browser can keep track of where you're going and where you've come from. This makes it easy to cancel out or go backwards logically.

  • PREV—. Shows the previous card.

  • RETURN—. Return from a GOSUB nested activity to the previous activity.

  • CANCEL—. Cancels the current activity.

  • CALL—. Changes the phone to voice mode and actually dials the number specified by the NUMBER attribute.

  • NOOP—. Do nothing. A way to show a command but “disable” it.

Hyperlinks

HDML allows you to create hyperlinks. However, there is no HREF attribute. Instead, you use DEST:

<A TASK="GO" DEST="test.hdml" LABEL="Hit Me" ACCESSKEY="1">

Images

Finally, images can be dropped into HDML documents using the <IMG> tag:

<IMG SRC="myimage" ALT="Neat Image">

Most HDML browsers, such as UP.Link, support 1-bit images in the BMP format. Images that are too large for the display will be cropped, and images that aren't valid will not be shown at all.

WAP 2.0 and xHTML Basic

URL: http://www.w3.org/TR/xhtml1/

The future of wireless markup languages appears to be xHTML Basic. All of the big wireless players are helping to craft the xHTML specification: Sun, Ericsson, Panasonic, Microsoft, Openwave (inventor of HDML and one of the main proponents of WAP), Access Co. (representing iMode's cHTML), and The World Wide Web Consortium (W3C).

The second version of WAP is based on xHTML. So what is it? The xHTML specification simply involves taking the whole kahuna of HTML version 4.01 and redefining it as a pure XML language. The beauty of xHTML is that today's Web browsers can instantly support and display it.

As with today's HTML, the content and layout of all the elements can be created in HTML, and the presentation look and feel can be specified using cascading style sheets (CSS).

What that means is that tomorrow's wireless languages will be an exact subset of major HTML and CSS tags and commands. This will make it much easier to define exactly how a mobile phone's content should look. Theoretically, phones will support slick interfaces, animation, pop-up menus, and lots and lots of color. It'll also make it really easy to create applications that work on both the Web and wireless browsers.

NOTE

WAP 2.0 and i-mode's cHTML (discussed in Chapter 6) seem to be converging into xHTML. Openwave, the leading provider of mobile phone browsers, has announced that it will be supporting xHTML in upcoming releases.

Summary

In this chapter, we covered the gamut of wireless technologies that exist today, as well as those being used to build the 3G systems of tomorrow. In Chapter 5, we'll focus in on instant messaging, one of the most popular wireless data offerings.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.122.68