URL and socket closing

by michael » Wed, 26 Mar 2008 10:12:15 GMT


Sponsored Links
 Hi,

I have a problem about correctly closing the underlying socket after
opening and reading an input stream from a URL object. The following
code leaves many (i.e. all) sockets open (in the CLOSE_WAIT state, as
netstat reports):

        private void test() {
                for (int i = 0; i < 10000; i++) {
                        try {
                                String urlStr = " http://test-url.com/?q=" ; + i;
                                URL url = new URL(urlStr);
                                InputStream is = url.openStream();
                                byte[] buffer = new byte[1024];
                                int len = is.read(buffer);
                                String content = "";
                                while (len != -1) {
                                        content += new String(buffer, 0, len);
                                        len = is.read(buffer);
                                }
                                is.close();
                        } catch (Exception e) {
                                Log.w(TAG,e);
                        }
                        Log.i(TAG, "i: " + i);
                }
        }

As a consequence, no more sockets can be opened after a while. The
problem does not seem to occur when running the same code in a
"normal" java program (i.e. not in android). Am I missing something
here? Or is this problem due to a bug in android? How could I read
many URLs without running into this problem? (I want to query a web
service with lots of different parameters, that's why I need to open
that many connections.)

By the way: The problem only occurs, if the urlStr changes in each
loop.

Thanks for any hints,

Michael


--~--~---------~--~----~------------~-------~--~----~



Other Threads

1. Minta link froyo untuk yang sudah r00t

Dear all,

As subject, boleh minta link untuk yang udah r00ted?

Sekalian nanya, wipe nya mesti wipe delvic dan wipe ext juga ya? File foto
sama video hilang gak ya? Soalnya belum backup ke pc.

Thanks,
Andreas

-- 
"Indonesian Android Community [id-android]" 

2. Anybody run Chrometophone in Android 2.2 Emulator successfully

I set chrometophone up in emulator
  You need to enable networking
  See "abd forward..."




> 

3. New media framework "Stagefright" sucks... :P

4. setContentView() fails in library project

5. library project returns wrong resource

6. HTC EVO/Incredible multitouch only reporting max of 2 points?

7. clear contact