尝试让 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;
}
}
最佳答案
是的。执行 input.readLine();
必须引发您处理并打印的异常。 GotBack
的值现在为“OverWritten”,该值在 return GotBack;
上返回。
关于java - Android 客户端实现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15733716/