简体   繁体   中英

Sending and receiving files on socket

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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