cuong
cuong

Reputation: 11

java socket. How to server know client close stream

I want to write a transfer file socket-program in java . But i have problem, how to cancel when transferring file.

when i close inputstream in client, how to server know it to close outputstream.

here is my code: Client

                   try {
            byte[] data = new byte[1024];
            InputStream is = socket.getInputStream();
            FileOutputStream fos = new FileOutputStream(
                    "/mnt/sdcard/UML.doc");
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            int total = 0;
            while ((count = is.read(data)) != -1 && !canceled) {
                total += count;
                publishProgress("" + (int) ((total * 100) / size));
                fos.write(data, 0, count);

            }

            if(canceled)
            {
                is.close();
                fos.close();
                //socket.close();
                pDialog.dismiss();
                File file = new File("mnt/sdcard/UML.doc");
                file.delete();

                canceled=false;

            }


        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

......

Server

           BufferedInputStream bis = null;

                    bis = new BufferedInputStream(new FileInputStream(
                            myFile));

                    bis.read(mybytearray, 0, mybytearray.length);
                    os = s.getOutputStream();
                    int total = 0;

                    try {

                        os.write(mybytearray, 0, mybytearray.length);

                        // os.flush();
                    }
                    catch(SocketException e){
                        os.flush();
                        tv.setText("aaaaa");
                    }

......

But nothing display when i close inputstream

Upvotes: 1

Views: 839

Answers (2)

Md. Arafat Al Mahmud
Md. Arafat Al Mahmud

Reputation: 3214

You can do this in a try-catch block. pseudocode:

try{
    //your file transferring code here through socket output streams
} catch(SocketException e) {
    /* now as you are in this block you got a socket closed 
      Exception and your server now knows about it */
}

Upvotes: 0

shinkou
shinkou

Reputation: 5154

When the client closes the InputStream in the middle of a transmission, a SocketException will be thrown on the server side.

Upvotes: 1

Related Questions