我正在开发一个Android应用程序,我必须在服务器上发送位置数据,并以这种方式获取作业数据,所有通信都是构建的,但是当我尝试阅读响应时,我对一件事情感到困惑从服务器没有任何输出,没有任何响应即将到来所以请帮助我摆脱困境。以下是我的代码。提前谢谢。
public static class MyClientTask extends AsyncTask<Void, Void, Void> { String dstAddress; int dstPort; String response = ""; String s; String red; String loc; String msg; Socket socket = null; DataOutputStream dataOutputStream = null; DataInputStream dataInputStream = null; InputStream is=null; BufferedReader br=null; public MyClientTask(String addr, int port,String msg){ dstAddress = addr; dstPort = port; loc=msg; } @Override protected Void doInBackground(Void... arg0) { try { socket = new Socket(dstAddress, dstPort); socket.setKeepAlive(true); dataOutputStream = new DataOutputStream(socket.getOutputStream()); is=socket.getInputStream(); socket.setSoTimeout(60*1000); dataInputStream = new DataInputStream(is); Log.i("socket connect","socket OK"); dataOutputStream.writeUTF(loc); while (dataInputStream == null) { ////this part is not working Log.i("DEV", "sleep "+is.available()); android.os.SystemClock.sleep(100); } br=new BufferedReader(new InputStreamReader(dataInputStream)); String st = null; while(socket.isConnected()){ st = br.readLine(); } Log.w("server response", "says Server = " + st); Dbase db2=new Dbase(mcontext); db2.addresponse(new info(st)); Log.w("second time server response", "says 2ndTime Server = " + st); } catch (UnknownHostException e) { Log.e("at exception", "at thread unknownHost " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { Log.e("io exception", "at thread IO " + e.getMessage()); e.printStackTrace(); } finally{ Log.i("on finally block", "finally"); if (dataOutputStream != null){ try { dataOutputStream.close(); } catch (IOException e) { Log.e("io eception", "at thread dataoutput IO " + e.getMessage()); e.printStackTrace(); } } if (dataInputStream != null){ try { dataInputStream.close(); } catch (IOException e) { Log.e("data input exception", "at thread datainput IO " + e.getMessage()); e.printStackTrace(); } } if (socket != null){ try { Log.i("socket", "socket closed"); socket.close(); } catch (IOException e) { Log.e("socket exception", "at thread finally IO " + e.getMessage()); e.printStackTrace(); } } } return null; } @Override protected void onPreExecute() { super.onPreExecute(); //displayProgressBar("Downloading..."); } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); } }
答案 0 :(得分:0)
您错误地使用InputStream.available方法。此方法不会尝试检索数据。实际上,此方法的大多数实现始终返回0.请参阅Inputstream available reference。 我建议您只删除可用的检查,并根据需要让readLine阻止。 BufferedReader.ready也是如此 - 通常这并不表示您在尝试读取时会获得任何数据,因此此调用也没有用。