Advertisement
vietanhlehuu

TCP for Client ANDROID

Oct 29th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. public class MyTCP extends AsyncTask<Void, String, Void> {
  2.  
  3. String dstAddress;
  4. int dstPort;
  5. String response = "";
  6. boolean isFirst = true;
  7.  
  8. MyTCP(String addr, int port) {
  9. dstAddress = addr;
  10. dstPort = port;
  11. }
  12. @Override
  13. protected void onPreExecute(){
  14. textResponse.setText("Hello bạn!");
  15. }
  16. @Override
  17. protected Void doInBackground(Void... arg0) {
  18.  
  19. Socket socket = null;
  20. try {
  21. socket = new Socket(dstAddress, dstPort);
  22.  
  23. //SystemClock.sleep(5000);
  24.  
  25. BufferedReader buff = new BufferedReader(new
  26. InputStreamReader(socket.getInputStream()));
  27. String inputLine= buff.readLine();
  28. while(inputLine != null) {
  29. //khi gọi hàm này thì onProgressUpdate sẽ thực thi
  30. publishProgress(inputLine);
  31. inputLine= buff.readLine();
  32.  
  33. }
  34. } catch (UnknownHostException e) {
  35. e.printStackTrace();
  36. response = "UnknownHostException: " + e.toString();
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. response = "IOException: " + e.toString();
  40. } finally {
  41. if (socket != null) {
  42. try {
  43. socket.close();
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. }
  47. }
  48.  
  49.  
  50. }
  51. // SystemClock.sleep(5000);
  52. //}
  53.  
  54. return null;
  55. }
  56. // Cập nhật giao diện ở đây
  57. @Override
  58. protected void onProgressUpdate(String... values) {
  59. // TODO Auto-generated method stub
  60. super.onProgressUpdate(values);
  61. textResponse.append("\n" + values[0]);
  62. if(response != "") {
  63. textResponse.setText(response);
  64. response ="";
  65. }
  66. }
  67. // Hàm này tự động gọi sau khi thực thi xong hết
  68. @Override
  69. protected void onPostExecute(Void result) {
  70. super.onPostExecute(result);
  71. isFirst = true;
  72. //textResponse.append("\n" + response);
  73. }
  74.  
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement