我想在java中编写一个传输文件socket-program。 但我有问题,如何在传输文件时取消。
当我在客户端关闭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");
}
...
但是当我关闭输入流
时没有显示答案 0 :(得分:1)
当客户端在传输过程中关闭InputStream
时,服务器端会抛出SocketException
。
答案 1 :(得分: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 */
}