我想用java编写一个传输文件套接字程序。但我有问题,如何在传输文件时取消。
当我在客户端关闭inputstream时,如何让服务器知道关闭outputstream。
这是我的代码:客户端
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");
}
但当我关闭输入流时没有显示任何内容
当客户端在传输过程中关闭InputStream
时,服务器端将抛出SocketException
。
您可以在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 */
}