Socket 的输入输出流只在服务器和客户端之间运输,所以需要额外的字节流读取文件内容然后Socket流写入,保存时,服务器端的Socket流读取的时候额外的字节流写出到文件

客户端: 上传文件

public class tcp2 {

public static void main(String[]args) throws IOException
{
	System.out.println("客户端启动中");
	
	Socket client =new Socket("localhost",8888);
	
	//文件的拷贝
	InputStream is=new BufferedInputStream(new FileInputStream("src\\linux学习路线.png"));
	OutputStream os=new BufferedOutputStream(client.getOutputStream());
	
	byte[] data=new byte[1024*60];
	int len=-1;
	while((len=is.read(data))!=-1)
	{
		os.write(data,0,len);
	}
	os.flush();
	os.close();
	
	
	client.close();
	
}
}

服务器端:存储文件

public class tcp {

public static void main(String[]args) throws IOException
{
	System.out.println("服务器启动中...");
	ServerSocket server=new ServerSocket(8888);
	
	Socket client=server.accept();
	
	//文件的拷贝
	InputStream is=new BufferedInputStream(client.getInputStream());
	OutputStream os=new BufferedOutputStream(new FileOutputStream("D:/d/tu.jpg"));
	
	byte[] flush=new byte[1024*60];
	int len=-1;
	
	while((len=is.read(flush))!=-1)
	{
		os.write(flush,0,len);
	}
	
	
	is.close();
	os.close();
	
	client.close();
	
}
}