Android中使用Socket怎么實(shí)現(xiàn)文件斷點(diǎn)上傳功能

今天就跟大家聊聊有關(guān)Android中使用Socket怎么實(shí)現(xiàn)文件斷點(diǎn)上傳功能,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

創(chuàng)新互聯(lián)建站是一家專(zhuān)業(yè)提供晉寧企業(yè)網(wǎng)站建設(shè),專(zhuān)注與成都做網(wǎng)站、成都網(wǎng)站建設(shè)、H5高端網(wǎng)站建設(shè)、小程序制作等業(yè)務(wù)。10年已為晉寧眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專(zhuān)業(yè)網(wǎng)站制作公司優(yōu)惠進(jìn)行中。

什么是Socket

所謂Socket通常也稱(chēng)作“套接字”,用于描述IP地址和端口,是一個(gè)通信連的句柄,應(yīng)用程序通常通過(guò)“套接字”向網(wǎng)絡(luò)發(fā)送請(qǐng)求或者應(yīng)答網(wǎng)絡(luò)請(qǐng)求,它就是網(wǎng)絡(luò)通信過(guò)程中端點(diǎn)的抽象表示。它主要包括以下兩個(gè)協(xié)議:

TCP (Transmission Control Protocol 傳輸控制協(xié)議):傳輸控制協(xié)議,提供的是面向連接、可靠的字節(jié)流服務(wù)。當(dāng)客戶和服務(wù)器彼此交換數(shù)據(jù)前,必須先在雙方之間建立一個(gè)TCP連接,之后才能傳輸數(shù)據(jù)。TCP提供超時(shí)重發(fā),丟棄重復(fù)數(shù)據(jù),檢驗(yàn)數(shù)據(jù),流量控制等功能,保證數(shù)據(jù)能從一端傳到另一端。

UDP (User Datagram Protocl 用戶數(shù)據(jù)報(bào)協(xié)議):用戶數(shù)據(jù)報(bào)協(xié)議,是一個(gè)簡(jiǎn)單的面向數(shù)據(jù)報(bào)的運(yùn)輸層協(xié)議。UDP不提供可靠性,它只是把應(yīng)用程序傳給IP層的數(shù)據(jù)報(bào)發(fā)送出去,但是并不能保證它們能到達(dá)目的地。由于UDP在傳輸數(shù)據(jù)報(bào)前不用在客戶和服務(wù)器之間建立一個(gè)連接,且沒(méi)有超時(shí)重發(fā)等機(jī)制,故而傳輸速度很快。

詳細(xì)解說(shuō)如下:

TCP傳輸和UDP不一樣,TCP傳輸是流式的,必須先建立連接,然后數(shù)據(jù)流沿已連接的線路(虛電路)傳輸。因此TCP的數(shù)據(jù)流不會(huì)像UDP數(shù)據(jù)報(bào)一樣,每個(gè)數(shù)據(jù)報(bào)都要包含目標(biāo)地址和端口,因?yàn)槊總€(gè)數(shù)據(jù)報(bào)要單獨(dú)路由。TCP傳輸則只需要在建立連接時(shí)指定目標(biāo)地址和端口就可以了。

形象的講,TCP就像打電話,UDP就像發(fā)電報(bào)。宏觀上來(lái)看UDP是不分客戶端和服務(wù)端的。通信雙方是平等的。微觀上來(lái)講只相對(duì)一個(gè)報(bào)文,發(fā)送端是客戶端,監(jiān)聽(tīng)端是服務(wù)端。發(fā)送端把數(shù)據(jù)報(bào)發(fā)給路由器就像把電報(bào)發(fā)給了郵局,后面的事情就是發(fā)送者無(wú)法控制,也無(wú)從知曉的了。所以說(shuō)是不可靠的,可能會(huì)出現(xiàn)報(bào)文丟失而無(wú)從知曉。就像每張電報(bào)都要有收件人一樣,每個(gè)數(shù)據(jù)報(bào)都要有目的地址和端口。

而TCP每次連接都是分客戶端和服務(wù)端的。連接的發(fā)起者(相當(dāng)與撥號(hào)打電話的人)是客戶端,監(jiān)聽(tīng)者(相當(dāng)于在電話邊等著接電話的人)是服務(wù)端。發(fā)起者指定要連接的服務(wù)器地址和端口(相當(dāng)于撥號(hào)),監(jiān)聽(tīng)者通過(guò)和發(fā)起者三次握手建立連接(相當(dāng)于聽(tīng)到電話響去接電話)。建立連接后雙方可以互相發(fā)送和接受數(shù)據(jù)(打電話)。

Java如何操作Socket?

值得一提的是,Java分別為T(mén)CP和UDP提供了相應(yīng)的類(lèi),TCP是java.NET中提供了兩個(gè)類(lèi)Socket和ServerSocket,分別用來(lái)表示雙向連接的客戶端和服務(wù)端。這是兩個(gè)封裝得非常好的類(lèi),使用起來(lái)很方便!UDP是java.Net.DatagramSocket.

127.0.0.1是回路地址,用于測(cè)試,相當(dāng)于localhost本機(jī)地址,沒(méi)有網(wǎng)卡,不設(shè)DNS都可以訪問(wèn),端口地址在0~65535之間,其中0~1023之間的端口是用于一些知名的網(wǎng)絡(luò)服務(wù)和應(yīng)用,用戶的普通網(wǎng)絡(luò)應(yīng)用程序應(yīng)該使用1024以上的端口.

Socket通信模型如下:

Android中使用Socket怎么實(shí)現(xiàn)文件斷點(diǎn)上傳功能

服務(wù)器,使用ServerSocket監(jiān)聽(tīng)指定的端口,端口可以隨意指定(由于1024以下的端口通常屬于保留端口,在一些操作系統(tǒng)中不可以隨意使用,所以建議使用大于1024的端口),等待客戶連接請(qǐng)求,客戶連接后,會(huì)話產(chǎn)生;在完成會(huì)話后,關(guān)閉連接。

客戶端,使用Java socket通信對(duì)網(wǎng)絡(luò)上某一個(gè)服務(wù)器的某一個(gè)端口發(fā)出連接請(qǐng)求,一旦連接成功,打開(kāi)會(huì)話;會(huì)話完成后,關(guān)閉Socket??蛻舳瞬恍枰付ù蜷_(kāi)的端口,通常臨時(shí)的、動(dòng)態(tài)的分配一個(gè)1024以上的端口。

TCP網(wǎng)絡(luò)連接模型:

Android中使用Socket怎么實(shí)現(xiàn)文件斷點(diǎn)上傳功能

Android中使用Socket怎么實(shí)現(xiàn)文件斷點(diǎn)上傳功能

Android客戶端程序代分析:

UploadActivity.java  

package com.android.upload; 
import java.io.File;  
import java.io.OutputStream;  
import java.io.PushbackInputStream;  
import java.io.RandomAccessFile;  
import java.net.Socket;  
  
import android.app.Activity;  
import android.os.Bundle;  
import android.os.Environment;  
import android.os.Handler;  
import android.os.Message;  
import android.view.View;  
import android.view.View.OnClickListener; 
import android.widget.Button;  
import android.widget.EditText;  
import android.widget.ProgressBar;  
import android.widget.TextView;  
import android.widget.Toast;  
  
import com.android.service.UploadLogService;  
import com.android.socket.utils.StreamTool; 
 
  
public class UploadActivity extends Activity {  
  private EditText filenameText;  
  private TextView resulView;  
  private ProgressBar uploadbar;  
  private UploadLogService logService;  
  private boolean start=true; 
  private Handler handler = new Handler(){  
    @Override  
    public void handleMessage(Message msg) {  
      int length = msg.getData().getInt("size");  
      uploadbar.setProgress(length);  
      float num = (float)uploadbar.getProgress()/(float)uploadbar.getMax();  
      int result = (int)(num * 100);  
      resulView.setText(result+ "%");  
      if(uploadbar.getProgress()==uploadbar.getMax()){  
        Toast.makeText(UploadActivity.this, R.string.success, 1).show();  
      }  
    }  
  };  
    
  @Override  
  public void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.main);  
      
    logService = new UploadLogService(this);  
    filenameText = (EditText)this.findViewById(R.id.filename);  
    uploadbar = (ProgressBar) this.findViewById(R.id.uploadbar);  
    resulView = (TextView)this.findViewById(R.id.result);  
    Button button =(Button)this.findViewById(R.id.button);  
    Button button1 =(Button)this.findViewById(R.id.stop);  
    button1 .setOnClickListener(new OnClickListener() { 
       
      @Override 
      public void onClick(View v) { 
        start=false; 
         
      } 
    }); 
    button.setOnClickListener(new View.OnClickListener() {  
      @Override  
      public void onClick(View v) {  
        start=true; 
        String filename = filenameText.getText().toString();  
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  
          File uploadFile = new File(Environment.getExternalStorageDirectory(), filename);  
          if(uploadFile.exists()){  
            uploadFile(uploadFile);  
          }else{  
            Toast.makeText(UploadActivity.this, R.string.filenotexsit, 1).show();  
          }  
        }else{  
          Toast.makeText(UploadActivity.this, R.string.sdcarderror, 1).show();  
        }  
      }  
    });  
  }  
  /** 
   * 上傳文件 
   * @param uploadFile 
   */  
  private void uploadFile(final File uploadFile) {  
    new Thread(new Runnable() {       
      @Override  
      public void run() {  
        try {  
          uploadbar.setMax((int)uploadFile.length());  
          String souceid = logService.getBindId(uploadFile);  
          String head = "Content-Length="+ uploadFile.length() + ";filename="+ uploadFile.getName() + ";sourceid="+  
            (souceid==null? "" : souceid)+"\r\n";  
          Socket socket = new Socket("192.168.1.78",7878);  
          OutputStream outStream = socket.getOutputStream();  
          outStream.write(head.getBytes());  
            
          PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());    
          String response = StreamTool.readLine(inStream);  
          String[] items = response.split(";");  
          String responseid = items[0].substring(items[0].indexOf("=")+1);  
          String position = items[1].substring(items[1].indexOf("=")+1);  
          if(souceid==null){//代表原來(lái)沒(méi)有上傳過(guò)此文件,往數(shù)據(jù)庫(kù)添加一條綁定記錄  
            logService.save(responseid, uploadFile);  
          }  
          RandomAccessFile fileOutStream = new RandomAccessFile(uploadFile, "r");  
          fileOutStream.seek(Integer.valueOf(position));  
          byte[] buffer = new byte[1024];  
          int len = -1;  
          int length = Integer.valueOf(position);  
          while(start&&(len = fileOutStream.read(buffer)) != -1){  
            outStream.write(buffer, 0, len);  
            length += len;  
            Message msg = new Message();  
            msg.getData().putInt("size", length);  
            handler.sendMessage(msg);  
          }  
          fileOutStream.close();  
          outStream.close();  
          inStream.close();  
          socket.close();  
          if(length==uploadFile.length()) logService.delete(uploadFile);  
        } catch (Exception e) {  
          e.printStackTrace();  
        }  
      }  
    }).start();  
  }  
}  

StreamTool.java  

package com.android.socket.utils; 
 
import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.PushbackInputStream; 
 
public class StreamTool { 
    
   public static void save(File file, byte[] data) throws Exception { 
     FileOutputStream outStream = new FileOutputStream(file); 
     outStream.write(data); 
     outStream.close(); 
   } 
    
   public static String readLine(PushbackInputStream in) throws IOException { 
      char buf[] = new char[128]; 
      int room = buf.length; 
      int offset = 0; 
      int c; 
loop:    while (true) { 
        switch (c = in.read()) { 
          case -1: 
          case '\n': 
            break loop; 
          case '\r': 
            int c2 = in.read(); 
            if ((c2 != '\n') && (c2 != -1)) in.unread(c2); 
            break loop; 
          default: 
            if (--room < 0) { 
              char[] lineBuffer = buf; 
              buf = new char[offset + 128]; 
              room = buf.length - offset - 1; 
              System.arraycopy(lineBuffer, 0, buf, 0, offset); 
               
            } 
            buf[offset++] = (char) c; 
            break; 
        } 
      } 
      if ((c == -1) && (offset == 0)) return null; 
      return String.copyValueOf(buf, 0, offset); 
  } 
    
  /** 
  * 讀取流 
  * @param inStream 
  * @return 字節(jié)數(shù)組 
  * @throws Exception 
  */ 
  public static byte[] readStream(InputStream inStream) throws Exception{ 
      ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); 
      byte[] buffer = new byte[1024]; 
      int len = -1; 
      while( (len=inStream.read(buffer)) != -1){ 
        outSteam.write(buffer, 0, len); 
      } 
      outSteam.close(); 
      inStream.close(); 
      return outSteam.toByteArray(); 
  } 
} 

UploadLogService.java  

package com.android.service; 
 
import java.io.File; 
 
import android.content.Context; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
 
public class UploadLogService { 
  private DBOpenHelper dbOpenHelper; 
   
  public UploadLogService(Context context){ 
    this.dbOpenHelper = new DBOpenHelper(context); 
  } 
   
  public void save(String sourceid, File uploadFile){ 
    SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); 
    db.execSQL("insert into uploadlog(uploadfilepath, sourceid) values(&#63;,&#63;)", 
        new Object[]{uploadFile.getAbsolutePath(),sourceid}); 
  } 
   
  public void delete(File uploadFile){ 
    SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); 
    db.execSQL("delete from uploadlog where uploadfilepath=&#63;", new Object[]{uploadFile.getAbsolutePath()}); 
  } 
   
  public String getBindId(File uploadFile){ 
    SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); 
    Cursor cursor = db.rawQuery("select sourceid from uploadlog where uploadfilepath=&#63;",  
        new String[]{uploadFile.getAbsolutePath()}); 
    if(cursor.moveToFirst()){ 
      return cursor.getString(0); 
    } 
    return null; 
  } 
} 

DBOpenHelper.java  

package com.android.service; 
 
import android.content.Context; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 
 
public class DBOpenHelper extends SQLiteOpenHelper { 
 
  public DBOpenHelper(Context context) { 
    super(context, "upload.db", null, 1); 
  } 
 
  @Override 
  public void onCreate(SQLiteDatabase db) { 
    db.execSQL("CREATE TABLE uploadlog (_id integer primary key autoincrement, uploadfilepath varchar(100), sourceid varchar(10))"); 
  } 
 
  @Override 
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    db.execSQL("DROP TABLE IF EXISTS uploadlog"); 
    onCreate(db);     
  } 
 
} 

main.xml  

<&#63;xml version="1.0" encoding="utf-8"&#63;> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" 
  > 
<TextView  
  android:layout_width="fill_parent"  
  android:layout_height="wrap_content"  
  android:text="@string/filename" 
  /> 
   
  <EditText  
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:text="022.jpg" 
    android:id="@+id/filename" 
    /> 
     
  <Button  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:text="@string/button" 
    android:id="@+id/button" 
    /> 
  <Button  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:text="暫停" 
    android:id="@+id/stop" 
    /> 
  <ProgressBar  
      android:layout_width="fill_parent"  
      android:layout_height="20px" 
       
      android:id="@+id/uploadbar" 
      />  
  <TextView  
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:gravity="center" 
    android:id="@+id/result" 
    />   
</LinearLayout> 

AndroidManifest.xml  

<&#63;xml version="1.0" encoding="utf-8"&#63;> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
  package="com.android.upload" 
  android:versionCode="1" 
  android:versionName="1.0" > 
 
  <uses-sdk android:minSdkVersion="8" /> 
 
  <application 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" > 
    <activity 
      android:name=".UploadActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
        <action android:name="android.intent.action.MAIN" /> 
 
        <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
    </activity> 
  </application> 
  <!-- 訪問(wèn)網(wǎng)絡(luò)的權(quán)限 --> 
  <uses-permission android:name="android.permission.INTERNET"/> 
  <!-- 在SDCard中創(chuàng)建與刪除文件權(quán)限 --> 
  <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> 
  <!-- 往SDCard寫(xiě)入數(shù)據(jù)權(quán)限 --> 
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
</manifest> 

Java服務(wù)端:

SocketServer.javapackage com.android.socket.server; 
 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.OutputStream; 
import java.io.PushbackInputStream; 
import java.io.RandomAccessFile; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
import java.util.HashMap; 
import java.util.Map; 
import java.util.Properties; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
 
import com.android.socket.utils.StreamTool; 
 
public class SocketServer { 
  private String uploadPath="D:/uploadFile/"; 
  private ExecutorService executorService;// 線程池 
  private ServerSocket ss = null; 
  private int port;// 監(jiān)聽(tīng)端口 
  private boolean quit;// 是否退出 
  private Map<Long, FileLog> datas = new HashMap<Long, FileLog>();// 存放斷點(diǎn)數(shù)據(jù),最好改為數(shù)據(jù)庫(kù)存放 
 
  public SocketServer(int port) { 
    this.port = port; 
    // 初始化線程池 
    executorService = Executors.newFixedThreadPool(Runtime.getRuntime() 
        .availableProcessors() * 50); 
  } 
 
  // 啟動(dòng)服務(wù) 
  public void start() throws Exception { 
    ss = new ServerSocket(port); 
    while (!quit) { 
      Socket socket = ss.accept();// 接受客戶端的請(qǐng)求 
      // 為支持多用戶并發(fā)訪問(wèn),采用線程池管理每一個(gè)用戶的連接請(qǐng)求 
      executorService.execute(new SocketTask(socket));// 啟動(dòng)一個(gè)線程來(lái)處理請(qǐng)求 
    } 
  } 
 
  // 退出 
  public void quit() { 
    this.quit = true; 
    try { 
      ss.close(); 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
  } 
 
  public static void main(String[] args) throws Exception { 
    SocketServer server = new SocketServer(7878); 
    server.start(); 
  } 
 
  private class SocketTask implements Runnable { 
    private Socket socket; 
 
    public SocketTask(Socket socket) { 
      this.socket = socket; 
    } 
 
    @Override 
    public void run() { 
      try { 
        System.out.println("accepted connenction from " 
            + socket.getInetAddress() + " @ " + socket.getPort()); 
        PushbackInputStream inStream = new PushbackInputStream( 
            socket.getInputStream()); 
        // 得到客戶端發(fā)來(lái)的第一行協(xié)議數(shù)據(jù):Content-Length=143253434;filename=xxx.3gp;sourceid= 
        // 如果用戶初次上傳文件,sourceid的值為空。 
        String head = StreamTool.readLine(inStream); 
        System.out.println(head); 
        if (head != null) { 
          // 下面從協(xié)議數(shù)據(jù)中讀取各種參數(shù)值 
          String[] items = head.split(";"); 
          String filelength = items[0].substring(items[0].indexOf("=") + 1); 
          String filename = items[1].substring(items[1].indexOf("=") + 1); 
          String sourceid = items[2].substring(items[2].indexOf("=") + 1); 
          Long id = System.currentTimeMillis(); 
          FileLog log = null; 
          if (null != sourceid && !"".equals(sourceid)) { 
            id = Long.valueOf(sourceid); 
            log = find(id);//查找上傳的文件是否存在上傳記錄 
          } 
          File file = null; 
          int position = 0; 
          if(log==null){//如果上傳的文件不存在上傳記錄,為文件添加跟蹤記錄 
            String path = new SimpleDateFormat("yyyy/MM/dd/HH/mm").format(new Date()); 
            File dir = new File(uploadPath+ path); 
            if(!dir.exists()) dir.mkdirs(); 
            file = new File(dir, filename); 
            if(file.exists()){//如果上傳的文件發(fā)生重名,然后進(jìn)行改名 
              filename = filename.substring(0, filename.indexOf(".")-1)+ dir.listFiles().length+ filename.substring(filename.indexOf(".")); 
              file = new File(dir, filename); 
            } 
            save(id, file); 
          }else{// 如果上傳的文件存在上傳記錄,讀取上次的斷點(diǎn)位置 
            file = new File(log.getPath());//從上傳記錄中得到文件的路徑 
            if(file.exists()){ 
              File logFile = new File(file.getParentFile(), file.getName()+".log"); 
              if(logFile.exists()){ 
                Properties properties = new Properties(); 
                properties.load(new FileInputStream(logFile)); 
                position = Integer.valueOf(properties.getProperty("length"));//讀取斷點(diǎn)位置 
              } 
            } 
          } 
           
          OutputStream outStream = socket.getOutputStream(); 
          String response = "sourceid="+ id+ ";position="+ position+ "\r\n"; 
          //服務(wù)器收到客戶端的請(qǐng)求信息后,給客戶端返回響應(yīng)信息:sourceid=1274773833264;position=0 
          //sourceid由服務(wù)生成,唯一標(biāo)識(shí)上傳的文件,position指示客戶端從文件的什么位置開(kāi)始上傳 
          outStream.write(response.getBytes()); 
           
          RandomAccessFile fileOutStream = new RandomAccessFile(file, "rwd"); 
          if(position==0) fileOutStream.setLength(Integer.valueOf(filelength));//設(shè)置文件長(zhǎng)度 
          fileOutStream.seek(position);//移動(dòng)文件指定的位置開(kāi)始寫(xiě)入數(shù)據(jù) 
          byte[] buffer = new byte[1024]; 
          int len = -1; 
          int length = position; 
          while( (len=inStream.read(buffer)) != -1){//從輸入流中讀取數(shù)據(jù)寫(xiě)入到文件中 
            fileOutStream.write(buffer, 0, len); 
            length += len; 
            Properties properties = new Properties(); 
            properties.put("length", String.valueOf(length)); 
            FileOutputStream logFile = new FileOutputStream(new File(file.getParentFile(), file.getName()+".log")); 
            properties.store(logFile, null);//實(shí)時(shí)記錄文件的最后保存位置 
            logFile.close(); 
          } 
          if(length==fileOutStream.length()) delete(id); 
          fileOutStream.close();          
          inStream.close(); 
          outStream.close(); 
          file = null; 
        } 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } finally { 
        try { 
          if(socket != null && !socket.isClosed()) socket.close(); 
        } catch (IOException e) {} 
      } 
    } 
 
  } 
 
  public FileLog find(Long sourceid) { 
    return datas.get(sourceid); 
  } 
 
  // 保存上傳記錄 
  public void save(Long id, File saveFile) { 
    // 日后可以改成通過(guò)數(shù)據(jù)庫(kù)存放 
    datas.put(id, new FileLog(id, saveFile.getAbsolutePath())); 
  } 
 
  // 當(dāng)文件上傳完畢,刪除記錄 
  public void delete(long sourceid) { 
    if (datas.containsKey(sourceid)) 
      datas.remove(sourceid); 
  } 
 
  private class FileLog { 
    private Long id; 
    private String path; 
     
    public FileLog(Long id, String path) { 
      super(); 
      this.id = id; 
      this.path = path; 
    } 
 
    public Long getId() { 
      return id; 
    } 
 
    public void setId(Long id) { 
      this.id = id; 
    } 
 
    public String getPath() { 
      return path; 
    } 
 
    public void setPath(String path) { 
      this.path = path; 
    } 
 
  } 
} 
ServerWindow.javapackage com.android.socket.server; 
 
import java.awt.BorderLayout; 
import java.awt.Frame; 
import java.awt.Label; 
import java.awt.event.WindowEvent; 
import java.awt.event.WindowListener; 
 
public class ServerWindow extends Frame{ 
  private SocketServer server; 
  private Label label; 
   
  public ServerWindow(String title){ 
    super(title); 
    server = new SocketServer(7878); 
    label = new Label(); 
    add(label, BorderLayout.PAGE_START); 
    label.setText("服務(wù)器已經(jīng)啟動(dòng)"); 
    this.addWindowListener(new WindowListener() { 
      @Override 
      public void windowOpened(WindowEvent e) { 
        new Thread(new Runnable() {      
          @Override 
          public void run() { 
            try { 
              server.start(); 
            } catch (Exception e) { 
              e.printStackTrace(); 
            } 
          } 
        }).start(); 
      } 
       
      @Override 
      public void windowIconified(WindowEvent e) { 
      } 
       
      @Override 
      public void windowDeiconified(WindowEvent e) { 
      } 
       
      @Override 
      public void windowDeactivated(WindowEvent e) { 
      } 
       
      @Override 
      public void windowClosing(WindowEvent e) { 
         server.quit(); 
         System.exit(0); 
      } 
       
      @Override 
      public void windowClosed(WindowEvent e) { 
      } 
       
      @Override 
      public void windowActivated(WindowEvent e) { 
      } 
    }); 
  } 
  /** 
   * @param args 
   */ 
  public static void main(String[] args) { 
    ServerWindow window = new ServerWindow("文件上傳服務(wù)端");  
    window.setSize(300, 300);  
    window.setVisible(true); 
  } 
 
} 
StreamTool.javapackage com.android.socket.utils; 
 
import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.PushbackInputStream; 
 
public class StreamTool { 
    
   public static void save(File file, byte[] data) throws Exception { 
     FileOutputStream outStream = new FileOutputStream(file); 
     outStream.write(data); 
     outStream.close(); 
   } 
    
   public static String readLine(PushbackInputStream in) throws IOException { 
      char buf[] = new char[128]; 
      int room = buf.length; 
      int offset = 0; 
      int c; 
loop:    while (true) { 
        switch (c = in.read()) { 
          case -1: 
          case '\n': 
            break loop; 
          case '\r': 
            int c2 = in.read(); 
            if ((c2 != '\n') && (c2 != -1)) in.unread(c2); 
            break loop; 
          default: 
            if (--room < 0) { 
              char[] lineBuffer = buf; 
              buf = new char[offset + 128]; 
              room = buf.length - offset - 1; 
              System.arraycopy(lineBuffer, 0, buf, 0, offset); 
               
            } 
            buf[offset++] = (char) c; 
            break; 
        } 
      } 
      if ((c == -1) && (offset == 0)) return null; 
      return String.copyValueOf(buf, 0, offset); 
  } 
    
  /** 
  * 讀取流 
  * @param inStream 
  * @return 字節(jié)數(shù)組 
  * @throws Exception 
  */ 
  public static byte[] readStream(InputStream inStream) throws Exception{ 
      ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); 
      byte[] buffer = new byte[1024]; 
      int len = -1; 
      while( (len=inStream.read(buffer)) != -1){ 
        outSteam.write(buffer, 0, len); 
      } 
      outSteam.close(); 
      inStream.close(); 
      return outSteam.toByteArray(); 
  } 
 
} 

看完上述內(nèi)容,你們對(duì)Android中使用Socket怎么實(shí)現(xiàn)文件斷點(diǎn)上傳功能有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。

文章題目:Android中使用Socket怎么實(shí)現(xiàn)文件斷點(diǎn)上傳功能
地址分享:http://bm7419.com/article8/pccoop.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供、小程序開(kāi)發(fā)、微信公眾號(hào)品牌網(wǎng)站制作、App設(shè)計(jì)微信小程序

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

小程序開(kāi)發(fā)