尝试让Android设备从我拥有的服务器获取数据:
RetreiveFeedTask DoStuff=new RetreiveFeedTask();
try{
Work=(DoStuff.execute(Exec)).get();
}
catch(Exception e)
{System.out.print(e+"");}
异步实施:
class RetreiveFeedTask extends AsyncTask<String , Void , String> {
//private Exception e;
String GotBack="empty";
@Override
protected String doInBackground(String... params) {
try{
Socket socket = new Socket("192.168.1.66", 2727);
OutputStream out = socket.getOutputStream();
PrintWriter output = new PrintWriter(out);
BufferedReader input=new BufferedReader(new InputStreamReader(socket.getInputStream()));
output.println(params[0]);
output.flush();
output.close();
GotBack="OverWritten";
GotBack=input.readLine();
socket.close();
}
catch(Exception e){System.out.print(e+"");}
return GotBack;
}
}
我的服务器正在发送ACK: “1 \ n” 个
但是我在屏幕上看到的是“Overwritten”,这是我从服务器读取数据之前的值。
知道为什么吗?
更新
我正在关闭输出套接字,因此抛出异常。现在我没有得到错误,但我得到的价值是空的。知道为什么吗?
新守则:
class RetreiveFeedTask extends AsyncTask<String , Void , String> {
//private Exception e;
String GotBack="empty";
@Override
protected String doInBackground(String... params) {
try{
Socket socket = new Socket("192.168.1.66", 2727);
OutputStream out = socket.getOutputStream();
PrintWriter output = new PrintWriter(out);
BufferedReader input=new BufferedReader(new InputStreamReader(socket.getInputStream()));
output.println(params[0]);
output.flush();
String read="";
while((read=input.readLine())!=null)
{
GotBack+=read;
}
output.close();
socket.close();
}
catch(Exception e){Log.e("MyApp","exception",e);}
return GotBack;
}
}
答案 0 :(得分:1)
是。执行input.readLine();
必须抛出您处理和打印的异常。 GotBack
的值现在为“OverWritten”,在return GotBack;
上返回。