简体   繁体   English

如何通过活动的插座连接正确关闭主动性?

[英]How to correctly close acitivity with active socket connection?

I have an android app with always active socket connections. 我有一个始终具有活动套接字连接的android应用。 If connection lost, the app immideately reconnect to the server. 如果连接断开,该应用将立即重新连接到服务器。 Socket running in seperate thread. 套接字在单独的线程中运行。

I can correctly close socket in different situations. 我可以在不同情况下正确关闭套接字。 For example, when screen off or back button pressed. 例如,当屏幕关闭或按下后退按钮时。

I tried to override onPause, onResume, onDestroy with this: 我试图用以下方法覆盖onPause,onResume,onDestroy:

I can correctly close socket in different situations. 我可以在不同情况下正确关闭套接字。 For example, when screen off or back button pressed. 例如,当屏幕关闭或按下后退按钮时。

I tried to override onPause, onResume, onDestroy. 我试图覆盖onPause,onResume,onDestroy。 I have tried all three of these approaches, 我已经尝试了所有这三种方法,

Closing the socket explicitly: 显式关闭套接字:

socket.close();

Just nulling it out: 只是使它无效:

socket = null;

And I have also tried the shutdownInput method: 我还尝试了shutdownInput方法:

socket.shutdownInput();

but server continue thinking that socket is alive. 但是服务器继续认为套接字仍然有效。

PS: by the way, when I recompile and run again android app the connection drops well. PS:顺便说一句,当我重新编译并再次运行android应用程序时,连接断开良好。

You should make the server to close the socket too. 您也应该使服务器也关闭套接字。 If you don't do that the server will belive the client server is still open until a write / read attempt is tried by the server. 如果不这样做,服务器将不可用,则客户端服务器仍处于打开状态,直到服务器尝试进行写/读尝试为止。

I suggest to check the client-server protocol: you should read some "command" from the server that could be interpreted as a close request; 我建议检查客户端-服务器协议:您应该从服务器读取一些“命令”,该命令可以解释为关闭请求。 then the server could close the socket too. 那么服务器也可以关闭套接字。 Something like this on server side should help you 在服务器端这样的事情应该可以帮助您

1 - server creates listening socket 1-服务器创建监听套接字

2 - server accept() 2-服务器accept()

3 - The following: 3-以下内容:

while( readClientCommand() !=CLOSE_COMMAND)

   // process command

4 - socket.close(); 4- socket.close();

What you're describing appears to be a common issue when dealing with sockets; 在处理套接字时,您所描述的似乎是一个常见 问题 namely, even though you may have correctly closed the socket on the client side (ie in your Android app), your server is not aware of this, and that is probably why it still thinks the socket is alive. 也就是说,即使您可能已经正确关闭了客户端的套接字(即在您的Android应用程序中),您的服务器也没有意识到这一点,这可能就是为什么它仍然认为套接字仍在运行的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM