Android中Socket大文件断点上传示例

Android中Socket大文件断点上传示例,第1张

概述什么是Socket?     所谓Socket通常也称作“套接字”,用于描述IP地址和端口,是一个通信连的句柄,应用程序通常通过“套接字”向网络发送请求或者应答网络请求,它就是网络通信过程中

什么是Socket?     

所谓Socket通常也称作“套接字”,用于描述IP地址和端口,是一个通信连的句柄,应用程序通常通过“套接字”向网络发送请求或者应答网络请求,它就是网络通信过程中端点的抽象表示。它主要包括以下两个协议:

TCP (Transmission Control Protocol 传输控制协议):传输控制协议,提供的是面向连接、可靠的字节流服务。当客户和服务器彼此交换数据前,必须先在双方之间建立一个TCP连接,之后才能传输数据。TCP提供超时重发,丢弃重复数据,检验数据,流量控制等功能,保证数据能从一端传到另一端。

UDP (User Datagram Protocl 用户数据报协议):用户数据报协议,是一个简单的面向数据报的运输层协议。UDP不提供可靠性,它只是把应用程序传给IP层的数据报发送出去,但是并不能保证它们能到达目的地。由于UDP在传输数据报前不用在客户和服务器之间建立一个连接,且没有超时重发等机制,故而传输速度很快。

详细解说如下:

TCP传输和UDP不一样,TCP传输是流式的,必须先建立连接,然后数据流沿已连接的线路(虚电路)传输。因此TCP的数据流不会像UDP数据报一样,每个数据报都要包含目标地址和端口,因为每个数据报要单独路由。TCP传输则只需要在建立连接时指定目标地址和端口就可以了。

形象的讲,TCP就像打电话,UDP就像发电报。宏观上来看UDP是不分客户端和服务端的。通信双方是平等的。微观上来讲只相对一个报文,发送端是客户端,监听端是服务端。发送端把数据报发给路由器就像把电报发给了邮局,后面的事情就是发送者无法控制,也无从知晓的了。所以说是不可靠的,可能会出现报文丢失而无从知晓。就像每张电报都要有收件人一样,每个数据报都要有目的地址和端口。

而TCP每次连接都是分客户端和服务端的。连接的发起者(相当与拨号打电话的人)是客户端,监听者(相当于在电话边等着接电话的人)是服务端。发起者指定要连接的服务器地址和端口(相当于拨号),监听者通过和发起者三次握手建立连接(相当于听到电话响去接电话)。建立连接后双方可以互相发送和接受数据(打电话)。

Java如何 *** 作Socket?

值得一提的是,Java分别为TCP和UDP提供了相应的类,TCP是java.NET中提供了两个类Socket和ServerSocket,分别用来表示双向连接的客户端和服务端。这是两个封装得非常好的类,使用起来很方便!UDP是java.Net.DatagramSocket.

127.0.0.1是回路地址,用于测试,相当于localhost本机地址,没有网卡,不设DNS都可以访问,端口地址在0~65535之间,其中0~1023之间的端口是用于一些知名的网络服务和应用,用户的普通网络应用程序应该使用1024以上的端口.

Socket通信模型如下:

服务器,使用ServerSocket监听指定的端口,端口可以随意指定(由于1024以下的端口通常属于保留端口,在一些 *** 作系统中不可以随意使用,所以建议使用大于1024的端口),等待客户连接请求,客户连接后,会话产生;在完成会话后,关闭连接。

客户端,使用Java socket通信对网络上某一个服务器的某一个端口发出连接请求,一旦连接成功,打开会话;会话完成后,关闭Socket。客户端不需要指定打开的端口,通常临时的、动态的分配一个1024以上的端口。

TCP网络连接模型:

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){//代表原来没有上传过此文件,往数据库添加一条绑定记录              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,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,buf,offset);                            }             buf[offset++] = (char) c;             break;         }       }       if ((c == -1) && (offset == 0)) return null;       return String.copyValueOf(buf,offset);   }       /**   * 读取流   * @param inStream   * @return 字节数组   * @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,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(?,?)",new Object[]{uploadfile.getabsolutePath(),sourceID});   }      public voID delete(file uploadfile){     sqliteDatabase db = dbOpenHelper.getWritableDatabase();     db.execsql("delete from uploadlog where uploadfilepath=?",new Object[]{uploadfile.getabsolutePath()});   }      public String getBindID(file uploadfile){     sqliteDatabase db = dbOpenHelper.getReadableDatabase();     Cursor cursor = db.rawquery("select sourceID from uploadlog where uploadfilepath=?",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  

<?xml version="1.0" enCoding="utf-8"?> <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  

<?xml version="1.0" enCoding="utf-8"?> <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>   <!-- 访问网络的权限 -->   <uses-permission androID:name="androID.permission.INTERNET"/>   <!-- 在SDCard中创建与删除文件权限 -->   <uses-permission androID:name="androID.permission.MOUNT_UNMOUNT_fileSYstemS"/>   <!-- 往SDCard写入数据权限 -->   <uses-permission androID:name="androID.permission.WRITE_EXTERNAL_STORAGE"/> </manifest> 

Java服务端:

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;// 监听端口   private boolean quit;// 是否退出   private Map<Long,fileLog> datas = new HashMap<Long,fileLog>();// 存放断点数据,最好改为数据库存放    public SocketServer(int port) {     this.port = port;     // 初始化线程池     executorService = Executors.newFixedThreadPool(Runtime.getRuntime()         .availableProcessors() * 50);   }    // 启动服务   public voID start() throws Exception {     ss = new ServerSocket(port);     while (!quit) {       Socket socket = ss.accept();// 接受客户端的请求       // 为支持多用户并发访问,采用线程池管理每一个用户的连接请求       executorService.execute(new SocketTask(socket));// 启动一个线程来处理请求     }   }    // 退出   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());         // 得到客户端发来的第一行协议数据:Content-Length=143253434;filename=xxx.3gp;sourceID=         // 如果用户初次上传文件,sourceID的值为空。         String head = StreamTool.readline(inStream);         System.out.println(head);         if (head != null) {           // 下面从协议数据中读取各种参数值           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()){//如果上传的文件发生重名,然后进行改名               filename = filename.substring(0,filename.indexOf(".")-1)+ dir.Listfiles().length+ filename.substring(filename.indexOf("."));               file = new file(dir,filename);             }             save(ID,file);           }else{// 如果上传的文件存在上传记录,读取上次的断点位置             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"));//读取断点位置               }             }           }                      OutputStream outStream = socket.getoutputStream();           String response = "sourceID="+ ID+ ";position="+ position+ "\r\n";           //服务器收到客户端的请求信息后,给客户端返回响应信息:sourceID=1274773833264;position=0           //sourceID由服务生成,唯一标识上传的文件,position指示客户端从文件的什么位置开始上传           outStream.write(response.getBytes());                      RandomAccessfile fileOutStream = new RandomAccessfile(file,"rwd");           if(position==0) fileOutStream.setLength(Integer.valueOf(filelength));//设置文件长度           fileOutStream.seek(position);//移动文件指定的位置开始写入数据           byte[] buffer = new byte[1024];           int len = -1;           int length = position;           while( (len=inStream.read(buffer)) != -1){//从输入流中读取数据写入到文件中             fileOutStream.write(buffer,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);//实时记录文件的最后保存位置             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) {     // 日后可以改成通过数据库存放     datas.put(ID,new fileLog(ID,savefile.getabsolutePath()));   }    // 当文件上传完毕,删除记录   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("服务器已经启动");     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("文件上传服务端");      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,len);       }       outSteam.close();       inStream.close();       return outSteam.toByteArray();   }  } 

运行效果如下:

AndroID前端控制:

后台监控日志:

下载后的文件路径:

 

源码下载地址:AndroidSocket_jb51.rar

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android中Socket大文件断点上传示例全部内容,希望文章能够帮你解决Android中Socket大文件断点上传示例所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1146951.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-31
下一篇2022-05-31

发表评论

登录后才能评论

评论列表(0条)

    保存