Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 CSCE 4013: Mobile Systems Programming Nilanjan Banerjee Mobile Systems Programming (Acknowledgment to Deepa Shinde and Cindy Atheron University of Arkansas.

Similar presentations


Presentation on theme: "1 CSCE 4013: Mobile Systems Programming Nilanjan Banerjee Mobile Systems Programming (Acknowledgment to Deepa Shinde and Cindy Atheron University of Arkansas."— Presentation transcript:

1 1 CSCE 4013: Mobile Systems Programming Nilanjan Banerjee Mobile Systems Programming (Acknowledgment to Deepa Shinde and Cindy Atheron University of Arkansas Fayetteville, AR nilanb@uark.edu http://mpss.csce.uark.edu/mobsys/

2 2 Socket Programming TCP and UDP

3 3 Socket programming Socket API introduced in BSD4.1 UNIX, 1981 explicitly created, used, released by apps client/server paradigm two types of transport service via socket API: –unreliable datagram –reliable, byte stream- oriented a host-local, application-created, OS-controlled interface (a “door”) into which application process can both send and receive messages to/from another application process socket Goal: learn how to build client/server application that communicate using sockets

4 4 TCP

5 2: Application Layer 5 Socket-programming using TCP Socket: a door between application process and end- end-transport protocol (UCP or TCP) TCP service: reliable transfer of bytes from one process to another process TCP with buffers, variables socket controlled by application developer controlled by operating system host or server process TCP with buffers, variables socket controlled by application developer controlled by operating system host or server internet

6 2: Application Layer 6 Socket programming with TCP Client must contact server server process must first be running server must have created socket (door) that welcomes client’s contact Client contacts server by: creating client-local TCP socket specifying IP address, port number of server process When client creates socket: client TCP establishes connection to server TCP When contacted by client, server TCP creates new socket for server process to communicate with client –allows server to talk with multiple clients –source port numbers used to distinguish clients TCP provides reliable, in-order transfer of bytes (“pipe”) between client and server application viewpoint

7 7 Stream jargon A stream is a sequence of characters that flow into or out of a process. An input stream is attached to some input source for the process, eg, keyboard or socket. An output stream is attached to an output source, eg, monitor or socket.

8 8 Socket programming with TCP Example client-server app: 1) client reads line from standard input ( inFromUser stream), sends to server via socket ( outToServer stream) 2) server reads line from socket 3) server converts line to uppercase, sends back to client 4) client reads, prints modified line from socket ( inFromServer stream) Client process client TCP socket

9 9 Client/server socket interaction: TCP wait for incoming connection request connectionSocket = welcomeSocket.accept() create socket, port= x, for incoming request: welcomeSocket = ServerSocket() create socket, connect to hostid, port= x clientSocket = Socket() close connectionSocket read reply from clientSocket close clientSocket Server (running on hostid ) Client send request using clientSocket read request from connectionSocket write reply to connectionSocket TCP connection setup

10 10 Example: Java client (TCP) import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Socket clientSocket = new Socket("hostname", 6789); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); Create input stream Create client socket, connect to server Create output stream attached to socket

11 11 Example: Java client (TCP), cont. BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + '\n'); modifiedSentence = inFromServer.readLine(); System.out.println ("FROM SERVER: " + modifiedSentence ); clientSocket.close(); } Create input stream attached to socket Send line to server Read line from server

12 12 Example: Java server (TCP) import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; ServerSocket welcomeSocket = new ServerSocket(6789); while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); Create welcoming socket at port 6789 Wait, on welcoming socket for contact by client Create input stream, attached to socket

13 13 Example: Java server (TCP), cont DataOutputStream outToClient = new DataOutputStream (connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + '\n'; outToClient.writeBytes(capitalizedSentence); } Read in line from socket Create output stream, attached to socket Write out line to socket End of while loop, loop back and wait for another client connection

14 14 UDP

15 15 Socket programming with UDP UDP: no “connection” between client and server no handshaking sender explicitly attaches IP address and port of destination to each packet server must extract IP address, port of sender from received packet UDP: transmitted data may be received out of order, or lost application viewpoint UDP provides unreliable transfer of groups of bytes (“datagrams”) between client and server

16 16 Client/server socket interaction: UDP close clientSocket Server (running on hostid ) read reply from clientSocket create socket, clientSocket = DatagramSocket() Client Create, address ( hostid, port=x, send datagram request using clientSocket create socket, port= x, for incoming request: serverSocket = DatagramSocket() read request from serverSocket write reply to serverSocket specifying client host address, port number

17 17 Example: Java client (UDP) Output: sends packet (TCP sent “byte stream”) Input: receives packet (TCP received “byte stream”) Client process client UDP socket

18 18 Example: Java client (UDP) import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("hostname"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); Create input stream Create client socket Translate hostname to IP address using DNS

19 19 Example: Java client (UDP), cont. DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData(),0,receivePacket.getLength()); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } Create datagram with data-to-send, length, IP addr, port Send datagram to server Read datagram from server

20 20 Example: Java server (UDP) import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); Create datagram socket at port 9876 Create space for received datagram Receive datagram

21 2: Application Layer 21 Example: Java server (UDP), cont String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } Get IP addr port #, of sender Write out datagram to socket End of while loop, loop back and wait for another datagram Create datagram to send to client

22 Required Packages

23 Layout

24 Link Activity and View View object may have an integer ID associated with it android:id="@+id/my_button“ To get the reference of the view object in activity Button myButton = (Button)findViewById(R.id.my_button);

25 Adding Event to View Object View.OnClickListener() –Interface definition for a callback to be invoked when a view is clicked. onClick(View v) –Called when a view has been clicked. Inside this function you can specify what actions to perform on a click.

26 Strings.xml

27 AndroidManifest.xml

28 Network Settings If you are using the emulator then there are limitations. Each instance of the emulator runs behind a virtual router/firewall service that isolates it from your development machine's network interfaces and settings and from the internet. Communication with the emulated device may be blocked by a firewall program running on your machine.

29 Behind Proxy Server

30

31

32

33

34

35 App to Download jpg file Step1 Add permissions to AndroidManifest.xml Step 2 Import files import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast;

36 App to Download jpg file Step 3 Writing OpenHttpConnection() –To open a connection to a HTTP server using OpenHttpConnection() –We first create an instance of the URL class and initialize it with the URL of the server –When the connection is established, you pass this connection to an URLConnection object. To check if the connection established is using a HTTP protocol. –The URLConnection object is then cast into an HttpURLConnection object and you set the various properties of the HTTP connection. –Next, you connect to the HTTP server and get a response from the server. If the response code is HTTP_OK, you then get the InputStream object from the connection so that you can begin to read incoming data from the server –The function then returns the InputStream object obtained.

37 App to Download jpg file public class HttpDownload extends Activity { /** Called when the activity is first created.*/ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } private InputStream OpenHttpConnection(String urlString) throws IOException { InputStream in = null; int response = -1; URL url = new URL(urlString); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection"); try{ HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception ex) { throw new IOException("Error connecting"); } return in; }

38 App to Download jpg file Step 4 Modify the Main.xml code <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" /> <TextView android:id="@+id/text" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content" />

39 App to Download jpg file Step 5 writing DownloadImage() –The DownloadImage() function takes in a string containing the URL of the image to download. –It then calls the OpenHttpConnection() function to obtain an InputStream object for reading the image data. –The InputStream object is sent to the decodeStream() method of the BitmapFactory class. –The decodeStream() method decodes an InputStream object into a bitmap. –The decoded bitmap is then returned by the DownloadImage() function. private Bitmap DownloadImage(String URL) { Bitmap bitmap = null; InputStream in = null; try { in = OpenHttpConnection(URL); bitmap = BitmapFactory.decodeStream(in); in.close(); } catch (IOException e1) { e1.printStackTrace(); } return bitmap; }

40 Step 6 T est the DownloadImage() function, modify the onCreate() event as follows @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Bitmap bitmap = DownloadImage( "http://www.streetcar.org/mim/cable/images/cable-01.jpg"); img = (ImageView) findViewById(R.id.img); img.setImageBitmap(bitmap); }

41 App to Download jpg file Step 7:Output

42 Intent and IntentFilter Intents request for an action to be performed and supports interaction among the Android components. ◦ For an activity it conveys a request to present an image to the user ◦ For broadcast receivers, the Intent object names the action being announced. Intent Filter Registers Activities, Services and Broadcast Receivers(as being capable of performing an action on a set of data).

43 SMS Sending STEP 1 –In the AndroidManifest.xml file, add the two permissions - SEND_SMS and RECEIVE_SMS. STEP 2 –In the main.xml, add Text view to display "Enter the phone number of recipient“ and "Message" –EditText with id txtPhoneNo and txtMessage –Add the button ID "Send SMS“

44 SMS Sending Step 3 Import Classes and Interfaces import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsManager; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;

45 SMS Sending Step 4 Write the SMS class public class SMS extends Activity { Button btnSendSMS; EditText txtPhoneNo; EditText txtMessage; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnSendSMS = (Button) findViewById(R.id.btnSendSMS); txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo); txtMessage = (EditText) findViewById(R.id.txtMessage); btnSendSMS.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String phoneNo = txtPhoneNo.getText().toString(); String message = txtMessage.getText().toString(); if (phoneNo.length()>0 && message.length()>0) sendSMS(phoneNo, message); else Toast.makeText(getBaseContext(), "Please enter both phone number and message.", Toast.LENGTH_SHORT).show(); } }); } Input from the user (i.e., the phone no, text message and sendSMS is implemented).

46 SMS Sending Step 5 ◦ To send an SMS message, you use the SmsManager class. And to instantiate this class call getDefault() static method. ◦ The sendTextMessage() method sends the SMS message with a PendingIntent. ◦ The PendingIntent object is used to identify a target to invoke at a later time. private void sendSMS(String phoneNumber, String message) { PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, SMS.class), 0); SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null, message, pi, null); }

47 SMS Sending

48 Receiving SMS Step 1

49 Receiving SMS Step 2 –In the AndroidManifest.xml file add the element so that incoming SMS messages can be intercepted by the SmsReceiver class. <action android:name= "android.provider.Telephony.SMS_RECEIVED" />

50 Receiving SMS Step 3 import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.SmsMessage; import android.widget.Toast;

51 Receiving SMS Step 4 public class SmsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //---get the SMS message passed in--- Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String str = ""; if (bundle != null){ //---retrieve the SMS message received--- Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for (int i=0; i<msgs.length; i++) { msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); str += "SMS from " + msgs[i].getOriginatingAddress(); str += " :"; str += msgs[i].getMessageBody().toString(); str += "\n"; } //---display the new SMS message--- Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); } In the SmsReceiver class, extend the BroadcastReceiver class and override the onReceive() method. The message is attached to the Intent The messages are stored in a object array PDU format. To extract each message, you use the static createFromPdu() method from the SmsMessage class. The SMS message is then displayed using the Toast class

52 Receiving SMS


Download ppt "1 CSCE 4013: Mobile Systems Programming Nilanjan Banerjee Mobile Systems Programming (Acknowledgment to Deepa Shinde and Cindy Atheron University of Arkansas."

Similar presentations


Ads by Google