试图让 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”
但是我在屏幕上看到的是“覆盖”,这是我从服务器读取数据之前的值。
知道为什么吗?
更新
我正在关闭输出套接字,所以它抛出了异常。现在我没有收到错误,但我得到的值是空的。知道为什么吗?
新代码:
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;
}
}