Send pictures from the server (PC side) to the client (Android phone side) [Go]

Source: Internet
Author: User

Send pictures from the server (PC side) to the client (Android phone side) and display the picture on the phone page. (Note: The purpose of this paper is to realize the function, not to consider efficiency, pending follow-up. )

1. Server-side

1 intport=9090;2 3 4 /**5 * How to send files6 * This defines the server port as 9090,ip address 192.168.1.17 * Set the path of the picture to be transferred to "Images/icon.png"8 * The images folder is placed in the root directory of this project, we can access the image file by relative path9  */Ten  One  A Private voidSendpic () { -  -     Try { the  -         //Creating a server -Java.net.ServerSocket SS =NewJava.net.ServerSocket (port); -         //wait for the client to access, blocking here until a client Access server +Java.net.Socket client =ss.accept (); -         //Create a file input stream for the picture that will be sent +Java.io.FileInputStream fin =NewJava.io.FileInputStream ("Images/icon.png"); A         //gets the output stream of the socket and wraps it into a data output stream atJava.io.DataOutputStream Dou =NewJava.io.DataOutputStream (Client - . Getoutputstream ()); -         //writes the file data length to the output stream -Dou.writeint (Fin.available ());//Note: This does not take into account that the picture is too large to exceed the int range, so that there is a memory overflow -         //read the actual picture data into the byte[] data -         byte[] data =New byte[Fin.available ()]; in fin.read (data); -         //write picture data to the output stream to dou.write (data); + Dou.flush (); -}Catch(IOException e) { the e.printstacktrace (); *     } $ Panax Notoginseng  -}

2. Client (Android phone)

1  Public classFrontpageextendsAndroid.app.ActivityImplementsRunnable {2 3      Public voidonCreate (Android.os.Bundle savedinstancestate) {4 5         Super. OnCreate (savedinstancestate);6 Setcontentview (r.layout.frontpage);7 8         //start a thread that reads data from a socket and processes it9 NewThread ( This). Start ();//This class inherits the Runnable interface, so the objects of this class are passed in when the thread is createdTen     } One  AString IP = "192.168.1.1"; -     intPort = 9090; -Android.widget.ImageView image;//The ImageView object that is used to display the received picture the  -     /** - * Because the Read method of the input stream is blocked, to prevent it from affecting other data processing of the main interface, start a thread to read the data in the input stream and process the data accordingly -      */ +      Public voidrun () { -  +         Try { A             //Create a link to the server atJava.net.Socket sc =Newjava.net.Socket (IP, port); -             //ImageView object to get the image displayed on the interface -Image =(Android.widget.ImageView) Findviewbyid (r.id.image); -             //get the input stream of the socket and wrap it into a basic data input stream -Java.io.DataInputStream din =NewJava.io.DataInputStream (SC - . getInputStream ()); in  -             //continuous monitoring of data in the input stream to              while(true) { +                 //Read and process data when there is data in the stream -                 if(din.available () > 0) { the  *                     //to create a data array and read the streams in the array $                     byte[] data =New byte[Din.readint ()];//Note This also does not handle cases where the picture size exceeds the range of intPanax Notoginseng din.read (data); -  the                     //The Bitmap object bitmap is created based on the read file data, because bitmap is to be used in the later inner class, so it is defined as +                     //Final Type A                     FinalAndroid.graphics.Bitmap Bitmap =android.graphics.BitmapFactory the. Decodebytearray (data, 0, data.length); +  -                     //display a picture on a imageview $                     //here because the components in view are thread insecure, use this approach provided by Android (see "Attached 2" below) $Image.post (NewRunnable () { -  -                          Public voidrun () { the                             //display the bitmap to the interface - Image.setimagebitmap (bitmap);Wuyi                         } the                     }); -                 } Wu  -                 //thread rest 1s AboutThread.Sleep (1000); $             } -  -}Catch(Exception e) { - e.printstacktrace (); A         } +     } the  -}

3, Main.xml

1<?xml version= "1.0" encoding= "Utf-8"?>2<linearlayout android:orientation= "Vertical"3Android:layout_width= "Fill_parent"4android:layout_height= "Fill_parent"5xmlns:android1= "Http://schemas.android.com/apk/res/android"6Xmlns:android= "Http://schemas.android.com/apk/res/android" >7<imageview android:layout_width= "Wrap_content"8android:layout_height= "Wrap_content"9Android:id= "@+id/image"Tenandroid:gravity= "Center"/> One</LinearLayout>

Attached 1, Android to do communication when you need to add a permission in Androidmainfest:

Java code
    1. <uses-permission android:name= "Android.permission.INTERNET" ></uses-permission>

Attached 2, about the Android View component thread is unsafe, many predecessors have done a detailed analysis of this, I will not repeat this, only to provide you with a reference to the address: http://www.cnblogs.com/playing/archive/ 2011/03/24/1993583.html

With 3, send and receive data, there are many ways to choose, the byte array method used here there are a few things to note:

A, new byte[], the incoming array size is int, so we have to consider that when the file data goes beyond the scope of the integer type, it needs to be supplemented by other means to ensure the integrity of the data.

b, when reading data from a file, and writing to the output stream, the code used in the article is:

Java code
    1. byte[] data = new byte[fin.available ()];//Create an array of file data to hold
    2. Fin.read (data);//Read the file data into the array
    3. Dou.write (data);//writes an array to the output stream

But there is no shortage of lazy code friends to write:

Java code
    1. Dou.write (Fin.read (New Byte[fin.available ()));
    2. As soon as we look at the JDK a little bit: read () If there is no more data because it has reached the end of the file, then the <code>-1 is returned, so it is not our file data to write to the output stream! </code>

What's more, it reads:

Java code
    1. Dou.write (New Byte[fin.available ()));//No file data is read into the array at all

The above several errors are I have encountered, this kind of very detailed questions to check out will be compared to time, I hope you code friends warning!

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.