public class MyClientTask extends AsyncTask<Void, Void, Void> { String dstAddress; int dstPort; String response = ""; MyClientTask(String addr, int port) { dstAddress = addr; dstPort = port; } PrintWriter out ; @Override protected Void doInBackground(Void... arg0) { Socket socket = null; try { socket = new Socket(dstAddress, dstPort); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); out.println("VB"); out.flush(); 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(Void result) { text.setText(response); super.onPostExecute(result); } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)