Issue
I am trying to get around Sockets in Android. Especially I want to know what is best practice to read data from socket and present it to UI. As per I understand, we cannot have call to read data in the main UI thread as it is a blocking operation.
So I got these code snippets reading data from socket. (Btw, I've picked up these snippets from voted up SO questions):
This...
SocketAddress sockaddr = new InetSocketAddress("192.168.1.1", 80);
nsocket = new Socket();
nsocket.connect(sockaddr, 5000); //10 second connection timeout
if (nsocket.isConnected()) {
nis = nsocket.getInputStream();
nos = nsocket.getOutputStream();
Log.i("AsyncTask", "doInBackground: Socket created, streams assigned");
Log.i("AsyncTask", "doInBackground: Waiting for inital data...");
byte[] buffer = new byte[4096];
int read = nis.read(buffer, 0, 4096); //This is blocking
while(read != -1){
byte[] tempdata = new byte[read];
System.arraycopy(buffer, 0, tempdata, 0, read);
publishProgress(tempdata);
Log.i("AsyncTask", "doInBackground: Got some data");
read = nis.read(buffer, 0, 4096); //This is blocking
}
And this...
clientSocket = new Socket(serverAddr, port);
socketReadStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String line = null;
String stringToSend = "This is from client ...Are you there???";
//Write to server..stringToSend is the request string..
this.writeToServer(stringToSend);
//Now read the response..
while((line = socketReadStream.readLine()) != null){
Log.d("Message", line);
Being newbe to android development I like to know:
What is difference between these two ways of reading?
First one was written as
AsyncTask
while second one was intended to run as separate thread. Which one is correct approach?Is there any better way to read from socket? (e.g. using non-blocking sockets, callbacks, using any popular third party library etc.)
Solution
- What is difference between these two ways of reading?
The second approach used BufferedReader, which has a internal buffer mechanism, which make you write less code.
- First one was written as AsyncTask while second one was intended to run as separate thread. Which one is correct approach?
AsyncTask is a wrapper of Thread, using AsyncTask can do network operation in the background thread and publish result int the ui thread.AsyncTask also manages the Thread pool, in some cases, you need not create a new thread every time. It is recommended to use AsyncTask in Android.
- Is there any better way to read from socket? (e.g. using non-blocking sockets, callbacks, using any popular third party library etc.)
You can use Square's okio, it is a better IO library for java, and has Buffer
support.
Answered By - Juude
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.