ITeye博客

socket write error

chokee · 2011-10-12 10:36 · J2EE · 编程语言 · Markdown

Software caused connection abort: socket write error解决方法!

package ok;

import java.net.; import java.io.;

public class Application1 { public static void main(String args) { try { ServerSocket server = new ServerSocket(1991); Socket soc = server.accept(); BufferedOutputStream output = new BufferedOutputStream(soc. getOutputStream()); BufferedInputStream input = new BufferedInputStream(new FileInputStream(new File( "C:\Documents and Settings\Administrator\My Documents\1.bmp ")));

byte zijie=new byte;

while(input.read(zijie)> 0) { output.write(zijie); output.flush(); }

input.close(); output.close(); //把这个去掉就没错了

soc.close(); server.close();

} catch (Exception ex) {

System.out.println( "有错误发生了! " + ex.getMessage()); }

} }

上面是我写的传图片的代码。 在运行的时候会报 Software caused connection abort: socket write error 这个错误? 可是如果把output.close();去掉后就不会有错了 事实上在我写的所有有关socket的代码中 只要把输出流一关 就会出错! 谁告诉我一下为什么?

------解决方法-------------------------------------------------------- 我的客户端代码是: /** * */ package ok;

import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.net.UnknownHostException;

/**

  • @author arkwrightzhn

*/ public class Application2 {

/**

  • @param args */ public static void main(String args) { Socket socket=null;   

InputStream is=null; FileOutputStream fos=null; try { socket=new Socket( "localhost ",1991); is=socket.getInputStream(); fos=new FileOutputStream( "C:\Documents and Settings\Administrator\My Documents\2.bmp "); byte bs=new byte; int len=0; //int i=0; while((len=is.read(bs))> 0){ //i++; //System.out.println(i); fos.write(bs,0,len); fos.flush(); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(fos!=null) fos.close(); if(is!=null) is.close(); if(socket!=null) socket.close(); } catch (IOException e) { e.printStackTrace(); } }

}

}

============================= 为此,我找遍了中英文的一些网站,搜遍了能找的每个角落,发现了出现这种状况的原理,该java异常在客户端和服务器端都有可能发生,引起该异常的原因有两个:

1,如果一端的Socket被关闭(或主动关闭,或因为异常退出而 引起的关闭),另一端仍发送数据,发送的第一个数据包引发该异常(Connect reset by peer)。

2,一端退出,但退出时并未关闭该连接,另一端如果在从连接中读数据则抛出该异常(Connection reset)。简单的说就是在连接断开后的读和写操作引起的。

评论(1)

  1. #1 楼 · zhouqinghao · 2012-05-31 16:39

    到目前为止,有解决方案吗?

评论功能维护中,当前仅展示历史评论。