Home >Documents >Creating Network-Enabled Applications

Creating Network-Enabled Applications

Date post:22-Jan-2016
Category:
View:39 times
Download:0 times
Share this document with a friend
Description:
CSCI 7010 UGA March 23 rd , 2010. Creating Network-Enabled Applications. Ways to Connect. BES/MDS TCP/IP BIS WiFi WAP 2.0 WAP 1.0. BES/MDS. Blackberry Enterprise Server/Mobile Data System used if the Blackberry device is owned by a company and is set up to run through their servers - PowerPoint PPT Presentation
Transcript:
  • CSCI 7010UGAMarch 23rd, 2010

  • BES/MDSTCP/IPBISWiFiWAP 2.0WAP 1.0

  • Blackberry Enterprise Server/Mobile Data Systemused if the Blackberry device is owned by a company and is set up to run through their serverslets the Blackberry device make a secure connection to corporate servers

  • Transmission Control Protocol/Internet Protocola regular internet connectionworks with most devices

  • Blackberry Internet Servicefor devices that arent under a BESused to send emailInternet connections, but less secure than BESbut you need to be part of the Blackberry Alliance Program to use it

  • 802.11 B/G and sometimes Aallows device to connect to network via a WiFi routerdevice user has to configure device to connect to the routerPro: better speed, lower latency, no carrier data chargesCon: WiFi coverage less than wireless network coveragecan write app so that it looks for WiFi first and then falls back to BES or BIS

  • Wireless Access Protocolconnects through wireless carriers WAP gatewayno Blackberry-specific infrastructurebut users plan must support WAP 2.0 (most do)dont need to configure as with TCP/IP

  • older version of WAPsupported by all Blackberry devicesbut doesnt support secure connections as do other methods

  • What should you do?If activated on a BES:use BES/MDS If not activated on a BES:use WAP 2.0fall back to TCP/IP

    In either case, might want to check for WiFi

  • how the device maintains info about its configurationrecords about optional applicationsemail account configurationconnection methods available on a device

  • open device Optionsclick Advanced OptionsService BookDemo on the simulator

  • Two parts:CID defines the type of recordUID a unique identifier

    most connection methods have a record in the service book

  • javax.microedition.io.Connectorused it before to open filescan also use it to open network connections

    Example:HttpConnection connection = (HttpConnection) Connector.open(http://www.cnn.com);orHttpConnection connection = (HttpConnection) Connector.open(http://www.apress.com);

  • Connection_type connectionName= (Connection_type) Connector.open(URL);Connection_type is some subclass of ConnectionconnectionName is a variable name that you chooseURL takes the form scheme://host:port/path[optional parameters]Example URLs:file://myfile.htmlhttp://www.apress.com:80/book/catalogsocket://www.apress.com:80https://www.amazon.com/gp/flex/sign-in/select.html

  • Hypertext transfer protocolprotocol of the World Wide Webconnectionlessrequest-response

  • opens a connection to an http serversends a request message receives the responsedisplays result

  • listens for a connection from clientreceives a requestdelivers a responsecloses the connection

  • initial line (different for request & response)header lines (zero or more)blank lineoptional message body

  • METHOD path http_versionGET /path/to/file/index.html HTTP/1.0

    METHOD:GET Please send this resourcePOST Here are some details about itHEAD Just checking some info about it

    PATH:the part of the URL after the host name

  • also know as status lineHTTP_version status_code reason_phraseHTTP/1.0 200 OKHTTP/1.1 404 Not Foundstatus codes:100s informational200s success of some kind300s redirect to another URL400s client error500s server error

  • Lets run it from a web browser first ...

  • package com.beginningblackberry.networking;

    import net.rim.device.api.ui.UiApplication;

    public class NetworkingApplication extends UiApplication {

    public NetworkingApplication() {NetworkingMainScreen scr = new NetworkingMainScreen();pushScreen(scr);}

    public static void main(String[] args) {NetworkingApplication app = new NetworkingApplication();app.enterEventDispatcher();}}

  • package com.beginningblackberry.networking;import net.rim.device.api.ui.container.MainScreen;

    public class NetworkingMainScreen extends MainScreen {private EditField urlField;private BitmapField imageOutputField;private RichTextField textOutputField;.... methods on following slides

    }

  • public NetworkingMainScreen() {

    setTitle("Networking");urlField = new EditField("URL:", "");textOutputField = new RichTextField();imageOutputField = new BitmapField();

    add(urlField);add(new SeparatorField());

    postDataField = new EditField("Post data:", "");add(postDataField);add(new SeparatorField());

    add(new LabelField("Image retrieved:"));add(imageOutputField);add(new SeparatorField());add(new LabelField("Text retrieved:"));add(textOutputField);}

  • protected void makeMenu(Menu menu, int instance) {super.makeMenu(menu, instance);menu.add(new MenuItem("Get", 10, 10) {public void run() {getURL();} } );menu.add(new MenuItem("Post", 10, 10) {public void run() {postURL();}});menu.add(new MenuItem("Socket Get", 10, 10) {public void run() {socketGet();}});}

  • http://www.purpletech.com/talks/Threads.ppt

    More on multi-threading (if youre interested):

    http://www.cs.uga.edu/~eileen/Concurrency_tutorials

  • You can learn about any component by looking at the API documentation.

    See:http://www.blackberry.com/developers/docs/4.1api/index.htmlto learn more about the MenuItem component

  • private void getURL() {HttpRequestDispatcher dispatcher = new HttpRequestDispatcher(urlField.getText(), "GET", this);dispatcher.start();}

    ... creates a new thread for the network-related operation... and starts it up

  • package com.beginningblackberry.networking;

    /* * Class to handle creating the request, sending it off, * and receiving the response */

    public class HttpRequestDispatcher extends Thread { private String url; private String method; // GET or POST private NetworkingMainScreen screen; private byte[] postData;...

    }

  • public HttpRequestDispatcher(String url, String method, NetworkingMainScreen screen) { this.url = url; this.method = method; this.screen = screen; }

    public HttpRequestDispatcher(String url, String method,NetworkingMainScreen screen, byte[] postData) { this.url = url; this.method = method; this.screen = screen; this.postData = postData; }

  • public void run(){try{HttpConnection connection = (HttpConnection) Connector.open(url);

    int responseCode = connection.getResponseCode();

    if (responseCode != HttpConnection.HTTP_OK){screen.requestFailed(Unexpected response code: + responseCode); connection.close(); return; }...

  • String contentType = connection.getHeaderField(Content-type);ByteArrayOutputStream baos = new ByteArrayOutputStream();

    InputStream responseData = connection.openInputStream();byte[] buffer = new byte[10000];

    int bytesRead = responseData.read(buffer);while (bytesRead > 0){baos.write(buffer, 0, bytesRead);bytesRead = responseData.read(buffer);}baos.close();connection.close();screen.requestSucceeded(baos.toByteArray(), contentType);} catch (IOException ex){ screen.requestFailed(ex.toString());}}

  • public void requestSucceeded(byte[] result, String contentType) {if (contentType.equals("image/png") ||contentType.equals("image/jpeg") ||contentType.equals("image/gif")) {

    Bitmap bitmap = Bitmap.createBitmapFromBytes(result, 0, result.length, 1);

    synchronized (UiApplication.getEventLock()) {imageOutputField.setBitmap(bitmap);}}else if (contentType.startsWith("text/")) {String strResult = new String(result);synchronized (UiApplication.getEventLock()) {textOutputField.setText(strResult);}}else {synchronized (UiApplication.getEventLock()) {Dialog.alert("Unknown content type: " + contentType);}}}

  • public void requestFailed(final String message) {UiApplication.getUiApplication().invokeLater(new Runnable() {public void run() {Dialog.alert("Request failed. Reason: " + message);}});

    }

    }

  • .... and weve skipped some gory detail for now

  • See: http://beginningblackberry.appspot.com

    Enter some words in the form apple berry cinnamon doughnutreturnsdoughnut cinnamon berry apple

  • Whats in the web application?

    Form

  • defines a form that the browser uses to send data to the web applicationsend data to the ULR / (the base URL )using HTTP POST

  • defines the text boxgives it the name content

    the application expects the content to be something like: content = ONE+TWO+THREE+ interpreted as a space

  • defines the Go button as invoking POST

    indicates end of the form

  • private byte[] postData;- to pass the POST body to the dispatcher

    public HttpRequestDispatcher(String url, String method, NetworkingMainScreen screen, byte[] postData){this.url = url;this.method = method;this.screen = screen;this.postData = postData;}- constructor to initialize

  • if (method.equals(POST) && postData != null){connection.setRequestProperty(Content-type, application/x-www-form-urlencoded);

    OutputStream requestOutput = connection.openOutputStream();

    requestOutput.write(postData);requestOutput.close();}

  • private void postURL(){ String postString = postDataField.getText();

    URLEncodedPostData encodedData = new URLEncodedPostData(null, false);

    encodedData.append(content, postString);

    HttpRequestDispatcher dispatcher = new HttpRequestDispatcher(urlField.getText(), POST, this, encodedData.getBytes());

    dispatcher.start();}

  • lets look at the code

  • explanation... and lets look at the code ...

  • private void socketGet() {SocketConnector connector = new SocketConnector(urlField.getText(), this);connector.start();}

    private void postURL() {String postString = postDataField.getText();URLEncodedPostData encodedData = new URLEncodedPostData(null, false);encodedData.append("content", postString);HttpRequestDispatcher dispatcher = new HttpRequestDispatcher(urlField.getText(), "POST", this, encodedData.getBytes());dispatcher.start();}

  • *The constructor is doing the usual things ... it creates the User Interface

    urlField and postDataField will be for user text input

    imageOutputField will be used to display an image

    textOutputField is a RichTextField which allows you to do multi-line text display, line wrap, & more

    We also have some label fields to label the image output and text output areas.*

    -- makeMenu is defined in the screen class. Here, we override it, so that themenu we define here is the one that is now associated with this screen.

    What does super.makeMenu(Menu, int) do?-- this calls the makeMenu for the superclass (MainScreen), which adds all the default items to the menu (i.e., Close)

    Each MenuItem is a class, with a constructor and a run() method.The constructor specifies the label , an ordinal value (determines where in the menu the item appears) and a priority value (determines which item will be initially highlighted). Lower ordinal values appear higherer on the list. Lowest priority value is highlighted. We set these with all the same value, so it means that we dont care.

    So, each MenuItem here is an anonymous inner class.

    When the user clicks on a MenuItem, a new thread is created and the newly created thread executes the run() method for that item.

    So here, when the user selects Get, a new thread runs the getURL() method.When the user selects Post, a new thread runs the postURL() method.

    **

Click here to load reader

Reader Image
Embed Size (px)
Recommended