- 简单demo实现文件下载以及将文件作为邮件附件进行发送
- 涉及的maven版本
- 测试代码
- hutool发送邮箱配置
- 运行结果截图
- 为什么 channel.get 能读取远程文件并写入到 outputStream
- 具体问题描述
- socket的创建
- ChannelSftp中 io属性的创建
- socket的inputStream 怎么同 io的outputStream 关联起来的
- Session 作为线程是谁创建的
测试代码com.jcraft jsch 0.1.55 org.apache.commons commons-io 1.3.2 com.sun.mail javax.mail 1.6.2
public class DownFileDemo {
public static void main(String[] args) {
try {
JSch jsch = new JSch();
Session sshSession = jsch.getSession("root", "ip地址", 22);
sshSession.setPassword("密码");
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect(15000);
ChannelSftp channel = (ChannelSftp) sshSession.openChannel("sftp");
channel.connect(15000);
File file = new File("download.pdf");
OutputStream outputStream = new FileOutputStream(file);
channel.get("/test/pdf/register.pdf", outputStream);
MailUtil.send("xxx@163.com", "测试数据","测试jsch ",false,file);
outputStream.close();
channel.disconnect();
sshSession.disconnect();
}
catch (Exception e){
System.out.println(e);
}
}
}
hutool发送邮箱配置
# 邮件服务器的SMTP地址,可选,默认为smtp.<发件人邮箱后缀> # host = smtp.yeah.net # 邮件服务器的SMTP端口,可选,默认25 qq必须 465端口 port = 465 # 发件人(必须正确,否则发送失败) from = xxx@qq.com # 用户名,默认为发件人邮箱前缀 # user = yichen # 密码(注意,某些邮箱需要为SMTP服务单独设置授权码,详情查看相关帮助) pass = aslkhexevrmibfcg # 使用SSL安全连接 ==> qq必须开启 sslEnable = true运行结果截图
socket的创建我之前一直很好奇,channel 为什么能读取到我远程服务器上的文件流,然后写入outputStream中。
代码 channel.get("/test/pdf/register.pdf", outputStream); 跟踪进去就直接从 io_in 里面读取数据流了,问题是这个流是哪里写入的。理论上来说肯定是从 io.outputStream 写入的,但是我找了好久都没找到。然后这个outputStream 里的数据又是从哪里来的呢?理论上来说肯定源于远程服务器上的文件,那是怎么获取的呢,看代码是通过socket获取的。所以socket和io.outputStream肯定有关系,但是我没找到。。
Session#connect方法,
1、入口 ChannelSftp channel = (ChannelSftp) sshSession.openChannel("sftp");
2、创建实例 Channel channel=Channel.getChannel(type); Session-864行
3、io创建, ChannelSftp 的父类(ChannelSession)构造函数 io=new IO();
Session#run() 方法实现,第1386行
1、从socket中读取数据流,1403行
2、写入io.outputStram中,1459行
sshSession.connect(15000); 这个方法执行时创建的 第530行



