1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| public class MyClientTask extends AsyncTask<Void, Void, String> {
private String json_url;
private ReturnValue returnValueImpl;
private int dstPort;
String response = "";
MyClientTask(String addr, int port){
this.json_url = addr;
this.dstPort = port;
}
@Override
protected String doInBackground(Void... params) {
Socket socket = null;
try {
socket = new Socket(json_url, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(String result)//Donne le résultat
{
returnValueImpl.renvoyerValeurString(result);
}
public void setReturnListener(ReturnValue returnListener) {
returnValueImpl = returnListener;
}
public interface ReturnValue {
abstract void renvoyerValeurString(String valeurARenvoyer);
}
} |
Partager