Server Side Development for Smart Clients, Game Developmentdtipper/2727/2727_Slides8.pdf · Server...
Transcript of Server Side Development for Smart Clients, Game Developmentdtipper/2727/2727_Slides8.pdf · Server...
1
Server Side Development for Smart Server Side Development for Smart Clients, Game DevelopmentClients, Game Development
David TipperAssociate ProfessorAssociate Professor
Department of Information Science and Telecommunications
University of Pittsburgh
[email protected]@tele.pitt.eduhttp://www.sis.pitt.edu/~dtipper/2727.html
Slides 7Slides 7
Infsci 1073/Telcom 27272
Smart Client Architecture•Custom software executes on Devices•Components:
• Smart clients• Synchronization server• data/content source• may include proxies or gateways
WWANInternet
WirelessGateway
Base Station
Synchronizationserver
SmartClients
EnterpriseData Sources
Wired connection
2
Infsci 1073/Telcom 27273
Platform Independence• Rather than develop multiple versions of the same
application for various platforms strive for platform independence
• Primary Tools– Sun’s Java 2 Micro Edition (J2ME)
• Run java apps on a java virtual machine (JVM)
– Microsoft .NET Compact Framework (.NET CF)• Run on Microsoft’s Common Language Runtime (CLR) platform
Infsci 1073/Telcom 27274
Distributed Application Architectures
• 1-Tier Architecture– All the layers are tightly integrated
• 2-Tier Architecture– The presentation layer and some or
all of the business logic is spread across to the clients
– Server becomes more or less just a database server
• N-Tier Architecture– The Presentation layer is located on
the client device– The Business Logic layer on a shared
computer (application server)– The data access layer on a database
server
PresentationLayer
Business LogicLayer
Data Access Layer
3
Infsci 1073/Telcom 27275
J2ME/MIDP Client
2-Tier Architecture
• User interface and business logic is bound to an individual application on the device
• Thin Client vs. Fat Client– How large the business logic is
embedded in the client device
Server
Presentation Layer(MIDlet UI)
Business Logic Layer(MIDlet engine)
Data Access Layer
Pros:• Applications are easy and relatively
inexpensive to develop• Performance is reasonable good
Cons• Parts of applications on clients might be
very complex and expensive to maintain• Low reusability
Infsci 1073/Telcom 27276
3-Tier Architecture
• Business logic at the application server has a dual role:– Act as a server towards client
devices– Act as a client towards the
database server J2ME/MIDP Client
Application Server
Presentation Layer(MIDlet UI)
Business Logic Layer(MIDlet engine)
Database Server
Data Access Layer
Business Logic Layer
Pros:• Decoupling layer implementation• Codes are easy to upgrade• High reusability• Easy to enhance with security, load
balancing, etc.Cons
• Complex implementation• May degrade the performance for a
simple application
4
Infsci 1073/Telcom 27277
Server Side Development
• Issues related to server side development relate to – Tier model– Managing code to client– Synchronization– Data management updates up/down
• Two platforms– Microsoft .NET for .NET CF C# applications– Sun Java platform (J2EE) for J2ME apps
Infsci 1073/Telcom 27278
Java Server Side Development
• Servlet: Standard are Java 2 programs which run on the server.
● MIDlet: The application, a MIDlet, was designed for the Mobile Information Device Profile, one of the J2ME specifications.
● The MIDlets can connect to servlets using http/GCF as discussed earlier. Servlet implement server side functionality (ex, available seats in movie theatre)
● Servlets developed in standard J2SE or J2EE environment using development tools like Tomcat, Netbeans, etc.
5
Infsci 1073/Telcom 27279
J2ME to J2EE Overview
• Data persistence possible on the client, server or both– Client MIDP Record Management System (RMS) APIs
allows for data storage that is persistent on the device• HTTP provides the bridge between J2ME (MIDP) and
the J2EE Platform– Both Platforms use HTTP/HTTPS (MIDP 1.0.3)– MIDP supports HTTP 1.1 and APIs for generating GET,
POST, and HEAD requests• Messages may tunnel through different protocols that
are transparent to the client and server• MIDlet can send any Message Format in the body of
a HTTP request– XML, Text, binary, …– Mime-types are used to indicate body format/type
Infsci 1073/Telcom 272710
HTTP
• Originally designed for transferring raw data, such as Web pages, across the Internet
• Ideal Client/Server Communication protocol for mobile Java applications.– High compatibility and portability– Firewall Friendly
6
Infsci 1073/Telcom 272711
MIDlet-Servlet Communication Through HTTP
• HTTP Get– The input values are sent as part
of the URL in the QUERY_STRING environment variable.
Easy to developo Support only texto Limit in length
• HTTP Post– Data is sent to the server as an
input stream independently from the URL, and its length is saved in the CONTENT_LENGTH environment variable.
Data volume is not constrainedSupport binary data
o May not be efficient
Infsci 1073/Telcom 272712
HTTP Get vs. HTTP Post
<form action="http://www.somesite.com/cgi-bin/getgrade.cgi" method="GET"> Student#: <input type="text" name="idnum" size=30> <input type="submit">
</form>
123333Student#:
Submit
http://www.somesite.com/cgi-bin/gergrade.cgi?idnum=123333
<form action="http://www.somesite.com/cgi-bin/getgrade.cgi" method=“POST"> Student#: <input type="text" name="idnum" size=30> <input type="submit">
</form>
http://www.somesite.com/cgi-bin/gergrade.cgi
idnum=123333
7
Infsci 1073/Telcom 272713
J2ME to J2EE
Areas to Consider for J2ME to J2EE Communications• Session: Sequence of service requests by single user
using a client to access server• State: Information maintained in the session across
requests. Ex: Contents of Shopping Cart• Personalization data: Information about the user, such
as address, SSN, etc… This information does not normally change from session to session, thus a J2ME application should use it to enhance the user’s experience.
Infsci 1073/Telcom 272714
J2ME to J2EE
Managing Session States for MIDlet to J2EE Communications• HTTP is a stateless protocol. The Java Servlet API provides a
HTTPSession object to work around this limitation • J2EE App Servers use 3 methods to maintain integrity of HTTP
Sessions:– Using Cookies– Using URL Rewriting– Using HTTPS
• MIDP Devices can use all these 3 methodsManaging Personalization Data for MIDlets• Session Management may be transient• Personalization data by nature is Persistent • Major benefit of utilizing Personalization is fewer interaction for the
user
8
Infsci 1073/Telcom 272715
J2ME Connection Types
• HTTP/HTTPS– Very simple to use
• XML over HTTP/HTTPS– Beginning to be a viable choice due to varying
parsers available• Model
– Creates an object representation of a document in memory (e.g., DOM)
• Push– Parses through an entire document, spitting out events to
registered listeners • Pull
– Parses a little at a time, returning a single element or tag
Infsci 1073/Telcom 272716
Wireless Web Services APIs (1)• J2ME Web Services (JSR 172)
– J2ME Web Services specification goals• Access remote SOAP/XML based web services
– Does not support web service hosting capabilities– JAX-RPC subset
» Must support stub based invocation (stub created using WSDL)
» No support yet for Dynamic proxies and Dynamic Invocation Interface (DII)
» No asynchronous messaging with attachment support» Not required to support Java beans
• Provides parsing XML data– JAXP subset
» Must support SAX 2.0 (with exceptions)» Must not support DOM
9
Infsci 1073/Telcom 272717
Wireless Web Services APIs 1 (2)
• SOAP and J2ME– J2ME has only limited string functionalities, a problem for every
wireless java XML parser– J2ME/CLDC lacks support Float datatypes– SOAP parsing requires to read the whole document
• kSOAP & kXML– kSOAP
• API with Small footprint• kSOAP is open source and based on kXML• Adds support for data types not supported by J2ME
– kXML• Non validating XML pull parser
Infsci 1073/Telcom 272718
MIDlet, J2EE Deployment,
• On the J2EE side, the Servlets and any other J2EE components such as EJBs are packaged in a JAR file, which along with any WARs go in an EAR file together with a deployment descriptor
• You can use the many tools that many App Servers provide to accomplish the packaging
• MIDP application (code and any resources)– packaged into a JAR file– a JAD file accompanies the JAR file
• Over The AIR (OTA) Provisioning provides guidelines for deploying the MIDlet on MIDP devices
10
Infsci 1073/Telcom 272719
Servlet Development Cycle
• Enable the invoker servlet• Create a Java class that extends
javax.servlet.http.HttpServlet• Testing and Debugging• Deployment
ExampleCreate a web-application to count number of Hits
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-appPUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN""http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app><servlet><servlet-name>myServlet</servlet-name><servlet-class>HitServlet</servlet-class>
</servlet>
<servlet-mapping><servlet-name>myServlet</servlet-name><url-pattern>/hits</url-pattern>
</servlet-mapping></web-app>
Enable the invoker servlet
11
Writing a Counting Servlet
import javax.servlet.http.*;import javax.servlet.*;import java.io.*;
public class HitServlet extends HttpServlet {private int mCount;
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
String message = "Hits: " + ++mCount;
response.setContentType("text/plain");response.setContentLength(message.length());PrintWriter out = response.getWriter();out.println(message);
}}
HitServlet simply counts the number of times it's been invoked and writes back to the client a message containing the count.
Hooking Up a MIDlet to the Servlet
Create a command action method in your MIDlet:
public void commandAction(Command c, Displayable s) {if (c == mExitCommand)
notifyDestroyed();else if (c == mConnectCommand) {
Form waitForm = new Form("Waiting...");mDisplay.setCurrent(waitForm);Thread t = new Thread() {
public void run() {connect();
}};t.start();
}}
12
Hooking Up a MIDlet to the Servlet
The Connect method
private void connect() {HttpConnection hc = null;InputStream in = null;String url = getAppProperty("HitMIDlet.URL");
try {hc = (HttpConnection)Connector.open(url);in = hc.openInputStream();
int contentLength = (int)hc.getLength();byte[] raw = new byte[contentLength];int length = in.read(raw);
in.close(); hc.close();
// Show the response to the user.String s = new String(raw, 0, length);mMessageItem.setText(s);
}catch (IOException ioe) {mMessageItem.setText(ioe.toString());
}mDisplay.setCurrent(mMainForm);
}
Infsci 1073/Telcom 272724
Enhanced Counting ServerCount Number of Hits for Each Client
• Using Cookies for Session Tracking– Cookie: a little piece of data that is passed from the
server to the client in an HTTP response• MIDLet associated with a session ID
– Each time the MIDlet sends a request to the server, it will be sending a session ID as a request header
• Server manages the counter– It uses the session ID from MIDlet to look up the
counter object to increment and return the value back to the MIDlet
13
Infsci 1073/Telcom 272725
CookieServlet
public class CookieServlet extends HttpServlet {private Map mHitMap = new HashMap(); public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {HttpSession session = request.getSession(); String id = session.getId(); int hits = -1; Integer hitsInteger = (Integer)mHitMap.get(id); if (hitsInteger != null) hits = hitsInteger.intValue(); hits++; mHitMap.put(id, new Integer(hits)); String message = "Hits for this session: "
+ hits + "."; response.setContentType("text/plain"); response.setContentLength(message.length()); PrintWriter out = response.getWriter();out.println(message);
} }
Extract session IDfrom the request
Using “HashMap” to store counter for each client
Increment, store,and return
Infsci 1073/Telcom 272726
Cookie MIDLet
Public void run()…{
// Query the server and retrieve the response. HttpConnection hc = (HttpConnection)Connector.open(url); if (mSession != null)
hc.setRequestProperty("cookie", mSession); InputStream in = hc.openInputStream(); String cookie = hc.getHeaderField("Set-cookie"); if (cookie != null) {
int semicolon = cookie.indexOf(';'); mSession = cookie.substring(0, semicolon);
} int length = (int)hc.getLength(); byte[] raw = new byte[length]; in.read(raw); String s = new String(raw); Alert a = new Alert("Response", s, null, null); a.setTimeout(Alert.FOREVER); mDisplay.setCurrent(a, mForm); in.close(); hc.close();
}…
Query the serverwith a session ID
Retrieve response from
the server
Display the result
14
Infsci 1073/Telcom 272727
J2ME Development• Basic steps as any software
application development• Characterize the application
(what will user be able to do?)– For example check movie times
and buy tickets• Identify tasks and target
devices– Choose a movie, find a theater,
view show times, buy ticket• Sketch tasks/application flow• Create a mock up • Determine server side
functionality
Infsci 1073/Telcom 272728
Recommended J2ME Programming Practices
• Keep in mind that there are strict memory constraints on most CLDC target devices
• Allocate memory resources just before use• Free resources as soon as they are not needed• Avoid allocating small temporary chunks of
memory to avoid heap fragmentation• Make local copies of global variables• Avoid redundant method calls, and inline functions
rather than creating a new class• Optimize loops
15
Infsci 1073/Telcom 272729
Game Development • Analyst Predictions for Mobile Games
– $2.8 billion in 2006 – In-Stat/MDR– $3.5 billion in 2006 - Informa Media– $4.4 billion in 2006 – Ovum– $9.3 billion in 2008 - Frost and Sullivan– $9 billion in 2010 – Informa Media
• Mobile games expected to fall into many game genres– Word and Trivia Games– Puzzle Games– Sports Games– Action Games– Multi-player games– Location based games
Infsci 1073/Telcom 272730
Handheld Games
• Challenges of Limited device– CPU Speed– Screen size and colors– Memory size and speed– Input – Latency
• For networked games
• Basic Game Components– Graphics and Animation– User Input– Sound– Networking
16
Infsci 1073/Telcom 272731
Handheld Games• Basic Game Features
– Storyline– Play Mode
• Single player standalone• Multiplayer
– turn based vs. simultaneous vs. round robin– Game Engine Options
» On each client device and have clients connect in peer to peer fashion
» Independent server that manages game state – distributes events to players
– Map (space where game takes place)• Design patterns exist for games
– Document / View pattern– Model+Functions / User Interfaces
Infsci 1073/Telcom 272732
General Game Architecture/Components
• Map: models physical space where the game takes place; can be many viewers for the same map (e.g. 2d and 3d viewers).
• Generic Game Loop– While the game is not over:
• read from the user• process the user input• process all automatic moves • generate new state of the model
– before: check that moves are legal– after: check for game over or winning situations
• refresh views• sleep/synchronize
17
Infsci 1073/Telcom 272733
Game Enabling Technology
Development platforms for games:• J2ME
– Largest global market, used by most carriers• Binary Runtime Environment Wireless (BREW)
(C++ for games)– Used by Verizon, largest US carrier
• Symbian– Supports C++, Java, VB
• Windows .NET CF Mobile SmartPhone– C#, VB.NET
Infsci 1073/Telcom 272734
Multi-Player Network Games
• Due to wireless network limitations, have following general guidelines
• Operate in standalone disconnected mode as much as possible, only connect to network if needed
• Try to batch message exchanged between players
• Perform client-side validations• Make operations interruptible• Provide progress meters and splash screens
18
Infsci 1073/Telcom 272735
J2ME Game Development
javax.microedition.lcdui.game• Series of Classes for the development of
games• APIs are optimized by device using native
code• Game APIs consist of • Layer, Sprite, TiledLayer, LayerManager,
GameCanvas
Infsci 1073/Telcom 272736
J2ME Game Development
19
Infsci 1073/Telcom 272737
J2ME Game Development• Layer
– Abstract class that represents a visual element of the game
• Sprite– Animated Layer displays one of
several graphical frames– Frames are equal size and
provided by a single object– Custom animation sequence
possible– Collision detection and
transformation methods provided• Tiled Layer
– A layer made up of a group of cells– Cells filled with single image object
or can be animated with rapid changes
– Use for background
Sprites
TiledLayer
Infsci 1073/Telcom 272738
J2ME Game Development• Layer Manager
– Provides APIs that control game’s layers and how rendered on the screen
• Game Canvas– Game engine
20
Infsci 1073/Telcom 272739
Game Blueprints
• Sun has developed set of wireless/handheld game blueprints– Standalone– Networked
• Basic game features coded as example games to show how tiled layer, sprites, layer manager game canvas, etc. work.
• Similarly Microsoft has a series of game forms for development of games in .NET CF
Infsci 1073/Telcom 272740
Standalone Game Example
• Player controls a paddle, which can be moved to the right, and to the left. To prevent the ball from falling out the bottom, the player has to keep moving the paddle to the point where the ball would drop out. The game is organized into levels. In each level, there are a number of bricks placed in the playing field. Some of these bricks will just disintegrate upon contact with the ball, some have special properties. The player has to use the ball to clear all destructible bricks from the playing field to advance to the next level. If the ball drops out the bottom, the player loses a life. The player has three lives. Once all lives are used up, the game is over.
Article discussing details of example game at http://developers.sun.com/techtopics/mobility/blueprints/articles/game/Code: http://java.sun.com/blueprints/code/index.html#games
21
Infsci 1073/Telcom 272741
Multi-player Networked Game Example
• Two player, level based game• Players control their characters
(slugs) through their phone• Slugs must move and avoid
obstacles (brick walls, poison, opponent, boundaries)
• Goal is to be the first player to reach the one slug house in each level
• Some levels have extra lives & lettuce to boost slugs energy
Article – discussing details of example networked game http://developers.sun.com/techtopics/mobility/blueprints/articles/game/Code: http://java.sun.com/blueprints/code/index.html#games