【发布时间】:2016-02-23 07:28:05
【问题描述】:
我正在尝试绕过 Android 中的套接字。特别是我想知道从套接字读取数据并将其呈现给 UI 的最佳做法是什么。 据我了解,我们不能调用在主 UI 线程中读取数据,因为它是一个阻塞操作。
所以我得到了这些代码 sn-ps 从套接字读取数据。 (顺便说一句,我从投票的 SO 问题中选择了这些 sn-ps):
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
}
还有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);
作为 android 开发的新手,我想知道:
这两种阅读方式有什么区别?
第一个写成
AsyncTask,而第二个打算作为单独的线程运行。哪种方法是正确的?有没有更好的从套接字读取的方法? (例如,使用非阻塞套接字、回调、使用任何流行的第三方库等)
【问题讨论】:
标签: android sockets android-asynctask android-networking