[英]java socket. How to server know client close stream
I want to write a transfer file socket-program in java . 我想用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 但是当我关闭输入流时什么也没显示
当客户端在传输过程中关闭InputStream
时,将在服务器端引发SocketException
。
You can do this in a try-catch block. 您可以在try-catch块中执行此操作。 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 */
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.