0% found this document useful (0 votes)
37 views49 pages

7 Network Programming Overview Parts1 and 2

The document discusses network programming for Android applications. It explores the motivations for and challenges of networked software, and describes the Android mechanisms available to implement apps and services that communicate across process boundaries. It also provides an overview of the foundational network programming mechanisms in Android, including sockets.

Uploaded by

ims
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views49 pages

7 Network Programming Overview Parts1 and 2

The document discusses network programming for Android applications. It explores the motivations for and challenges of networked software, and describes the Android mechanisms available to implement apps and services that communicate across process boundaries. It also provides an overview of the foundational network programming mechanisms in Android, including sockets.

Uploaded by

ims
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Android Network Programming:

Introduction

Douglas C. Schmidt
[email protected]
www.dre.vanderbilt.edu/~schmidt

Professor of Computer Science


Institute for Software
Integrated Systems

Vanderbilt University
Nashville, Tennessee, USA
Network Programming Douglas C. Schmidt

Introduction
• Explore the motivations for & challenges of networked software

Networked software defines protocols that enable computing


devices to exchange messages
2
& perform services remotely
Network Programming Douglas C. Schmidt

Introduction
• Explore the motivations for & challenges of networked software
• Describe the Android mechanisms available to implement apps & services
that communicate across process boundaries that span mobile devices &
server hosts

3
Network Programming Douglas C. Schmidt

Introduction
• Explore the motivations for & challenges of networked software
• Describe the Android mechanisms available to implement apps & services
that communicate across process boundaries
• Many Android apps use Sockets & TCP and/or HTTP to communicate &
exchange data via the Internet
• e.g., Browser, Email, MMS/SMS, Calendar, Contacts, etc.

Socket

Socket

4
See developer.android.com/training/basics/network-ops/connecting.html
Network Programming Douglas C. Schmidt

Introduction
• Explore the motivations for & challenges of networked software
• Describe the Android mechanisms available to implement apps & services
that communicate across process boundaries
• Many Android apps use Sockets & TCP and/or HTTP to communicate &
exchange data via the Internet
• Android also provides certain IPC mechanisms that are optimized for inter-
process communicate within a mobile device
• e.g., the Android Interface Definition Language (AIDL) & Binder framework
Process A Binder IPC Mechanism Process B
DownloadActivity DownloadService

1: Call method downloadImage() LocalBinder

mBoundService downloadImage()
2: Return results to caller

5
We’ll cover the the Android Binder & AIDL in later modules
Android Network Programming: Part 1

Douglas C. Schmidt
[email protected]
www.dre.vanderbilt.edu/~schmidt

Professor of Computer Science


Institute for Software
Integrated Systems

Vanderbilt University
Nashville, Tennessee, USA
Network Programming Douglas C. Schmidt

Learning Objectives in this Part of the Module


• Understand the motivations for & challenges of networked software

7
Network Programming Douglas C. Schmidt

Motivations for Networked Software


• Collaboration & commerce
• e.g., file sharing, social
media, e-commerce online CLIENTS
transaction processing, B2B
supply chain management,
etc.

8
Network Programming Douglas C. Schmidt

Motivations for Networked Software


• Collaboration & commerce
• Scalability
• e.g., utility computing in clouds CLIENTS

9
www.ge.com/stories/industrial-internet has many apt examples
Network Programming Douglas C. Schmidt

Motivations for Networked Software


• Collaboration & commerce
• Scalability
• Availability CLIENTS

• e.g., minimizing single points


of failure via replication

10
Network Programming Douglas C. Schmidt

Motivations for Networked Software


• Collaboration & commerce
• Scalability
• Availability CLIENTS

• Cost effectiveness
• e.g., via shared resources

11
Network Programming Douglas C. Schmidt

Challenges for Networked Software


• Accidental Complexities
• Algorithmic decomposition

Algorithmic decomposition is
a historically popular design
method that structures the
software based on the actions
performed by the system

12
www.informit.com/articles/article.aspx?p=726130&seqNum=5 has more info
Network Programming Douglas C. Schmidt

Challenges for Networked Software


• Accidental Complexities
• Algorithmic decomposition
• Continuous re-discovery
& re-invention of core
components

13
See steve.vinoski.net/pdf/IEEE-Middleware_Dark_Matter.pdf for more
Network Programming Douglas C. Schmidt

Challenges for Networked Software


• Accidental Complexities
• Algorithmic decomposition
• Continuous re-discovery
& re-invention of core
components
• Inherent Complexities
• Latency & jitter

14
Network Programming Douglas C. Schmidt

Challenges for Networked Software


• Accidental Complexities
• Algorithmic decomposition
• Continuous re-discovery
& re-invention of core
components
• Inherent Complexities
• Latency & jitter
• Reliability & partial
failure

Error detection & handling is more15


complicated for networked software
Network Programming Douglas C. Schmidt

Challenges for Networked Software


• Accidental Complexities
• Algorithmic decomposition
• Continuous re-discovery
& re-invention of core
components
• Inherent Complexities
• Latency & jitter
• Reliability & partial
failure
• Security

16
See www.dre.vanderbilt.edu/~schmidt/PDF/pdcp-editorial.pdf for more info
Network Programming Douglas C. Schmidt

Summary
• Networked software helps
• Leverage advances in hardware
& networking technology
• Meet the quality & performance
needs of apps & services

17
Network Programming Douglas C. Schmidt

Summary
• Networked software helps
• Leverage advances in hardware
& networking technology
• Meet the quality & performance
needs of apps & services
• Successful networked software
solutions must address key accidental
& inherent complexities arising from
• Limitations with development
tools/techniques
• Fundamental domain challenges

18
Network Programming Douglas C. Schmidt

Summary
• Networked software helps
• Leverage advances in hardware
& networking technology
• Meet the quality & performance
needs of apps & services
• Successful networked software
solutions must address key accidental
& inherent complexities arising from
• Limitations with development
tools/techniques
• Fundamental domain challenges
• As networked systems have grown in
scale & functionality they must cope
with a broader & more challenging set
of complexities

19
Android Network Programming: Part 2

Douglas C. Schmidt
[email protected]
www.dre.vanderbilt.edu/~schmidt

Professor of Computer Science


Institute for Software
Integrated Systems

Vanderbilt University
Nashville, Tennessee, USA
Network Programming Douglas C. Schmidt

Learning Objectives in this Part of the Module


• Understand the foundational network programming mechanisms in Android

Socket

Socket

21
Network Programming Douglas C. Schmidt

Overview of Android Network Programming


• Android includes multiple network
programming classes, e.g.,
• java.net – (Socket, URL, etc.)
• org.apache – (HttpRequest,
HttpResponse, etc.)
• android.net – (AndroidHttpClient,
URI, AudioStream, etc.)

22
Network Programming Douglas C. Schmidt

Overview of Android Network Programming


• Android includes multiple network
programming classes, e.g.,
• java.net – (Socket, URL, etc.)
• org.apache – (HttpRequest,
HttpResponse, etc.)
• android.net – (AndroidHttpClient,
URI, AudioStream, etc.)
• Under the hood, Android’s HTTP
libraries use the Java Sockets API
Socket
• A socket is a software endpoint
that can create a bi-directional Socket
“reliable” communication link
between software processes

Sockets are a common programming23


interface for network communication
Network Programming Douglas C. Schmidt

Overview of Android Network Programming


• Android includes multiple network
programming classes, e.g.,
• java.net – (Socket, URL, etc.)
• org.apache – (HttpRequest,
HttpResponse, etc.)
• android.net – (AndroidHttpClient,
URI, AudioStream, etc.)
• Under the hood, Android’s HTTP
libraries use the Java Sockets API
Socket
• Even deeper under the hood
Android’s java.net implementation Socket
uses the Linux C Socket API via JNI

24
en.wikipedia.org/wiki/Java_Native_Interface has more info on JNI
Network Programming Douglas C. Schmidt

Overview of Java Sockets


1: Passive Role

ServerSocket
accept()
Represents a server-side bind()
factory that waits for close()
incoming client connections
& creates connected Sockets

Socket

Network

25
developer.android.com/reference/java/net/ServerSocket.html
Network Programming Douglas C. Schmidt

Overview of Java Sockets


1: Passive Role

ServerSocket
accept()
Plays a portion of the bind()
Acceptor role in the close()
Acceptor-Connector pattern

Socket

Network

26
www.dre.vanderbilt.edu/~schmidt/PDF/Acc-Con.pdf has more info
Network Programming Douglas C. Schmidt

Overview of Java Sockets


Provides a client-side (&
Provides a client-side 1: Passive Role
server-side) TCP socket
ServerSocket
2: Active Role
accept()
Socket bind()
bind() close()
close()
connect()
getInputStream()
getOutputStream() Socket

Network

27
developer.android.com/reference/java/net/Socket.html
Network Programming Douglas C. Schmidt

Overview of Java Sockets


Clients & servers designate their
Provides
Providesa aclient-side
client-side 1: Passive Role
addresses with an InetAddress
ServerSocket
2: Active Role
accept()
Socket bind()
bind() close()
close()
connect()
getInputStream()
getOutputStream() Socket

Network

28
developer.android.com/reference/java/net/InetAddress.html
Network Programming Douglas C. Schmidt

Overview of Java Sockets


1: Passive Role
InputStream &
2: Active Role
ServerSocket OutputStream are
accept() used to exchange
Socket bind() bytes on
bind() close() connected sockets
close()
connect()
getInputStream()
getOutputStream() Socket
3: Communication
Role

Network

29
oreilly.com/catalog/javaio/chapter/ch05.html has more info
Network Programming Douglas C. Schmidt

InputStream in Android
• An InputStream is a stream of incoming byte data
• An InputStream can be obtained from a Socket by using the
getInputStream() method
• To read from a stream, you must create a byte buffer to read in data
• Each call to read on an InputStream fills your buffer with data & returns the
number of bytes read

InputStream in = someSocket.getInputStream();
const int BUFSIZ = 1024;
byte[] buffer = new byte[BUFSIZ];

for(int bytesRead;
(bytesRead = in.read(buffer,0,buffer.length)) != -1;
) {
// the buffer’s been filled, do something with the data
}

30
developer.android.com/reference/java/io/InputStream.html has more info
Network Programming Douglas C. Schmidt

InputStreamReader in Android
• An InputStreamReader turns a byte stream into a character stream
• Data read from the source input stream is converted into characters by
either a default or a provided character converter
• InputStreamReader contains an 8K buffer of bytes read from the source
stream & converts these into characters as needed
InputStream in = someSocket.getInputStream();
Reader reader = new InputStreamReader(in);

Read one character at a time

for (int data; (data = reader.read()) != -1; ){


char theChar = (char) data;
// … do something with the data
}

reader.close();

31
Network Programming Douglas C. Schmidt

InputStreamReader in Android
• An InputStreamReader turns a byte stream into a character stream
• Data read from the source input stream is converted into characters by
either a default or a provided character converter
• InputStreamReader contains an 8K buffer of bytes read from the source
stream & converts these into characters as needed
InputStream in = someSocket.getInputStream();
Reader reader = new InputStreamReader(in);

for (int data; (data = reader.read()) != -1; ){


char theChar = (char) data;
// … do something with the data
}
Can also read a buffer at a time
reader.close();

32
developer.android.com/reference/java/io/InputStreamReader.html has more
Network Programming Douglas C. Schmidt

BufferedReader in Android
• Wraps an existing Reader & buffers the input
• Expensive interaction with underlying reader is minimized, since most
(smaller) requests can be satisfied by accessing buffer alone
• Drawback is that some extra space is required to hold the buffer & copying
takes place when filling that buffer

BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader
(someSocket.getInputStream()));

for (String data;


(data = bufferedReader.readLine()) != null; ){
// … do something with the data
}

bufferedReader.close();

33
developer.android.com/reference/java/io/BufferedReader.html has more info
Network Programming Douglas C. Schmidt

OutputStream in Android
• An OutputStream is a stream of outgoing byte data
• An OutputStream can be obtained from a Socket by using the
getOutputStream() method
• You can write data to a stream by passing in a byte buffer of data
• You should use flush() if you want to ensure the data you have written is
output to disk or sent to other end of socket

OutputStream out = someSocket.getOutputStream();


out.write("Hello Socket".getBytes());
out.flush();

byte[] buffer = new byte[1024];


// fill the buffer
out.write(buffer,0,buffer.length);
out.close();

34
developer.android.com/reference/java/io/OutputStream.html has more info
Network Programming Douglas C. Schmidt

OutputStreamWriter in Android
• A class for turning a character stream into a byte stream
• Data written to the target input stream is converted into bytes by either a
default or a provided character converter
• OutputStreamWriter contains an 8K buffer of bytes to be written to target
stream & converts these into characters as needed

OutputStreamWriter out =
new OutputStreamWriter
(someSocket.getOutputStream());

String string1 = "Android socket IO",


string2 = " is fun";

out.write(string1);
out.append(string2);
out.flush();
out.close();

developer.android.com/reference/java/io/OutputStreamWriter.html
35 has more
Network Programming Douglas C. Schmidt

PrintWriter in Android
• Wraps either an existing OutputStream or an existing Writer (including
OutputStreamWriter)
• Provides convenience methods for printing common data types in a human
readable format
PrintWriter pw =
new PrintWriter(new
OutputStreamWriter(someSocket.getOutputStream()),
// “true” indicates auto-flush
true);
pw.println("GET /index.html");

BufferedReader br = new BufferedReader(new


InputStreamReader(socket.getInputStream()));

for (String rawData; (rawData = br.readLine()) != null; )


data.append(rawData);

36
developer.android.com/reference/java/io/PrintWriter.html has more info
Network Programming Douglas C. Schmidt

Android I/O Implements the Decorator Pattern


• The Java I/O streams classes use the Decorator pattern, which allows for
the dynamic wrapping of objects to modify their existing responsibilities &
behaviors

• Stream classes extend the base subclasses to add features to the stream
classes

37
en.wikipedia.org/wiki/Decorator_pattern has more on Decorator
Network Programming Douglas C. Schmidt

Programming Java Sockets in Android


public class NetworkingSocketsActivity extends Activity
{
TextView mTextView = null;

public void onCreate(Bundle savedInstanceState) {


...
// assuming server is listening on port 80
new HttpGet().execute("www.dre.vanderbilt.edu ");
}
Pass a URL to the template
method of an AsyncTask

38
Network Programming Douglas C. Schmidt

Programming Java Sockets in Android


private class HttpGet
extends AsyncTask<String, Void, String> {

Runs in a background thread


protected String doInBackground(String... params) {
Socket socket = null;
StringBuffer data = new StringBuffer();
try {
socket = new Socket(params[0], 80);
Connect to the server
PrintWriter pw =
new PrintWriter(new
OutputStreamWriter(socket.getOutputStream()),
true);
pw.println("GET /index.html");
...
Send GET request

39
Network Programming Douglas C. Schmidt

Programming Java Sockets in Android


...
BufferedReader br = new BufferedReader(
new InputStreamReader
(socket.getInputStream()));
String rawData;
while ((rawData = br.readLine()) != null) {
data.append(rawData);
} Read data from server
} catch ...
// close socket
return data.toString(); Return data as a String
...
} Display the text on the screen

protected void onPostExecute(String result) {


mTextView.setText(result);
}
40
Network Programming Douglas C. Schmidt

Programming with URLConnection in Android

public class NetworkingURLActivity extends Activity {


TextView mTextView = null;

public void onCreate(Bundle savedInstanceState) {


new HttpGetTask().execute
("http://api.geonames.org/...");
}
... Pass a URL to the template
method of an AsyncTask

41
Network Programming Douglas C. Schmidt

Programming with URLConnection in Android


private class HttpGetTask
extends AsyncTask<String, Void, String> {
Runs in a background thread
...
protected String doInBackground(String... params) {
StringBuffer serverData = new StringBuffer();
HttpURLConnection conn = (HttpURLConnection) new
URL(params[0]).openConnection();
Connect to the server &
send GET request
InputStream in =
new BufferedInputStream(conn.getInputStream());
BufferedReader br = ...;
... Read & process the
data from the server
return serverData.toString(); Return data as a String
...
42
developer.android.com/reference/java/net/URLConnection.html has more
Network Programming Douglas C. Schmidt

Networking Permissions
• To allow an app to access the
Internet using Eclipse, open
AndroidManifest.xml, go to
“Permissions” tab, add "Uses
Permission" & select android.
permission.INTERNET

43
developer.android.com/training/basics/network-ops/connecting.html
Network Programming Douglas C. Schmidt

Networking Permissions
• To allow an app to access the <manifest
xmlns:android="http://schemas.android
Internet using Eclipse, open com/apk/res/android"
AndroidManifest.xml, go to
“Permissions” tab, add "Uses package="examples.threadeddownloads"
Permission" & select android. android:versionCode="1"
permission.INTERNET android:versionName="1.0" >
• Alternatively, open the
AndroidManifest.xml file <uses-permission android:name=
as raw XML & add a line "android.permission.INTERNET">
</uses-permission>
near the top:

If you don't do this, your application will crash with an


UnknownHostException when trying to access a remote host!!

44
ffct.cc/android-development-accessing-the-internet
Network Programming Douglas C. Schmidt

Summary
• Android provides a wide range of network programming mechanisms

www.vogella.com/tutorials.html

45& resources available online


There are many Android tutorials
Network Programming Douglas C. Schmidt

Summary
• Android provides a wide range of network programming mechanisms
• There are many patterns underlying these Android network programming
mechanisms, e.g.:
• Wrapper Facade

www.dre.vanderbilt.edu/~schmidt/PDF/wrapper-facade.pdf
46 has more info
Network Programming Douglas C. Schmidt

Summary
• Android provides a wide range of network programming mechanisms
• There are many patterns underlying these Android network programming
mechanisms, e.g.:
Variations in how Socket
• Wrapper Façade is implemented
• Bridge
Variations in what
service a Socket provides

Socket SocketImpl

SSLSocket CompressionSocket WindowsSocketImpl UNIXSocketImpl

operation() operation()

47
en.wikipedia.org/wiki/Bridge_pattern has more info
Network Programming Douglas C. Schmidt

Summary
• Android provides a wide range of network programming mechanisms
• There are many patterns underlying these Android network programming
mechanisms, e.g.:
• Wrapper Façade
• Bridge
• Decorator

48
en.wikipedia.org/wiki/Decorator_pattern has more info
Network Programming Douglas C. Schmidt

Summary
• Android provides a wide range of network programming mechanisms
• There are many patterns underlying these Android network programming
mechanisms, e.g.:
• Wrapper Façade
• Bridge
• Decorator
• Acceptor-Connector

49
www.dre.vanderbilt.edu/~schmidt/PDF/Acc-Con.pdf has more info

You might also like