Sending and receiving files on socket

只谈情不闲聊 提交于 2019-12-28 03:14:09

问题


I am sending files to remote Android client from java server. I write the bytes using outputstream. On reading these bytes read() method keep trying to read bytes after the stream is ended. if I close the outputstream on server-side, read operation work fines. 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 :

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

Thanks in advance


回答1:


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.
  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

Actually I want to reset socket connection

Actually you don't want to do any such thing.




回答2:


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.

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.

Create a thread that reads the InputStream and another one for the OutputStream

Side note:

Don't try to close your outputStream that it cant be reopened again as the documentation is saying:

Closing the returned OutputStream will close the associated socket.

The general contract of close is that it closes the output stream. A closed stream cannot perform output operations and cannot be reopened.



来源:https://stackoverflow.com/questions/24150559/sending-and-receiving-files-on-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!