This example for you to share the Java based on the socket production of the download process, and related code for your reference, the specific content as follows
1. First set up a server to process information and transfer files to the client (computer)
I use a computer to open a WiFi, mobile phone connected with the use of Scoket transmission
ServerIP to change according to their actual situation. Ports can also be arbitrarily changed 0~65535, try to choose a little bigger
Import Java.io.BufferedInputStream;
Import Java.io.BufferedOutputStream;
Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.io.PrintWriter;
Import Java.net.ServerSocket;
Import Java.net.Socket; /** * Test the Android client interacts with the PC server via a socket server: Receive client information and send it back to the client * * @author ameyume * */public Class Server implements Ru
nnable {//defines the IP and port information for the transmission public static final String ServerIP = "192.168.155.1";
The defined 9888 port public static final int serverport = 9888;
The definition file, private file = null;
public static void Main (string[] args) {//Create a method thread that invokes the transport of threads Desktopserverthread = new Thread (new Server ());
Desktopserverthread.start (); public void Run () {try {System.out.println s:connecting ...
9888 ");
Create socket ServerSocket ServerSocket = new ServerSocket (serverport); while (true) {//waiting to accept client request Socket client = Serversocket.accePT (); System.out.println ("s:receiving ...")
9888 ");
try {//Accept client information BufferedReader in = new BufferedReader (New InputStreamReader (Client.getinputstream ()));
System.out.println ("S: Receiving client Information");
Read the client's information String str = In.readline ();
String str1 = str.substring (0,2);
String str2 = str.substring (2);
System.out.println (str); Locate the corresponding file according to the client's request and pass the value of the file size to the IF (Str.equals ("File_size")) {//define the file you want to transfer (I am writing a file under E disk) file = new file ("e:\\
a document ");
Input stream FileInputStream fis = new FileInputStream (file);
Output stream Bufferedinputstream bis = new Bufferedinputstream (FIS);
Calculates the size of the file to be transferred int sum = bis.available ();
Converts a file size of type int to string s = string.valueof (sum);
System.out.println (s); Create an output stream to send a file size information printwriter out = new PrintWriter (new BufferedWriter (New OutputStreamWriter (client.getoutputstre
AM ()), true);
Send the size information of the file out.println (s);
Close flow Out.flush ();
Bis.close (); else if (str1.equals ("OK")) {
int a = Integer.parseint (STR2);
The client receives the value of the file size, and then transmits the file according to the "OK" from the client bufferedoutputstream bos = new Bufferedoutputstream (Client.getoutputstream ());
System.out.println ("S: Start Transmission");
Start transfer if (true) {//input stream FileInputStream FIS = new FileInputStream (file);
Skip the previously transmitted bytes Fis.skip (a);
Buffer input stream Bufferedinputstream bis = new Bufferedinputstream (FIS);
int t =-1;
while ((t = Bis.read ()) >= 0) {bos.write (t);
String s = "transmitted";
Close flow Bos.flush ();
Bis.close ();
Bos.close ();
Serversocket.close ();
System.out.println ("s:received:" "+ S +" ");
} else {System.out. println ("Not receiver anything from client!");
The catch (Exception e) {System.out.println ("S:error 1");
E.printstacktrace ();
finally {client.close ();
System.out.println ("S:done.");
A catch (Exception e) {System.out.println ("S:error 2");
E.printstacktrace ();
}
}
}
2. To create a client, I'm using the Android Mainactivity.java (I was running on the phone)
Package com.xhy.zz;
Import android.app.Activity;
Import android.content.Intent;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.TextView;
public class Mainactivity extends activity {//define Handler public static Handler MyHandler;
Define Intent private Intent Intent;
Gets the control private TextView text_name;
Private TextView text_percent;
Private Button Btn_start;
Private Button btn_stop;
The file shows private TextView text_sel_file; @Override protected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated Method stub super.oncreate (Savedi
Nstancestate);
Setcontentview (R.layout.activity_main);
Text_name = (TextView) Findviewbyid (r.id.text_name);
Text_percent = (TextView) Findviewbyid (r.id.text_percent);
Btn_start = (Button) Findviewbyid (R.id.btn_start); Btn_stop = (Button) Findviewbyid (r.id.btn_stop); Return information for button one, showing progress MyHandler = new Handler () {@Override public void Handlemessage (msg) {Super.handlemessage
(msg);
if (msg.what = = 0x0001) {Bundle data = Msg.getdata ();
String str = data.getstring ("value");
Text_percent.settext (str);
}
}
};
An explicit way to invoke helloservice intent = new Intent (this, downservice.class); Set Startup button Click event Btn_start.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {//Open
Service StartService (intent);
}
});
Set Stop button click event Btn_stop.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {//Close service
StopService (Intent);
}
}); /*** * Called activity once returned value the callback method will be automatically invoked by the system/@Override protected void Onactivityresult (int requestcode, int resultcode
, Intent Intent) {super.onactivityresult (Requestcode, ResultCode, Intent); If the request code is 0//and the returned result code is 1//The requested activity may return multiple result codes if (Requestcode = 0 && ResultCode = = 1) {//Fetch data Bundle DATA = Intent.getextras ();
String str = data.getstring ("Files");
Display data text_sel_file.settext (str);
}
}
}
3.activity_main.xml file
<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" "Vertical" &
Gt <linearlayout android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:layout_margi ntop= "20DP" android:orientation= "horizontal" > <textview android:id= "@+id/text_name" Android:la Yout_width= "160DP" android:layout_height= "wrap_content" android:layout_gravity= "Center_vertical" Android : text= "1"/> <textview android:id= "@+id/text_percent" android:layout_width= "50DP" Android:lay out_height= "Wrap_content" android:layout_gravity= "center_vertical" android:layout_marginleft= "20DP" and roid:text= "0%"/> <linearlayout android:layout_width= "Wrap_content" android:layout_height= Ent "Android:layout_marginleft= "20DP" android:orientation= "vertical" > <button android:id= "@+id/btn_start"
Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "Start" /> <button android:id= "@+id/btn_stop" android:layout_width= "Wrap_content" Android:layo ut_height= "Wrap_content" android:text= "Stop"/> </LinearLayout> </linearlayout>
;
</LinearLayout>
4.DownService used to open a thread in the background to perform the download
Package com.xhy.zz;
Import Java.io.BufferedInputStream;
Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.io.PrintWriter;
Import java.net.InetAddress;
Import Java.net.Socket;
Import java.net.UnknownHostException;
Import Android.app.Service;
Import Android.content.Context;
Import android.content.Intent;
Import android.content.SharedPreferences;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.os.IBinder;
Import Android.os.Message;
Import Android.util.Log;
public class Downservice extends Service {private static final String TAG = "Socket_android";
The filename of the preferece mechanism operation is public static final String preference_name = "Downservice";
The operating mode of the preferece mechanism is public static int mode = Context.mode_private;
Thread private thread workthread;
Define file name private String filename= "file";
Port number private int port = 9888; PRivate Boolean isstop = false;
/*** * The method must be implemented * * @Override public ibinder onbind (Intent Intent) {return null;
@Override public void OnCreate () {super.oncreate ();
@Override public int Onstartcommand (Intent Intent, int flags, int startid) {log.v ("TCP", filename);
The method of establishing the transmission Runnable backgroundwork = new Runnable () {@Override public void run () {//Settitle ("Test socket Connection");
Socket socket = NULL;
Socket socket1 = null;
try {* * * Specifies the IP address of the server, which is the LAN address and, if you are using WiFi, the PC's WiFi IP address * ipconfig the IP address seen in the following: Ethernet adapter wireless network connection: * Connection-specific DNS Suffix.
: IP address .... * . . . . . . . . : 192.168.155.1 * * inetaddress serveraddr = inetaddress. Getbyname ("192.168.155.1");//Tcpserver.serverip Lo
G.D ("TCP", "c:connecting ...");
LOG.D ("TCP", filename + "" + port);
Apply server IP and port to establish Socket object, send request to server to get file size value Socket1 = new Socket (serveraddr, Port); String message = "---test_socket_android---";
LOG.D ("TCP", "c:sending:" "+ Message +" "); Send information through this object to the server printwriter out = new PrintWriter (new BufferedWriter (New OutputStreamWriter SOCKET1.G
Etoutputstream ()), true);
Sends the user input to the server out.println ("File_size");
Out.flush ();
Receive server information BufferedReader in = new BufferedReader (New InputStreamReader (Socket1.getinputstream ()));
Gets the file size String str1 = In.readline ();
LOG.D ("TCP", str1);
Convert file size to int int sum = integer.parseint (STR1);
LOG.D ("TCP", str1);
Turn off the input stream in.close ();
Sharedpreferences sharedpreferences = getsharedpreferences (Preference_name, MODE);
Sharedpreferences.editor Editor = sharedpreferences. Edit ();
Remove the bytes that have been transmitted int pre = Sharedpreferences.getint ("Downservice", 0);
int _pre = pre;
Converts it to a string to send to the service side string s = string.valueof (_pre);
Apply server's IP and port to create a socket object to send a request to the server again to get the file content socket = new Socket (serveraddr, port); Send a request to the server to get the character of the file PrintwritEr out1 = new PrintWriter (new BufferedWriter (New OutputStreamWriter (Socket.getoutputstream ())), true;
Out1.println ("OK" +s);
Out1.flush ();
Out.close ();
Define input stream Bufferedinputstream bis = new Bufferedinputstream (Socket.getinputstream ());
String file1 = filename;
String file; To determine if the phone is plugged into a sdcard, insert the file into the memory card if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {F
Ile sdcard = environment. getExternalStorageDirectory ();
SD Card Definition file = Sdcard.getcanonicalfile () + "/" + file1;
Definition file output stream FileOutputStream fos = new FileOutputStream (file,true);
try {int t =-1;
int downloaded = pre;
Defines the number of bytes per transmission byte[] Buff = new byte[8192];
LOG.I ("sum", Sum + "");
Starts writing the server-side file to the cell phone SD card while ((t = bis.read (Buff))!=-1) {if (Isstop = = true) {break;
} fos.write (buff, 0, T);
downloaded + = t; Store the progress of the transfer editor.putint ("Downservice", downloaded);
Editor.commit ();
When passed, the storage information is returned to zero if (downloaded = sum) {editor.putint ("Downservice", 0);
Editor.commit ();
//Get file transfer Progress float = ((downloaded *)/(float) sum);
int WI = (int) WB;
SYSTEM.OUT.PRINTLN (downloaded);
String str = string.valueof (WI) + "%"; Send the file's progress to baseactivity to display to the user message msg = new (); Generate message//Generate message Msg.what = 0x0001;
Set Message type//generate Bundle carry data Bundle to new Bundle ();
Data.putstring ("value", str);
Msg.setdata (data);
Use handler to send messages MainActivity.myHandler.sendMessage (msg);
//Turn off the input/output stream bis.close ();
Fos.flush ();
Fos.close ();
catch (Exception e) {bis.close ();
Fos.flush ();
Fos.close ();
} log.d (TAG, "from server: ' Received" + "");
catch (Unknownhostexception e) {log.e (TAG, "192.168.155.1 is Unkown server!");
catch (Exception e) {e.printstacktrace (); } Finally {try {socket.close ();
catch (Exception e) {e.printstacktrace ();
}
}
}
};
Workthread = new Thread (backgroundwork);
The IsAlive method is used to determine if the workthread thread is open if (!workthread.isalive ()) {//Generate a new thread workthread.start ();
LOG.V ("ServiceLife", "thread begins to work");
else {log.v ("Workthread", "thread has been called");
return start_sticky;
@Override public void OnDestroy () {Super.ondestroy ();
Use interrupt to interrupt the thread isstop = true;
LOG.V ("ServiceLife", "OnDestroy method called");
}
}
5, in the end don't forget to register Androidmanifest.xml
<uses-permission android:name= "Android.permission.INTERNET"/>
<uses-permission android:name= " Android.permission.MOUNT_UNMOUNT_FILESYSTEMS ">
</uses-permission>
<uses-permission android: Name= "Android.permission.WRITE_EXTERNAL_STORAGE" >
</uses-permission>
<service android:name= ". Downservice "></service>
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.