After completing this module, you will be able to: Send and receive data between client and server. Java.net Provides networking-related classes, including stream and datagram sockets, Internet Protocol, and generic HTTP handling. Android.net.http Contains classes for manipulating SSL certificates.
After completing this module, you will be able to: Send and receive data between client and server. Java.net Provides networking-related classes, including stream and datagram sockets, Internet Protocol, and generic HTTP handling. Android.net.http Contains classes for manipulating SSL certificates.
After completing this module, you will be able to: Send and receive data between client and server. Java.net Provides networking-related classes, including stream and datagram sockets, Internet Protocol, and generic HTTP handling. Android.net.http Contains classes for manipulating SSL certificates.
Department of Software Engineering, Faculty of Information Technology, University of Science Ho Chi Minh City, Viet Nam Networking with Android Android Course 2011 University of Science HCM City . Objectives After completing this module, you will able to: Send and receive data between client and server.
2 Android Course 2011 University of Science HCM City . Contents Using TCP Using UDP Using HTTP Get Request Using HTTP Post Request Using HttpURLConnection Using URLConnection 3 Android Course 2011 University of Science HCM City . Note Working with Network requires the following permissions in AndroidManifest.xml: <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 4 Android Course 2011 University of Science HCM City . Android SDK networking packages Package Description java.net Provides networking-related classes, including stream and datagram sockets, Internet Protocol, and generic HTTP handling. This is the multipurpose networking resource. Experienced Java developers can create applications right away with this familiar package. java.io Though not explicitly networking, it's very important. Classes in this package are used by sockets and connections provided in other Java packages. They're also used for interacting with local files (a frequent occurrence when interacting with the network). java.nio Contains classes that represent buffers of specific data types. Handy for network communications between two Java language-based end points. org.apache.* Represents a number of packages that provide fine control and functions for HTTP communications. You might recognize Apache as the popular open source Web server. 5 Android Course 2011 University of Science HCM City . Android SDK networking packages
Package Description android.net Contains additional network access sockets beyond the core java.net.* classes. This package includes the URI class, which is used frequently in Android application development beyond traditional networking. android.net.http Contains classes for manipulating SSL certificates. android.net.wifi Contains classes for managing all aspects of WiFi (802.11 wireless Ethernet) on the Android platform. Not all devices are equipped with WiFi capability, particularly as Android makes headway in the "flip-phone" strata of cell phones from manufacturers like Motorola and LG. android.telephony.gsm Contains classes required for managing and sending SMS (text) messages. Over time, an additional package will likely be introduced to provide similar functions on non- GSM networks, such as CDMA, or something like android.telephony.cdma. 6 Android Course 2011 University of Science HCM City . Socket API for applications to read and write data from TCP/IP or UDP/IP File abstraction (open, read, write, close) TCP: connection-oriented protocol monitor error-free delivery slower than UDP UDP: connectionless protocol not monitor error-free delivery faster than TCP 7 Android Course 2011 University of Science HCM City . Ports The so called well known ports are those ports in the range of 0 to 1023 only the operating system or an Administrator of the system can access these. They are used for common services such as web servers (port 80) or e-mail servers (port 25). Registered Ports are in the range of 1024 to 49151. Sun's NEO Object Request Broker: port numbers 1047 and 1048. Shockwave: port number 1626. Dynamic and/or Private Ports are those from 49152 through 65535 and are open for use without restriction.
8 Android Course 2011 University of Science HCM City . Getting the ip address of your phone's network private String getLocalIpAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface .getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf .getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { Log.e(DEBUG", ex.toString()); } return null; } 9 Android Course 2011 University of Science HCM City . Using TCP
10 Android Course 2011 University of Science HCM City . Creating a connection at client-side Using IP Address: Socket client =new Socket("10.0.2.15", Integer.parseInt("9999")); Using local IP Address: String ip = getLocalIpAddress(); Socket client =new Socket(ip, Integer.parseInt("9999")); Using server name (DNS): Socket client =new Socket(www.mycomputer.net", 9999); Using host name: InetAddress serverAddr = InetAddress.getByName(10.0.2.15"); serverAddr = InetAddress.getByName(www.mycomputer.net"); Socket client=new Socket(serverAddr, Integer.parseInt(port)); Using local host name: serverAddr = InetAddress.getByName("localhost"); Socket client=new Socket(serverAddr, Integer.parseInt(port)); 11 Android Course 2011 University of Science HCM City . Creating a connection at client-side try { InetAddress serverAddr = InetAddress.getByName("localhost"); Socket client=new Socket(serverAddr,Integer.parseInt(port)); // Socket is now ready to send and receive data
// close connection client.close(); } catch (NumberFormatException e) { // write e.getMessage() to logcat } catch (UnknownHostException e) { // write e.getMessage() to logcat } catch (IOException e) { // write e.getMessage() to logcat } 12 Android Course 2011 University of Science HCM City . Receiving a connection request at server-side try { ServerSocket ss = new ServerSocket(9999); while (true) { Socket server = ss.accept(); Log.d("TCP Server", "Client Connect"); // Socket is now ready to send and receive data
// close connection server.close(); } } catch (IOException e) { // Write e.getMessage() to logcat } 13 Android Course 2011 University of Science HCM City . Sending data Using BufferedWriter: OutputStream os = socket.getOutputStream(); BufferedWriter writer = new BufferedWriter(new InputStreamReader(os)); Using PrintWriter: OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os, true);
14 Android Course 2011 University of Science HCM City . Receiving data Using BufferedReader: InputStream is = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 15 Android Course 2011 University of Science HCM City . Sending and Receiving data at server-side ServerSocket ss = new ServerSocket(9999); while (true) { Socket server = ss.accept(); Log.d("TCP Server", "Client Connect");
InputStream is = server.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader( is)); String a = br.readLine(); String b = br.readLine();
OutputStream os = server.getOutputStream(); PrintWriter pr = new PrintWriter(os, true); float c = Float.parseFloat(a) + Float.parseFloat(b); pr.println(c);
server.close(); } 16 Android Course 2011 University of Science HCM City . Sending and Receiving data at client-side InetAddress serverAddr = InetAddress.getByName("localhost"); Socket client = new Socket(serverAddr, Integer.parseInt(port));
OutputStream os = client.getOutputStream(); PrintWriter pw = new PrintWriter(os, true); pw.println(a); pw.println(b);
InputStream is = client.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); output = br.readLine();
client.close(); 17 Android Course 2011 University of Science HCM City . Using UDP
18 Android Course 2011 University of Science HCM City . Sending and Receiving data at server-side /* Retrieve the ServerName */ InetAddress serverAddr = InetAddress.getByName(SERVERIP); /* Create new UDP-Socket */ DatagramSocket socket = new DatagramSocket(SERVERPORT, serverAddr); /* By magic we know, how much data will be waiting for us */ byte[] buf = new byte[17];
/* Prepare a UDP-Packet that can * contain the data we want to receive */ DatagramPacket packet = new DatagramPacket(buf, buf.length);
/* Receive the UDP-Packet */ socket.receive(packet); InetAddress clientAddr = packet.getAddress(); int clientPort = packet.getPort(); String s = "Thanks"; buf = s.getBytes(); packet = new DatagramPacket(buf, buf.length, clientAddr, clientPort); socket.send(packet); 19 Android Course 2011 University of Science HCM City . Sending and Receiving data at client-side // Retrieve the ServerName InetAddress serverAddr = InetAddress.getByName(SERVERIP); /* Create new UDP-Socket */ DatagramSocket socket = new DatagramSocket();
/* Prepare some data to be sent. */ byte[] buf = ("Hello from Client").getBytes();
/* Create UDP-packet with * data & destination(url+port) */ DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, SERVERPORT);
/* Send out the packet */ socket.send(packet);
socket.receive(packet); 20 Android Course 2011 University of Science HCM City . Using HTTP Get Request HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI("http://w3mentor.com/")); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity() .getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String page = sb.toString(); System.out.println(page); 21 Android Course 2011 University of Science HCM City . Using HTTP Get Request HttpClient client = new DefaultHttpClient(); HttpGet method = new HttpGet("http://w3mentor.com/download.aspx?key=valueGoesHere"); client.execute(method); 22 Android Course 2011 University of Science HCM City . Using HTTP Post Request HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost("http://w3mentor.com/Upload.aspx"); List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("filename", "xyz")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity( postParameters); request.setEntity(formEntity); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity() .getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String result = sb.toString(); return result; 23 Android Course 2011 University of Science HCM City . Using HttpURLConnection URL url = new URL("http://www.developer.android.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line = ""; while ((line = rd.readLine()) != null) { // do something } 24 Android Course 2011 University of Science HCM City . Using URLConnection URL url = new URL("http://www.developer.android.com"); URLConnection conn = url.openConnection(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line = ""; while ((line = rd.readLine()) != null) { // do something } 25 Android Course 2011 University of Science HCM City . Questions or Discussions
26 Android Course 2011 University of Science HCM City . References & Further readings Networking with Android http://www.ibm.com/developerworks/opensource/library/os-android- networking/ http://www.java2s.com/Code/Android/Network/CatalogNetwork.htm Android Http Services http://w3mentor.com/learn/category/java/android- development/android-http-services/ Android Http Access http://www.vogella.com/articles/AndroidNetworking/article.html Socket Programming http://www.edumobile.org/android/android-development/socket- programming/ Socket Programming in Android Applications http://android10.org/index.php/articlesgeneralprogramming/262- socket-programming-in-android-applications Android Emulator as server in Socket communication http://www.coderanch.com/t/434412/Android/Mobile/Android- Emulator-as-server-Socket 27