Network programming example of Android based on TCP and URL protocol [demo source code download], androiddemo

Source: Internet
Author: User

Network programming example of Android based on TCP and URL protocol [demo source code download], androiddemo

This article describes network programming for Android based on TCP and URL protocols. We will share this with you for your reference. The details are as follows:

Mobile phones are used as mobile terminals, so their computing and storage capabilities are limited. Its main advantage is its ease of carrying, its ability to open it at any time, and its mobile phone is always online. Therefore, network support is very important for mobile apps.

Android fully supports JDK's TCP and UDP network communication APIs. You can also use ServerSocket and Socket to establish network communication based on the TCP/IP protocol, or use ipvramsocket, datagrampacket is used to establish UDP-based network communication. Android also supports Network Communication APIs such as URLs and URLConnection provided by JDK. Android also has built-in HttpClient and HttpUrlConnection, which can easily send HTTP requests and obtain Http responses.

-- TCP-based programming

Programming with Socket and ServerSocket:

Network Programming is completed using multithreading and handler mechanism.

Note: Mobile Phone Wireless Internet access IP addresses are usually dynamically allocated by mobile operators and generally do not have their own fixed IP addresses. Therefore, server terminals are rarely run on mobile phones, the server usually runs on a server with a fixed IP address.

-- Access network resources must be placed in sub-Thread
-- You need to add the network access permission.
-- IP address, which cannot be written as 127.0.0.1.
-- Use the Handler mechanism to parse the returned data
-- Fix Garbled text

-- Use URL for Network Programming

-- Use a URL to access network resources

A URL object represents a uniform resource identifier. It refers to resources on the Internet. This resource can be used to make simple files or directories. It can also be a reference to more complex objects.

URL format: protocol: // host: port/resourceName

You can use the constructor to create a URL object. Once a URL object is obtained, you can call the following method to access the resources corresponding to the URL:

String getFile(): Get the Resource Name of the URL
String getHost(): Get the Host Name of the URL
String getPath(): Obtain the URL path
int getPort(): Get the URL port number
String getProtocol(): Get the protocol name of the URL
String getQuery(): Obtain the URL query string
InputStream url.openStream(): Open the URL Connection and return an InputStream that reads the resource.

Code writing:

1. Write the server:

Use Socket and ServerSocket:

Public class serverTest {public static void main (String [] args) {try {ServerSocket serverSocket = new ServerSocket (7777); System. out. println ("the server has started on port 7777"); while (true) {// There is a blocking function. If the method below the socket is not obtained, Socket socket = serverSocket is not executed. accept (); System. out. println ("A client has sent a request"); new ServerThread (socket ). start () ;}} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace ();}}}

ServerThread inherits Thread:

Public class ServerThread extends Thread {private Socket socket; OutputStream outputStream; public ServerThread (Socket socket) {this. socket = socket ;}@ Override public void run () {// TODO Auto-generated method stub try {outputStream = socket. getOutputStream (); outputStream. write ("server-side time" + new Date ()). getBytes ("UTF-8"); outputStream. flush (); outputStream. close ();} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace ();} super. run ();}}

2. Write the client:

Key code:

Public void click (View view) {new Thread () {public void run () {try {// The client obtains data from the server Socket client = new Socket ("169.254.244.141 ", 7777); BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (client. getInputStream (); String text = bufferedReader. readLine (); // TV. setText (text); // The thread multiplex Message msg = Message. obtain (); msg. what = 0x123; msg. obj = text; handler. sendMessage (msg);} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace ();}};}. start ();}

Get time from the server ~

As follows:

Appendix:Click here for the complete instance codeDownload from this site.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.