简体   繁体   English

Android:从套接字读取数据的最佳实践

[英]Android: Best practice to read data from socket

I am trying to get around Sockets in Android.我正在尝试绕过 Android 中的套接字。 Especially I want to know what is best practice to read data from socket and present it to UI.特别是我想知道从套接字读取数据并将其呈现给 UI 的最佳实践是什么。 As per I understand, we cannot have call to read data in the main UI thread as it is a blocking operation.据我了解,我们不能在主 UI 线程中调用读取数据,因为它是一个阻塞操作。

So I got these code snippets reading data from socket.所以我得到了这些从套接字读取数据的代码片段。 (Btw, I've picked up these snippets from voted up SO questions): (顺便说一句,我从投票的 SO 问题中挑选了这些片段):

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:作为 android 开发的新手,我想知道:

  1. What is difference between these two ways of reading?这两种阅读方式有什么区别?

  2. First one was written as AsyncTask while second one was intended to run as separate thread.第一个被编写为AsyncTask而第二个打算作为单独的线程运行。 Which one is correct approach?哪一种是正确的做法?

  3. Is there any better way to read from socket?有没有更好的方法从套接字读取? (eg using non-blocking sockets, callbacks, using any popular third party library etc.) (例如使用非阻塞套接字、回调、使用任何流行的第三方库等)

  1. 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.第二种方法使用 BufferedReader,它有一个内部缓冲机制,可以让你编写更少的代码。

  1. First one was written as AsyncTask while second one was intended to run as separate thread.第一个被编写为 AsyncTask 而第二个打算作为单独的线程运行。 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. AsyncTask是Thread的一个封装,使用AsyncTask可以在后台线程中进行网络操作,并将结果发布到ui线程中。AsyncTask还管理着线程池,在某些情况下,你不需要每次都创建一个新线程。 It is recommended to use AsyncTask in Android.建议在 Android 中使用 AsyncTask。

  1. Is there any better way to read from socket?有没有更好的方法从套接字读取? (eg 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.你可以使用 Square 的okio ,它是一个更好的 java IO 库,并且有Buffer支持。

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

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