0

当我连接 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 应该有。我希望这将解决所有用户的大多数问题。

4

1 回答 1

1

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

如果要使连接持久,请移动 try-catch 块内的初始化块:

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()当您想关闭连接时,您不应该忘记手动调用。因此,您还应该将对已创建连接的引用保存在某处,而不仅仅是会话。

于 2019-10-31T18:33:12.727 回答