Android - 套接字关闭速度不够快

Android - Socket does not close fast enough

我有一个客户端应用程序和一个服务器应用程序。客户端应用程序通过 java.net.Socket(协议 = TCP)向服务器应用程序发送数据包。在 Socket.Close() 上,我的服务器应用程序立即向我显示连接已关闭 - 这就是它必须正常工作的方式。注意:整个 tcp-streaming 逻辑在辅助 activity 中,这就是为什么我使用 onBackPressed() 函数来完成整个 tcp-streaming 并切换到主要 activity.

工作场景:

@Override
public void onBackPressed(){
      m_socket.Close();
      finish();
}

如前所述,套接字关闭,服务器立即通知连接已关闭。

不工作的场景,因为 Socket.close() 似乎太慢了:

@Override
public void onBackPressed(){
      m_socket.Close();
      m_wifiManager.disconnect();
      finish();
}

这种情况只在 20% 的情况下能正常工作。在另外 80% 中,我的服务器应用程序通知连接已关闭 大延迟 。在我看来,这是因为 tcp-socket 需要关闭的时间 - 所以进程被 wifi-connection 断开中断,并且无法正确关闭 socket (#).作为我的观点的证明:如果我逐步调试,这个场景在 100% 的情况下都有效。服务器立即通知。

我已经尝试过的以及仍然无法正常工作的:

所以我的问题是:

  1. 我的意见(#)正确吗? socket-closing 来不及吗?

  2. 我该如何解决这个问题?这样 tcp-socket-closing 正确完成,就像在第一个场景中一样,然后 wifi 断开连接?

问题可能与 SO_LINGER 套接字选项有关:

Specify a linger-on-close timeout. This option disables/enables immediate return from a close() of a TCP Socket. Enabling this option with a non-zero Integer timeout means that a close() will block pending the transmission and acknowledgement of all data written to the peer, at which point the socket is closed gracefully. Upon reaching the linger timeout, the socket is closed forcefully, with a TCP RST. Enabling the option with a timeout of zero does a forceful close immediately. If the specified timeout value exceeds 65,535 it will be reduced to 65,535.

默认情况下它是禁用的,您 close 立即调用 returns 并在套接字实际关闭之前断开 wifi。您需要致电 setSoLinger 进行修复:

m_socket.setSoLinger(true, 1);