[转载] Android通过Socket发送大文件到服务器

android通过socket发送大文件到服务,并且在服务器接受完后返回一个结果给android。主要的是需要在android通过socket.getOutputStream()传送完文件后,需要关闭socket的OutputStream(socket.shutdownOutput();), 而并不是执行getOutputStream()对象的close()方法,如果执行这个方法,那么socket就关闭了,就接收不到服务器返回的结果 了。如果不关闭客户端的输出流,那么服务器端socket获取输入流对象后,调用这个对象的read方法会在执行完后一直处于等待状态,也就是read阻 塞。socket输入流不同于文件输入流,一般调用in.read(),如果返回-1代表就结束了,但是socket这个输入流的read不会返回-1, (如果客户端在发送完文件后不及时关闭);

android端代码:

  1. package com.roadview.drivermate.net;  
  2.   
  3. import java.io.DataInputStream;  
  4. import java.io.DataOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.net.InetSocketAddress;  
  8. import java.net.Socket;  
  9.   
  10. import android.util.Log;  
  11.   
  12. import com.roadview.drivermate.common.AppConst;  
  13.   
  14. public class SocketService {  
  15.   
  16.     String tag = "SocketService";  
  17.     File file=null;  
  18.     String sendinfo=null;     
  19.     //socket执行结果  
  20.     public int status;  
  21.       
  22.     public SocketService() {  
  23.         super();  
  24.     }  
  25.   
  26.     public SocketService(File file, String sendinfo) {  
  27.         super();  
  28.         this.file = file;  
  29.         this.sendinfo = sendinfo;  
  30.     }  
  31.   
  32.   
  33.     /** 
  34.      * 上传文件方法(图片,视频,录音) 
  35.      * @param file 文件对象 
  36.      * @param sendinfo  文件信息 
  37.      * @return 
  38.      */  
  39.     public String sendSocket() {  
  40.         String result = null;  
  41.         FileInputStream reader = null;  
  42.         DataOutputStream out = null;  
  43.         DataInputStream in = null;  
  44.         Socket socket = new Socket();  
  45.         byte[] buf = null;  
  46.   
  47.         try {  
  48.             // 连接Socket  
  49.             socket.connect(new InetSocketAddress(AppConst.ADDRESS,  
  50.                     AppConst.PORT), 1000);  
  51.   
  52.             // 1. 读取文件输入流  
  53.             reader = new FileInputStream(file);  
  54.             // 2. 将文件内容写到Socket的输出流中  
  55.             out = new DataOutputStream(socket.getOutputStream());  
  56.             out.writeInt(AppConst.UPLOAD);  
  57.             out.writeUTF(sendinfo);  
  58.   
  59.             int bufferSize = 20480; // 20K  
  60.             buf = new byte[bufferSize];  
  61.             int read = 0;  
  62.             // 将文件输入流 循环 读入 Socket的输出流中  
  63.             while ((read = reader.read(buf, 0, buf.length)) != -1) {  
  64.                 out.write(buf, 0, read);  
  65.             }  
  66.             Log.i(tag, "socket执行完成");  
  67.             out.flush();  
  68.             // 一定要加上这句,否则收不到来自服务器端的消息返回  
  69.             socket.shutdownOutput();  
  70.   
  71.             // //获取服务器端的相应  
  72.             in = new DataInputStream(socket.getInputStream());  
  73.             status = in.readInt();  
  74.             result = in.readUTF();  
  75.             Log.i(tag, "返回结果:" + status + "," + result);  
  76.   
  77.         } catch (Exception e) {  
  78.             Log.i(tag, "socket执行异常:" + e.toString());  
  79.         } finally {  
  80.             try {  
  81.                 // 结束对象  
  82.                 buf = null;  
  83.                 out.close();  
  84.                 in.close();  
  85.                 reader.close();  
  86.                 socket.close();  
  87.             } catch (Exception e) {  
  88.   
  89.             }  
  90.         }  
  91.         return result;  
  92.     }  
  93.   
  94. }  


服务器端代码1:

  1. package audioTest;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.DataInputStream;  
  5. import java.io.IOException;  
  6. import java.net.ServerSocket;  
  7. import java.net.Socket;  
  8. import java.util.Date;  
  9.   
  10. /**  
  11.  * 
  12.  *  该类是Socket服务端的入口 
  13.  */  
  14. public class Server extends Thread{  
  15.       
  16.     // 端口  
  17.     public static int port = 9999;  
  18.     private static ServerSocket server = null;  
  19.     // 存放录音文件的 文件夹  
  20.     private final String AUDIO_RECORD = "D:\\audio_record";  
  21.       
  22.     public void run() {  
  23.         if(server == null){  
  24.             try{  
  25.                 //1、新建ServerSocket实例  
  26.                 server = new ServerSocket(port);  
  27.             }catch(IOException e){  
  28.                 e.printStackTrace();  
  29.             }  
  30.         }  
  31.           
  32.         System.out.println(new Date().toString() + " \n 服务器启动...");  
  33.           
  34.         while(true){  
  35.             try{  
  36.                 //2、访问ServerSocket实例的accept方法取得一个客户端Socket对象  
  37.                 Socket client = server.accept();  
  38.                 if(client == null || client.isClosed()) continue;  
  39.                   
  40.                 // 判断客户端请求类型  
  41.                 DataInputStream in = new DataInputStream(new BufferedInputStream(client.getInputStream()));  
  42.                 switch (in.readInt()) {  
  43.                 // 上传文件  
  44.                 case 1:  
  45.                     new SocketUpLoad(client, AUDIO_RECORD).start();  
  46.                     break;  
  47.                 // 下载文件   
  48.                 case 2:  
  49.                     new SocketDownLoad(client, AUDIO_RECORD).start();  
  50.                     break;  
  51.                 default:  
  52.                     break;  
  53.                 }  
  54.                   
  55.                   
  56.             }catch(IOException ex){  
  57.                 ex.printStackTrace();  
  58.             }  
  59.         }  
  60.     }  
  61.   
  62.     public static void main(String[] args) {  
  63.         new Server().start();  
  64.     }  
  65.       
  66. }  


服务器端代码2:

    1. package com.roadview.drivermate.socket.service;  
    2.   
    3. import java.io.BufferedInputStream;  
    4. import java.io.BufferedOutputStream;  
    5. import java.io.DataInputStream;  
    6. import java.io.DataOutputStream;  
    7. import java.io.File;  
    8. import java.io.FileOutputStream;  
    9. import java.io.IOException;  
    10. import java.net.Socket;  
    11. import java.util.Date;  
    12.   
    13. public class SocketUpLoad extends Thread {  
    14.       
    15.     // socket对象  
    16.     private Socket client;  
    17.       
    18.     // 保存路径  
    19.     private String savepath=AppConst.WEBROOT+AppConst.WEBDIR+"\\";  
    20.       
    21.     //返回路径(相对路径)  
    22.     private String filepath="/"+AppConst.WEBDIR+"/";  
    23.       
    24.   
    25.     public SocketUpLoad(Socket client) {  
    26.         this.client = client;  
    27.     }  
    28.   
    29.     // 创建目录(不存在则创建)  
    30.     public File CreateDir(String dir) {  
    31.         File file = new File(dir);  
    32.         if (!file.exists()) {  
    33.             file.mkdirs();  
    34.         }  
    35.         return file;  
    36.     }  
    37.   
    38.     public void run() {  
    39.         if (client == null)  
    40.             return;  
    41.   
    42.         DataInputStream in = null;  
    43.         BufferedOutputStream fo = null;  
    44.         DataOutputStream out = null;  
    45.   
    46.         try {  
    47.             // 1、访问Socket对象的getInputStream方法取得客户端发送过来的数据流  
    48.             in = new DataInputStream(new BufferedInputStream(  
    49.                     client.getInputStream()));  
    50.   
    51.             String[] str = in.readUTF().split("\\|");  
    52.             //文件名  
    53.             String fileName =System.currentTimeMillis()+"."+ str[0].split("\\.")[1]; // 取得附带的文件名  
    54.             System.out.println(new Date().toString() + " \n 文件名为:"  
    55.                     + fileName);  
    56.             String filetype=str[1];  
    57.             String userid = str[2];// 取用户ID  
    58.             //存储路径  
    59.             savepath=savepath+filetype+"\\"+userid;  
    60.             if (savepath.endsWith("/") == false  
    61.                     && savepath.endsWith("\\") == false) {  
    62.                 savepath += "\\";  
    63.             }  
    64.             System.out.println("保存路径:"+savepath);  
    65.             //创建目录  
    66.             CreateDir(savepath);  
    67.                
    68.               
    69.             //返回文件名和路径  
    70.             filepath = filepath+filetype+"/"+userid+"/"+fileName;  
    71.             System.out.println("返回路径:"+filepath);  
    72.   
    73.             // 2、将数据流写到文件中  
    74.             fo = new BufferedOutputStream(new FileOutputStream(new File(  
    75.                     savepath+"\\"+fileName)));  
    76.   
    77.             int bytesRead = 0;  
    78.             byte[] buffer = new byte[1024];  
    79.             while ((bytesRead = in.read(buffer, 0, buffer.length)) != -1) {  
    80.                 fo.write(buffer, 0, bytesRead);  
    81.             }  
    82.             fo.flush();  
    83.             fo.close();  
    84.   
    85.             System.out.println(new Date().toString() + " \n 数据接收完毕");  
    86.   
    87.             // 3、获得Socket的输出流,返回一个值给客户端  
    88.             out = new DataOutputStream(new BufferedOutputStream(  
    89.                     client.getOutputStream()));  
    90.             out.writeInt(1);  
    91.             out.writeUTF(filepath);  
    92.             out.flush();  
    93.   
    94.         } catch (Exception ex) {  
    95.             ex.printStackTrace();  
    96.             try {  
    97.                 out.writeInt(0);  
    98.                 out.flush();  
    99.             } catch (IOException e) {  
    100.                 System.out.println(new Date().toString() + ":" + e.toString());  
    101.             }  
    102.         } finally {  
    103.             try {  
    104.                 out.close();  
    105.                 fo.close();  
    106.                 in.close();  
    107.                 client.close();  
    108.             } catch (IOException e) {  
    109.                 System.out.println(new Date().toString() + ":" + e.toString());  
    110.             }  
    111.         }  
    112.   
    113.     }  
    114. }  
posted @ 2015-01-03 00:53  chenlinyunyi  阅读(1153)  评论(0编辑  收藏  举报