java基於Socket做一個簡略下載器。本站提示廣大學習愛好者:(java基於Socket做一個簡略下載器)文章只能為提供參考,不一定能成為您想要的結果。以下是java基於Socket做一個簡略下載器正文
本文實例為年夜家分享了java基於Socket制造下載器的進程,及相干代碼,供年夜家參考,詳細內容以下
1.起首要樹立一個辦事器用來處置信息並給客戶端傳輸文件(電腦)
我是用電腦開了一個WIFI,手機連上後應用scoket傳輸的
SERVERIP要依據本身現實情形更改。端口也能夠隨意更改0~65535,盡可能選年夜一點
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; /** * 測試Android客戶端與PC辦事器經由過程socket停止交互 辦事器端:吸收客戶真個信息並回送給客戶 * * @author Ameyume * */ public class Server implements Runnable { //界說傳輸的IP和端口信息 public static final String SERVERIP = "192.168.155.1"; //界說的9888端口 public static final int SERVERPORT = 9888; //界說文件 private File file = null; public static void main(String[] args) { //樹立挪用線程履行傳輸的辦法 Thread desktopServerThread = new Thread(new Server()); desktopServerThread.start(); } public void run() { try { System.out.println("S: Connecting...9888"); //創立套接字 ServerSocket serverSocket = new ServerSocket(SERVERPORT); while (true) { // 期待接收客戶端要求 Socket client = serverSocket.accept(); System.out.println("S: Receiving...9888"); try { // 接收客戶端信息 BufferedReader in = new BufferedReader( new InputStreamReader(client.getInputStream())); System.out.println("S: 吸收客戶端信息"); // 讀取客戶真個信息 String str = in.readLine(); String str1 = str.substring(0,2); String str2 = str.substring(2); System.out.println(str); //依據客戶真個要求找到對應的文件並把文件年夜小的值傳曩昔 if (str.equals("file_size")) { //界說你要傳輸的文件(我這裡寫的是E盤下的某個文件) file = new File("E:\\某個文件"); //輸出流 FileInputStream fis = new FileInputStream(file); //輸入流 BufferedInputStream bis = new BufferedInputStream(fis); //盤算將要傳輸的文件年夜小 int sum = bis.available(); //將int型的文件年夜小轉成字符串 String s = String.valueOf(sum); System.out.println(s); //樹立輸入流以發送文件年夜小的信息 PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(client.getOutputStream())), true); //發送文件的年夜小信息 out.println(s); //封閉流 out.flush(); bis.close(); } else if (str1.equals("ok")) { int a = Integer.parseInt(str2); // 客戶端收到文件年夜小的值後,再依據客戶端傳來的“ok”將文件傳曩昔 BufferedOutputStream bos = new BufferedOutputStream( client.getOutputStream()); System.out.println("S: 開端傳輸"); //開端傳輸 if (true) { //輸出流 FileInputStream fis = new FileInputStream(file); //跳過後面曾經傳輸過的字節 fis.skip(a); //緩沖輸出流 BufferedInputStream bis = new BufferedInputStream( fis); int t = -1; while ((t = bis.read()) >= 0) { bos.write(t); } String s = "已傳輸"; //封閉流 bos.flush(); bis.close(); bos.close(); // serverSocket.close(); System.out.println("S: Received: '" + s + "'"); } } else { System.out .println("Not receiver anything from client!"); } } catch (Exception e) { System.out.println("S: Error 1"); e.printStackTrace(); } finally { client.close(); System.out.println("S: Done."); } } } catch (Exception e) { System.out.println("S: Error 2"); e.printStackTrace(); } } }
2.再樹立一個客戶端,我這裡用的是安卓寫的MainActivity.java(我是在手機上運轉的)
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 { // 界說Handler public static Handler myHandler; // 界說intent private Intent intent; // 獲得控件 private TextView text_name; private TextView text_percent; private Button btn_start; private Button btn_stop; // 文件顯示 private TextView text_sel_file; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); 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); // 按鈕一的前往信息,顯示進度 myHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 0x0001) { Bundle data = msg.getData(); String str = data.getString("value"); text_percent.setText(str); } } }; // 顯式的方法挪用HelloService intent = new Intent(this, DownService.class); // 設置啟動按鈕點擊事宜 btn_start.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 開啟辦事 startService(intent); } }); // 設置停滯按鈕點擊事宜 btn_stop.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 封閉辦事 stopService(intent); } }); } /*** * 被挪用Activity一旦前往值 該回調辦法將被體系主動挪用 */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); // 假如要求碼是0 // 而且前往的成果碼為1 // 要求的Activity能夠前往多種成果碼 if (requestCode == 0 && resultCode == 1) { // 掏出數據 Bundle data = intent.getExtras(); String str = data.getString("files"); // 顯示數據 text_sel_file.setText(str); } } }
3.activity_main.xml文件
<?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" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:orientation="horizontal" > <TextView android:id="@+id/text_name" android:layout_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:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginLeft="20dp" android:text="0%"/> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" 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:layout_height="wrap_content" android:text="stop" /> </LinearLayout> </LinearLayout> </LinearLayout>
4.DownService用於在後台開啟線程履行下載
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"; // Preferece機制操作的文件名 public static final String PREFERENCE_NAME = "DownService"; // Preferece機制的操作形式 public static int MODE = Context.MODE_PRIVATE; // 線程 private Thread workThread; // 界說文件名 private String filename="file"; // 端標語 private int port = 9888; private boolean isStop = false; /*** * 必需要完成的辦法 */ @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); // 樹立傳輸的辦法 Runnable backgroundWork = new Runnable() { @Override public void run() { // setTitle("測試Socket銜接"); Socket socket = null; Socket socket1 = null; try { /* * 指定Server的IP地址,此地址為局域網地址,假如是應用WIFI上彀,則為PC機的WIFI IP地址 * 在ipconfig檢查到的IP地址以下: Ethernet adapter 無線收集銜接: * Connection-specific DNS Suffix . : IP Address. . . . * . . . . . . . . : 192.168.155.1 */ InetAddress serverAddr = InetAddress .getByName("192.168.155.1");// TCPServer.SERVERIP Log.d("TCP", "C: Connecting..."); Log.d("TCP", filename + " " + port); // 運用Server的IP和端口樹立Socket對象,向辦事端發送要求獲得文件年夜小的值 socket1 = new Socket(serverAddr, port); String message = "---Test_Socket_Android---"; Log.d("TCP", "C: Sending: '" + message + "'"); // 將信息經由過程這個對象來發送給Server PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter( socket1.getOutputStream())), true); // 把用戶輸出的內容發送給server out.println("file_size"); out.flush(); // 吸收辦事器信息 BufferedReader in = new BufferedReader( new InputStreamReader(socket1.getInputStream())); // 獲得文件年夜小 String str1 = in.readLine(); Log.d("TCP", str1); // 將文件年夜小轉成int型 int sum = Integer.parseInt(str1); Log.d("TCP", str1); // 封閉輸出流 in.close(); SharedPreferences sharedPreferences = getSharedPreferences( PREFERENCE_NAME, MODE); SharedPreferences.Editor editor = sharedPreferences .edit(); //掏出曾經傳輸了的字節 int pre = sharedPreferences.getInt("DownService", 0); int _pre = pre; //將其轉化為字符串以便發送給辦事端 String s = String.valueOf(_pre); // 運用Server的IP和端口樹立Socket對象再次向辦事端發送要求,以獲得文件內容 socket = new Socket(serverAddr, port); // 向辦事端發送要求取得文件的字符 PrintWriter out1 = new PrintWriter( new BufferedWriter(new OutputStreamWriter( socket.getOutputStream())), true); out1.println("ok"+s); out1.flush(); out.close(); // 界說輸出流 BufferedInputStream bis = new BufferedInputStream( socket.getInputStream()); String file1 = filename; String file; // 斷定手機能否拔出了SDCard,是則將文件拔出內存卡 if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File sdCard = Environment .getExternalStorageDirectory(); // SD卡界說文件 file = sdCard.getCanonicalFile() + "/" + file1; // 界說文件輸入流 FileOutputStream fos = new FileOutputStream(file,true); try { int t = -1; int downloaded = pre; // 界說每次傳輸的字節數 byte[] buff = new byte[8192]; Log.i("sum", sum + ""); // 開端將辦事真個文件寫動手機SD卡中 while ((t = bis.read(buff)) != -1) { if (isStop == true) { break; } fos.write(buff, 0, t); downloaded += t; //將傳輸的進度存儲起來 editor.putInt("DownService", downloaded); editor.commit(); //當傳完了則把存儲信息歸零 if (downloaded == sum) { editor.putInt("DownService", 0); editor.commit(); } // 取得文件傳輸的進度 float wb = ((downloaded * 100) / (float) sum); int wi = (int) wb; System.out.println(downloaded); String str = String.valueOf(wi) + "%"; // 將文件的傳輸進度給送給BaseActivity,以顯示給用戶 Message msg = new Message(); // 生成新聞 // 生成新聞 msg.what = 0x0001; // 設置新聞類型 // 生成Bundle攜帶數據 Bundle data = new Bundle(); data.putString("value", str); msg.setData(data); // 應用Handler發送新聞 MainActivity.myHandler.sendMessage(msg); } // 封閉輸出輸入流 bis.close(); fos.flush(); fos.close(); } catch (Exception e) { bis.close(); fos.flush(); fos.close(); } } Log.d(TAG, "From server:'已吸收" + "'"); } 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); // isAlive辦法用於斷定workThread線程能否被開啟 if (!workThread.isAlive()) { // 生成新線程 workThread.start(); Log.v("ServiceLife", "線程開端任務"); } else { Log.v("workThread", "線程曾經被挪用"); } return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); // 應用interrupt方法中止該線程 isStop = true; Log.v("ServiceLife", "onDestroy辦法被挪用"); } }
5、最初別忘了注冊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>
以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。