550 likes | 748 Views
CSCE 4013: Mobile Systems Programming. Nilanjan Banerjee. University of Arkansas Fayetteville, AR nilanb@uark.edu http:// mpss.csce.uark.edu/mobsys /. Mobile Systems Programming (Acknowledgment to Deepa Shinde and Cindy Atheron. Socket Programming. TCP and UDP. a host-local ,
E N D
CSCE 4013: Mobile Systems Programming Nilanjan Banerjee University of Arkansas Fayetteville, AR nilanb@uark.edu http://mpss.csce.uark.edu/mobsys/ Mobile Systems Programming (Acknowledgment to DeepaShinde and Cindy Atheron
Socket Programming TCP and UDP
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 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 Goal: learn how to build client/server application that communicate using sockets
process process TCP with buffers, variables TCP with buffers, variables socket socket Socket-programming using TCP Socket: a door between application process and end-end-transport protocol (UCP or TCP) TCP service: reliable transfer of bytesfrom one process to another controlled by application developer controlled by application developer controlled by operating system controlled by operating system internet host or server host or server 2: Application Layer
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 Socket programming with TCP 2: Application Layer
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. Stream jargon
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) Socket programming with TCP Client process client TCP socket
create socket, connect to hostid, port=x create socket, port=x, for incoming request: clientSocket = Socket() welcomeSocket = ServerSocket() TCP connection setup wait for incoming connection request connectionSocket = welcomeSocket.accept() send request using clientSocket read request from connectionSocket write reply to connectionSocket read reply from clientSocket close connectionSocket close clientSocket Client/server socket interaction: TCP Server (running on hostid) Client
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
Example: Java client (TCP), cont. Create input stream attached to socket BufferedReaderinFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + '\n'); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } } Send line to server Read line from server
Example: Java server (TCP) import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; ServerSocketwelcomeSocket = new ServerSocket(6789); while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReaderinFromClient = 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
Example: Java server (TCP), cont DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + '\n'; outToClient.writeBytes(capitalizedSentence); } } } Create output stream, attached to socket Read in line from socket Write out line to socket End of while loop, loop back and wait for another client connection
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 UDP provides unreliable transfer of groups of bytes (“datagrams”) between client and server application viewpoint Socket programming with UDP
Client create socket, port=x, for incoming request: serverSocket = DatagramSocket() create socket, clientSocket = DatagramSocket() Create, address (hostid, port=x, send datagram request using clientSocket read request from serverSocket write reply to serverSocket specifying client host address, port number read reply from clientSocket close clientSocket Client/server socket interaction: UDP Server (running on hostid)
Example: Java client (UDP) Client process Input: receives packet (TCP received “byte stream”) Output: sends packet (TCP sent “byte stream”) client UDP socket
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
Example: Java client (UDP), cont. Create datagram with data-to-send, length, IP addr, port 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(); } } Send datagram to server Read datagram from server
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
Example: Java server (UDP), cont String sentence = new String(receivePacket.getData()); InetAddressIPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); DatagramPacketsendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } } } Get IP addr port #, of sender Create datagram to send to client Write out datagram to socket End of while loop, loop back and wait for another datagram 2: Application Layer
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);
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.
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.
App to Download jpg file • Step1 Add permissions to AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET" /> • 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;
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.
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{ HttpURLConnectionhttpConn = (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; } }
App to Download jpg file • Step 4 Modify the Main.xml code <?xml version="1.0" encoding="utf-8"?> <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" /> </LinearLayout>
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; }
Step 6 Test 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); }
App to Download jpg file Step 7:Output
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).
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“
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;
SMS Sending Input from the user (i.e., the phone no, text message and sendSMS is implemented). • Step 4 Write the SMS class public class SMS extends Activity { Button btnSendSMS; EditTexttxtPhoneNo; EditTexttxtMessage; /** 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(); } }); } }
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); SmsManagersms = SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null, message, pi, null); }
Receiving SMS Step 1
Receiving SMS • Step 2 • In the AndroidManifest.xml file add the <receiver> element so that incoming SMS messages can be intercepted by the SmsReceiver class. <receiver android:name=".SmsReceiver"> <intent-filter> <action android:name= "android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>
Receiving SMS • Step 3 import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.SmsMessage; import android.widget.Toast;