1

我想用 java 写一个传输文件 socket-program 。但是我有问题,传输文件时如何取消。

当我在客户端关闭输入流时,服务器如何知道它关闭输出流。

这是我的代码:客户端

                   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在传输过程中关闭 a 时,SocketException将在服务器端抛出 a。

于 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 回答