简体   繁体   English

在套接字上发送和接收文件

[英]Sending and receiving files on socket

I am sending files to remote Android client from java server. 我正在从Java服务器向远程Android客户端发送文件。 I write the bytes using outputstream. 我使用outputstream写入字节。 On reading these bytes read() method keep trying to read bytes after the stream is ended. 在读取这些字节时,read()方法将继续尝试在流结束之后读取字节。 if I close the outputstream on server-side, read operation work fines. 如果我在服务器端关闭outputstream流,则读取操作正常。 But I have to write file on the same socket again so can't close output stream any solution? 但是我必须再次在同一套接字上写入文件,因此无法关闭输出流吗?

NOTE: MY CODE WORKS FINE FOR SHARING SINGLE FILE 注意:我的代码可以很好地共享单个文件

CODE FOR WRITING FILE 写入文件的代码

public static void writefile(String IP, String filepath, int port, OutputStream out) throws IOException {
    ByteFileConversion bfc = new ByteFileConversion();
    byte[] file = bfc.FileToByteConversion(filepath);

    out.write(file, 0, file.length);
    out.close(); // i donot want to close this and how can I tell reading side that stream is ended.
    System.out.println("WRITTEN");
}

Here Am I reading the file on Android : 我在这里在Android上阅读文件:

public Bitmap fileReceived(InputStream is) {

    Bitmap bitmap = null;
    String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    String fileName = "a.png";
    String imageInSD = baseDir + File.separator + fileName;
    //  System.out.println(imageInSD);
    if (is != null) {
        FileOutputStream fos = null;
        OutputStream bos = null;
        try {

            bos = new FileOutputStream(imageInSD);

            byte[] aByte = new byte[1024];
            int bytesRead;
            int index = 0;
            DataInputStream dis = new DataInputStream(is);


            while ((bytesRead = is.read(aByte)) > 0) {
                index = bytesRead + index;
                bos.write(aByte, 0, bytesRead);

                //  index = index+ bytesRead;

                System.out.println("Loop" + aByte + "    byte read are " + bytesRead + "whree  index =" + index);

            }
            bos.flush();
            bos.close();

            Log.i("IMSERVICE", "out of loop");
            java.io.FileInputStream in = new FileInputStream(imageInSD);
            bitmap = BitmapFactory.decodeStream(in);
            bitmap = BitmapFactory.decodeFile(imageInSD);

            Log.i("IMSERVICE", "saved");
            //  if (bitmap != null) 
            //       System.out.println("bitmap is    "+ bitmap.toString());

        } catch (IOException ex) {
            // Do exception handling      
            //      Log.i("IMSERVICE", "exception ");
            System.out.println("ex");
        }
    }

    return bitmap;
}

Actually, I want to reset socket connection 实际上,我想重置socket连接

Thanks in advance 提前致谢

You need to: 你需要:

  1. Send the length of the file ahead of the file. 在文件之前发送文件长度。 You can use DataOutputStream.writeLong() for that, and DataInputStream.readLong() at the receiver. 您可以为此使用DataOutputStream.writeLong() ,并在接收方使用DataInputStream.readLong()
  2. Read exactly that many bytes from the stream at the receiver: 从接收器的流中准确读取那么多字节:

     while (total < length && (count = in.read(buffer, 0, length-total > buffer.length ? buffer.length : (int)(length-total))) > 0) { out.write(buffer, 0, count); total += count; } 

E&OE E&OE

Actually I want to reset socket connection 其实我想重置套接字连接

Actually you don't want to do any such thing. 实际上,您不想执行任何此类操作。

If i donot close outputstream the read operation on other side stuck on keep reading 如果我不关闭输出流,则另一侧的读取操作会停留在继续读取状态

That is because the client socket's InputStream is still waiting for the server to send some packets of data thus blocking your Main Thread. 那是因为客户端套接字的InputStream仍在等待服务器发送一些数据包,从而阻塞了您的主线程。

Solution: 解:

You can put each of your sending( OutputStream ) and reading( InputStream ) of packets of data from the socket to a Thread to prevent blocking your main thread when reading and sending. 您可以将每个发送( OutputStream )和读取( InputStream )数据包从套接字放入线程中,以防止在读取和发送时阻塞主线程。

Create a thread that reads the InputStream and another one for the OutputStream 创建一个读取InputStream的线程,并读取另一个OutputStream的线程

Side note: 边注:

Don't try to close your outputStream that it cant be reopened again as the documentation is saying: 不要试图关闭您的outputStream,因为文档说它不能再次打开:

Closing the returned OutputStream will close the associated socket. 关闭返回的OutputStream将关闭关联的套接字。

The general contract of close is that it closes the output stream. 关闭的总协定是关闭输出流。 A closed stream cannot perform output operations and cannot be reopened. 关闭的流无法执行输出操作,因此无法重新打开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM