gpt4 book ai didi

java - 如何在 Android java 中正确使用 smbj 连接并列出 samba 共享上的文件?

转载 作者:行者123 更新时间:2023-12-02 09:23:17 33 4
gpt4 key购买 nike

当我连接 smbj 时,错误日志显示:

...
I/c.h.s.c.Connection: Successfully authenticated user on 192.168.1.222, session is 4399187361905
I/c.h.s.s.Session: Logging off session 4399187361905 from host 192.168.1.222
I/c.h.s.t.PacketReader: Thread[Packet Reader for 192.168.1.222,5,main] stopped.
I/c.h.s.c.Connection: Closed connection to 192.168.1.222
I/c.h.s.s.Session: Connecting to \\192.168.1.222\pop on session 4399187361905

立即 - 没有任何延迟。因此,连接在打开后立即关闭,如果我尝试列出文件,它们将会崩溃...

Caused by: com.hierynomus.smbj.common.SMBRuntimeException: com.hierynomus.protocol.transport.TransportException: Cannot write SMB2_TREE_CONNECT with message id << 4 >> as transport is disconnected

这似乎很明显,因为没有开放的连接。

一个与 smbj 相关的问题,表明该人使用 try 语句的方式有问题......我相信这是一个类似的情况。

在 AsyncTask 中,我有:

try (Connection connection = client.connect(serverName)) {
AuthenticationContext ac = new AuthenticationContext(username, password.toCharArray(), domain);
Session session = connection.authenticate(ac);
this.session = session;
return session;
} catch (IOException e) {
e.printStackTrace();
}

我确定 try-catch 有问题。有人可以提供一段完整的代码,包括 AsyncTask - 正如 smbj 模块 github 应该有的那样。我希望这能够解决所有用户的大多数问题。

最佳答案

您正在使用 try-with 资源 block 。 try-with-resource block 自动对已在其头部初始化的变量执行 close()(头部为 Connection connection = client.connect(serverName)) 。在您的情况下,当它到达 return 语句时,它会在到达 try block 的末尾时调用 connection.close()

如果您想让连接持久化,请将初始化 block 移至 try-catch block 内:

try {
Connection connection = client.connect(serverName);
this.connection = connection; // save the connection reference to be able to close it later manually
AuthenticationContext ac = new AuthenticationContext(username, password.toCharArray(), domain);
Session session = connection.authenticate(ac);
this.session = session;
return session;
} catch (IOException e) {
e.printStackTrace();
}

当然,当你想关闭连接时,你不应该忘记手动调用connection.close()。因此,您还应该将对创建的连接的引用保存在某处,而不仅仅是 session 。

关于java - 如何在 Android java 中正确使用 smbj 连接并列出 samba 共享上的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58524109/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com