Closing Android socket

Assume we have a Socket that is connected to a server. Usually, we will use a secondary thread to read from the socket in a blocking connection.

If the user want to terminate the connection, in Java, we can call socket.close(). But not in Android (well, we can, but it will do nothing). While the thread is still alive and waiting, close() will not be executed and the connection will remain active. So, what can be done?

One way is to terminate the thread. This is obviously not a very good way, and denied the thread from executing its final code correctly.

The second and the right one, is simply to call Socket.shutdownInput() method. This will create a disconnection for the waiting thread, the thread will die according to plan and your application will run just fine!

Leave a Reply

You must be logged in to post a comment.


Warning: mysql_query() [function.mysql-query]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /home/content/61/4091161/html/wptalreg/wp-content/plugins/vsf-simple-stats/vsf_simple_stats_shutdown.php on line 17

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/content/61/4091161/html/wptalreg/wp-content/plugins/vsf-simple-stats/vsf_simple_stats_shutdown.php on line 17

Warning: mysql_fetch_row() expects parameter 1 to be resource, boolean given in /home/content/61/4091161/html/wptalreg/wp-content/plugins/vsf-simple-stats/vsf_simple_stats_shutdown.php on line 17

Warning: mysql_query() [function.mysql-query]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /home/content/61/4091161/html/wptalreg/wp-content/plugins/vsf-simple-stats/vsf_simple_stats_shutdown.php on line 45

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/content/61/4091161/html/wptalreg/wp-content/plugins/vsf-simple-stats/vsf_simple_stats_shutdown.php on line 45

Warning: mysql_query() [function.mysql-query]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /home/content/61/4091161/html/wptalreg/wp-content/plugins/vsf-simple-stats/vsf_simple_stats_shutdown.php on line 47

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/content/61/4091161/html/wptalreg/wp-content/plugins/vsf-simple-stats/vsf_simple_stats_shutdown.php on line 47

Warning: mysql_fetch_row() expects parameter 1 to be resource, boolean given in /home/content/61/4091161/html/wptalreg/wp-content/plugins/vsf-simple-stats/vsf_simple_stats_shutdown.php on line 47