传输文件时丢包(文件)

时间:2017-03-15 17:04:31

标签: java android

使客户端和服务器通过网络传输多个文件。 Windows上的服务器,客户端Android。 面对丢包问题(如果服务器是Java),文件(如果是c ++中的serv)可能是因为异步传输。 找到所需延迟的位置(如果服务器在java上运行,那么在每个批处理之后,如果在每个文件传输后c ++中的serv),但速度越低,所需的延迟就越大。 也许我做错了什么? 这里的答案Java multiple file transfer over socket没有帮助

客户端

    Socket socket = new Socket(ip, Integer.parseInt(portC));
       PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
       out.println("name.zip");
       Log.d("Out", "n-OK");

       byte[] bytes = new byte[1024];
       InputStream inf = new BufferedInputStream(new FileInputStream(file));
       OutputStream outf = new BufferedOutputStream(socket.getOutputStream());

       int count;
           int totalRead = 0;
       while ((count = inf.read(bytes)) != -1) {
            outf.write(bytes, 0, count);

               totalRead += count;
               System.out.println("\nread:"+count+"\ntotalread: "+totalRead);
 //delay if java server
 //try { Thread.sleep(100); } catch (InterruptedException err) { err.printStackTrace(); }
       }

       outf.flush();
       inf.close();
       outf.close();
       out.close();
       socket.close();
           lf.delete();
       Log.d("Out", "f-OK");

 //delay if с++ server
 //try { Thread.sleep(500); } catch (InterruptedException err) { err.printStackTrace(); }

服务器

    String file = fl + "/" + name;
     try {
          InputStream inf = new BufferedInputStream(mySocket.getInputStream());
          OutputStream outf = new BufferedOutputStream(new FileOutputStream(file));

          int count;
          byte[] bytes = new byte[1024];

          while (size > 0 && (count = inf.read(bytes, 0, (int)Math.min(bytes.length, size))) != -1) {  
               outf.write(bytes, 0, count);   
            size -= count;    
            System.out.println("\nread:"+count+"\ntotalread: "+size);
        } 

        outf.flush();
        inf.close();
        outf.close();

        System.out.println("received file");
          dataSinh = "received file";

     } catch(Exception e)
    {
          System.out.println("received error");
          dataSinh = "received error";
          e.printStackTrace();
    }

0 个答案:

没有答案