1

転送ファイルsocket-programをjavaで書きたい。しかし、私は問題があります、ファイルを転送するときにキャンセルする方法。

クライアントでinputstreamを閉じるとき、出力ストリームを閉じることをサーバーが認識する方法。

これが私のコードです:クライアント

                   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());
        }

.....。

サーバ

           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");
                    }

.....。

しかし、入力ストリームを閉じると何も表示されません

4

2 に答える 2

1

InputStreamクライアントが送信中に を閉じるとSocketException、サーバー側で がスローされます。

于 2012-07-10T05:12:33.500 に答える
0

これは、try-catch ブロックで行うことができます。疑似コード:

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 */
}
于 2012-07-10T05:15:24.620 に答える