java初学网络编程时遇到的Connection reset错误

package tcp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Fileserver直接写3 {//忽略这里的中文 hhh 
	public static void main(String[] args) throws IOException {
		System.out.println("==server==");
		//1指定端口 使用Serversocket创建服务器
		ServerSocket server = new ServerSocket(8888);
		//2阻塞式等待连接 accept
		Socket client = server.accept();
		System.out.println("一个客户端已经建立连接");
		//3输入输出时的操作
		InputStream is =new BufferedInputStream(client.getInputStream()) ;
		OutputStream os =new BufferedOutputStream(new FileOutputStream("02.png"));
		byte[] flush = new byte[1024];
		int len = is.read(flush);
		while(len>=0) {
			os.write(flush,0,len);
			System.out.println(len);
			len = is.read(flush);
		}
		System.out.println("文件传输完成");
		os.flush();
		
	}
}

package tcp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 创建客户端
 * 1建立连接:使用socket创建客户端+服务器地址和端口
 * 2操作:输入输出操作
 * 3释放资源
 * @author Administrator
 *
 */
public class Fileclient直接写3 {
	public static void main(String[] args) throws UnknownHostException, IOException {
		System.out.println("==client==");
		Socket client = new Socket("localhost",8888);
		OutputStream os = new BufferedOutputStream(client.getOutputStream());
		InputStream is = new BufferedInputStream(new FileInputStream("01.png"));
		byte[] con = new byte[1024];
		int len = -1;
		while((len=is.read(con))!=-1) {
			os.write(con,0,len);
		}
		os.flush();
		System.out.println("文件传输完成");
		client.close();//**问题出在此处客户端上传完数据后必须关闭才不会出现报错**
	}
}

附上已找到的connection reset 的报错原因:错误总结(本次错误在第四条)

你可能感兴趣的:(#,java学习中遇到bug)