Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MyTCP extends AsyncTask<Void, String, Void> {
- String dstAddress;
- int dstPort;
- String response = "";
- boolean isFirst = true;
- MyTCP(String addr, int port) {
- dstAddress = addr;
- dstPort = port;
- }
- @Override
- protected void onPreExecute(){
- textResponse.setText("Hello bạn!");
- }
- @Override
- protected Void doInBackground(Void... arg0) {
- Socket socket = null;
- try {
- socket = new Socket(dstAddress, dstPort);
- //SystemClock.sleep(5000);
- BufferedReader buff = new BufferedReader(new
- InputStreamReader(socket.getInputStream()));
- String inputLine= buff.readLine();
- while(inputLine != null) {
- //khi gọi hàm này thì onProgressUpdate sẽ thực thi
- publishProgress(inputLine);
- inputLine= buff.readLine();
- }
- } catch (UnknownHostException e) {
- e.printStackTrace();
- response = "UnknownHostException: " + e.toString();
- } catch (IOException e) {
- e.printStackTrace();
- response = "IOException: " + e.toString();
- } finally {
- if (socket != null) {
- try {
- socket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- // SystemClock.sleep(5000);
- //}
- return null;
- }
- // Cập nhật giao diện ở đây
- @Override
- protected void onProgressUpdate(String... values) {
- // TODO Auto-generated method stub
- super.onProgressUpdate(values);
- textResponse.append("\n" + values[0]);
- if(response != "") {
- textResponse.setText(response);
- response ="";
- }
- }
- // Hàm này tự động gọi sau khi thực thi xong hết
- @Override
- protected void onPostExecute(Void result) {
- super.onPostExecute(result);
- isFirst = true;
- //textResponse.append("\n" + response);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement