Android Socket Programming tài liệu, giáo án, bài giảng , luận văn, luận án, đồ án, bài tập lớn về tất cả các lĩnh vực k...
This Page Intentionally Left Blank Introduction to Socket Programming in Android Jules White Bradley Dept of Electrical and Computer Engineering Virginia Tech julesw@vt.edu What is a Socket? • A socket is a software endpoint that can plug into or be plugged into to create a bi-directional communication link between software processes • A socket is a common interface for performing network communication • Underneath the hood, Android’s HTTP client library is using sockets to send and receive data Socket Socket Socket Socket Java Sockets • In Java, a ServerSocket can receive new connections from a client • A client connects to a remote ServerSocket through a standard Socket instance • When the server receives the connection, it talks to the client using a standard socket Socket Socket Server Server Socket Socket InputStreams in Java • An InputStream is a stream of incoming byte data • An InputStream can be obtained from a Socket by using the getInputStream() method • In order 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 and returns the number of bytes read InputStream in = somesocket.getInputStream(); byte[] buffer = new byte[1024]; int bytesread = 0; while( (bytesread = in.read(buffer,0,buffer.length)) != -1){ //the buffer has been filled, something with the data } OutputStreams in Java • 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 the flush() method if you want to make sure that the data you have written has been output to disk or sent to the other end of the 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(); A Simple Socket-based Server • Example: public class ExampleServerSocket{ public void start() throws Exception { //Create a ServerSocket on port 9090 ServerSocket serversock = new ServerSocket(9090); while(running){ Socket client = serversock.accept(); OutputStream out = client.getOutputStream(); InputStream in = client.getInputStream(); //read and write some data from the streams out.close(); in.close(); client.close(); } } } A Simple Socket-based Client • Example: public class ExampleSocketClient{ public void start() throws Exception { Socket server = Socket( “127.0.0.1”, //the host or IP address to connect to 9090 //the port to connect to on that host ); OutputStream out = server.getOutputStream(); InputStream in = server.getInputStream(); out.write(“foo”.getBytes()); out.flush(); //VERY IMPORTANT // read some stuff… in.close(); out.close(); server.close(); } } Threading in Android • Socket and streaming network operations may take a significant amount of time • You cannot block the GUI thread for too long in Android • In order to connect as a client or receive connections, you must spawn threads to handle the communication • To spawn a Thread in Java, create a class that implements runnable and construct a new Thread object with it public class LongRunningWork implements Runnable { public void run(){ //do long running stuff here } public void threadMe(){ Thread t = new Thread(this); t.start(); } } What Should You Thread? • For the client, you need to thread the instantiation of the Socket and all read/write operations to it when it is connected • For the server, you need to have multiple threads • Some thread needs to call accept() • Some thread needs to manage reading/writing data for each client after a socket is returned from accept • The threading architecture is very important • Possible threading approaches: • Thread per connection • Eager spawning / thread pools • Half-sync / Half-async • Leader / Followers Synchronizing the GUI Thread with Others • Once approach that we have learned is to use a Handler to coordinate the exchange of work between the GUI and other threads • Another approach is to use the Android AsyncTask class • Android automatically manages the creation of Threads for AsyncTasks • An AsyncTask has three key methods that each run in a different thread context: • doInBackground() – runs in a NON-GUI thread • onProgressUpdate() – runs in the GUI thread • onPostExecute() – runs in the GUI thread • You create a subclass of AsyncTask and Android automatically runs each of your implementations of these methods in the correct thread context The AsyncTask Template Parameters • The types specified in the template parameters correspond to the parameter type of the doInBackground method, the type for the parameter to onProgressUpdate, and the type that is returned by doInBackground public class HttpTask extends AsyncTask { … protected Long doInBackground(String params) { //this runs in a background thread from the pool … publishProgress(some_new_progress_value); … return new ... This Page Intentionally Left Blank 2: Application Layer 1 Socket Programming TCP and UDP 2: Application Layer 2 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 2: Application Layer 3 TCP 2: Application Layer 4 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 2: Application Layer 5 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 (more in Chap 3) TCP provides reliable, in-order transfer of bytes (“pipe”) between client and server application viewpoint 2: Application Layer 6 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. 2: Application Layer 7 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) outToServer to network from network inFromServer inFromUser keyboard monitor Process clientSocket input stream input stream output stream TCP socket Client process client TCP socket 2: Application Layer 8 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 2: Application Layer 9 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 2: Application Layer 10 Example: Java client (TCP), cont. BufferedReader inFromServer = new @2011 Mihail L. Sichitiu 1 XML Review XML eXtensible Markup Language Simple text (Unicode) underneath Tags (like in HTML) are used to provide information about the data Similar to HTML, but: HTML is used to describe how to display the data XML is used to describe what is the data Often used to store and transfer data @2011 Mihail L. Sichitiu 2 HTML Example <html> <head><title>Here goes the title</title></head. <body> <h1>This is a header</h1> Here goes the text of the page </body> </html> @2011 Mihail L. Sichitiu 3 • Tags mean something specific to the browser • They are used for display XML Example <?xml version=“1.0”/> <person> <name> <first>Jose</first> <last>Barrios</last> </name> <email>jb@ucab.edu</email> <phone 555-456-1234 /> </person> @2011 Mihail L. Sichitiu 4 • Tags mean whatever the user wants them to mean • They are used to describe the data XML Rules Tags are enclosed in angle brackets. Tags come in pairs with start-tags and end-tags. Tags must be properly nested. <name><email>…</name></email> is not allowed. <name><email>…</email><name> is. Tags that do not have end-tags must be terminated by a ‘/’. Document has a single root element XML Documents are Trees @2011 Mihail L. Sichitiu 6 person name email phone first last @2010 Mihail L. Sichitiu 7 Android Manifest <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.helloandroid" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".HelloAndroid" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Attributes Questions? @2011 Mihail L. Sichitiu 8 Socket Programming and Multithreading The DNS Server project The purpose of this lesson is to show you how you can do socket programming in C#. Network programming in windows is possible with sockets. A socket is like a handle to a file. Socket programming resembles the file IO as does the Serial Communication. You can use sockets programming to have two applications communicate with each other. The two applications are typically on different computers but they can be on the same computer. For the two applications to talk to each other on the same or different computers using sockets, one application is generally a server that keeps listening to the incoming requests and the other application acts as a client and makes the connection to the server application. The server application can either accept or reject the connection. If the server accepts the connection, a dialog can begin with between the client and the server. Once the client is done with whatever it needs to do, it can close the connection with the server. Connections are expensive in the sense that servers allow finite connections to occur. During the time the client has an active connection; it can send the data to the server and/or receive the data. The complexity begins here. When either side (client or server) sends data the other side is supposed to read the data. But how will the other side know when data has arrived. There are two options - either the application needs to poll for the data at regular intervals or there needs to be some sort of mechanism that would enable application to get notifications for the application to read the data at that time. Well, Windows is an event driven system and the notification system seems an obvious and best choice here. So, the two applications that need to communicate with each other need to make a connection first. In order for the two applications to make connections, the two applications need to identify each other (or each other's computer). Computers on network have a unique identifier called IP address which is represented in dot-notation like 10.20.120.127, etc. Lets see how all this works in .NET. 1- The Server a. Implement the GUI shown below (call your project DNServer): b. Include the following using statements: • using System.Net • using System.Net.Sockets • using System.Collections • using System.Threading • using System.IO c. declare the following variables, objects, and resources: • public delegate void UpdateRichEditCallback(string text); • public AsyncCallback functionWorkerCallBack; • private Socket myMainSocket; • private System.Collections.ArrayList myWorkerSocketList = ArrayList.Synchronized(new System.Collections.ArrayList()); • private int myClientCount = 0; • private int myCurrentClientsCount = 0; d. name= richActivity name= txtIP name= txtPort name= buttonStart name= buttonStop name= txtClients name= buttonClear name= buttonClose IP address returned from GetIP() method which is called from the Form constructor GetIP( ) e. Constructor f. Test it! g. Our socket communication will follow the following steps. 1) Create a socket 2) Bind the socket to an address or end point 3) Listen for an incoming communications attempt 4) Accept the communication 5) Send and receive messages (packets) 6) Shutdown the communication channel 7) Close the socket connection String GetIP() { String strHostName = Dns.GetHostName(); // Find host by name IPHostEntry iphostentry = Dns.GetHostByName(strHostName); // Grab the first IP addresses String IPStr = ""; foreach(IPAddress ipaddress in iphostentry.AddressList) { IPStr = ipaddress.ToString(); return IPStr; } return IPStr; } public DNServer() { // The InitializeComponent() call is required for Windows Forms designer support. InitializeComponent(); // Display the local IP address on the GUI [...]... entity that created the request } } AsyncTask Example public class HttpTask extends AsyncTask { … protected Long doInBackground(String params) { Socket socket = new Socket( some_host,some_port); InputStream in = socket. getInputStream(); byte[] buff = new byte[1024]; float expectedsize = 12341234; int read = 0; float totalread = 0; while( (in.read(buff,0,buff.length)) != -1){ totalread ... communication • Underneath the hood, Android s HTTP client library is using sockets to send and receive data Socket Socket Socket Socket Java Sockets • In Java, a ServerSocket can receive new connections... remote ServerSocket through a standard Socket instance • When the server receives the connection, it talks to the client using a standard socket Socket Socket Server Server Socket Socket InputStreams... Simple Socket- based Server • Example: public class ExampleServerSocket{ public void start() throws Exception { //Create a ServerSocket on port 9090 ServerSocket serversock = new ServerSocket(9090);