-2

I'm new at socket programming and I've read several tutorials to have an idea on when to start. But I still have little knowledge about Android UI Thread and socket programming.

When using HTTP request, you should do the operation in a different thread to prevent the UI from blocking and getting an ANR. So my question is what about a socket connection? does it works the same as an HTTP request where the code execution stops until the device gets a response, therefore, I have to do the operations in a background thread to prevent ANR?

Christopher Francisco
  • 14,798
  • 28
  • 86
  • 202
  • 1
    Using HTTP request is basically the same as a socket connection. A HTTP request sets up a TCP connection, and then sends some text that is understandable by a program that knows the protocol HTTP. Thus, sending and receiving packets plus processing packet data will be blocking your app while working. The same works for a socket connection. Therefore you should always do your connections in a separate thread. EDIT: I cannot think of any application (android or not) that shouldn't use threads when handling network traffic, so one can consider it at least good practice to always use threads. – Pphoenix Jun 02 '14 at 12:29

3 Answers3

1

Yes, socket connection and read operations are blocking.

Asaf
  • 597
  • 2
  • 5
  • 17
0

HTTP requests use TCP as an underlying protocol, so it is similar to using sockets. In Android if you put any network code on the main thread you will get this exception NetworkOnMainThreadException.

This is an example on how to safely make an HTTP request in Android:

Thread  httpThread = new Thread(new Runnable() {

                                @Override
                                public void run() {

                                    try {

                                        HttpParams httpParameters = new BasicHttpParams();
                                        // Set the timeout in milliseconds until a connection is established.
                                        // The default value is zero, that means the timeout is not used. 
                                        int timeoutConnection = 5000;
                                        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                                        // Set the default socket timeout (SO_TIMEOUT) 
                                        // in milliseconds which is the timeout for waiting for data.
                                        int timeoutSocket = 7000;
                                        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

                                        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
                                        HttpResponse httpResponse = null;

                                        HttpPost httpPost = new HttpPost(url);

                                        httpResponse = httpClient.execute(httpPost);

                                        StatusLine statusLine = httpResponse.getStatusLine();
                                        int statusCode = statusLine.getStatusCode();

                                        System.out.println(statusCode);
                                        if (statusCode == 200) {
                                            //success
                                        }else{
                                            //fail
                                        }

                                    } catch (Exception exception) {

                                        Log.e("", exception.toString());

                                    }
                                }
                            });
                            httpThread.start();
Tareq
  • 719
  • 1
  • 10
  • 22
0

For HTTP, you can use asynchronous HTTP libraries that work with Listeners in mind: http://loopj.com/android-async-http/

For Sockets, you can use AsyncTask to do things in background: Using AsyncTask for android network connection

You cannot do network connection on the main thread, it throws an Exception, because it freezes the application if it times out.

Community
  • 1
  • 1
EpicPandaForce
  • 75,743
  • 26
  • 240
  • 404