title: Android. Sockets. Fail Connection
body: <p>I develop simple client-server app for Android by examples:
  <a href="http://android-er.blogspot.com/2014/02/android-sercerclient-example-server.html" rel="nofollow">http://android-er.blogspot.com/2014/02/android-sercerclient-example-server.html</a>
  <a href="http://android-er.blogspot.com/2014/02/android-sercerclient-example-client.html" rel="nofollow">http://android-er.blogspot.com/2014/02/android-sercerclient-example-client.html</a>
  Server code:</p>
  
  <pre><code>package com.example.androidserversocket;
  
  import java.io.IOException;
  import java.io.OutputStream;
  import java.io.PrintStream;
  import java.net.InetAddress;
  import java.net.NetworkInterface;
  import java.net.ServerSocket;
  import java.net.Socket;
  import java.net.SocketException;
  import java.util.Enumeration;
  
  import android.os.Bundle;
  import android.app.Activity;
  import android.widget.TextView;
  
  public class MainActivity extends Activity {
  
      TextView info, infoip, msg;
      String message = "";
      ServerSocket serverSocket;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          info = (TextView) findViewById(R.id.info);
          infoip = (TextView) findViewById(R.id.infoip);
          msg = (TextView) findViewById(R.id.msg);
  
          infoip.setText(getIpAddress());
  
          Thread socketServerThread = new Thread(new SocketServerThread());
          socketServerThread.start();
      }
  
      @Override
      protected void onDestroy() {
          super.onDestroy();
  
          if (serverSocket != null) {
              try {
                  serverSocket.close();
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
      }
  
      private class SocketServerThread extends Thread {
  
          static final int SocketServerPORT = 8080;
          int count = 0;
  
          @Override
          public void run() {
              try {
                  serverSocket = new ServerSocket(SocketServerPORT);
                  MainActivity.this.runOnUiThread(new Runnable() {
  
                      @Override
                      public void run() {
                          info.setText("I'm waiting here: "
                                  + serverSocket.getLocalPort());
                      }
                  });
  
                  while (true) {
                      Socket socket = serverSocket.accept();
                      count++;
                      message += "#" + count + " from " + socket.getInetAddress()
                              + ":" + socket.getPort() + "\n";
  
                      MainActivity.this.runOnUiThread(new Runnable() {
  
                          @Override
                          public void run() {
                              msg.setText(message);
                          }
                      });
  
                      SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
                              socket, count);
                      socketServerReplyThread.run();
  
                  }
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
  
      }
  
      private class SocketServerReplyThread extends Thread {
  
          private Socket hostThreadSocket;
          int cnt;
  
          SocketServerReplyThread(Socket socket, int c) {
              hostThreadSocket = socket;
              cnt = c;
          }
  
          @Override
          public void run() {
              OutputStream outputStream;
              String msgReply = "Hello from Android, you are #" + cnt;
  
              try {
                  outputStream = hostThreadSocket.getOutputStream();
                  PrintStream printStream = new PrintStream(outputStream);
                  printStream.print(msgReply);
                  printStream.close();
  
                  message += "replayed: " + msgReply + "\n";
  
                  MainActivity.this.runOnUiThread(new Runnable() {
  
                      @Override
                      public void run() {
                          msg.setText(message);
                      }
                  });
  
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                  message += "Something wrong! " + e.toString() + "\n";
              }
  
              MainActivity.this.runOnUiThread(new Runnable() {
  
                  @Override
                  public void run() {
                      msg.setText(message);
                  }
              });
          }
  
      }
  
      private String getIpAddress() {
          String ip = "";
          try {
              Enumeration&lt;NetworkInterface&gt; enumNetworkInterfaces = NetworkInterface
                      .getNetworkInterfaces();
              while (enumNetworkInterfaces.hasMoreElements()) {
                  NetworkInterface networkInterface = enumNetworkInterfaces
                          .nextElement();
                  Enumeration&lt;InetAddress&gt; enumInetAddress = networkInterface
                          .getInetAddresses();
                  while (enumInetAddress.hasMoreElements()) {
                      InetAddress inetAddress = enumInetAddress.nextElement();
  
                      if (inetAddress.isSiteLocalAddress()) {
                          ip += "SiteLocalAddress: " 
                                  + inetAddress.getHostAddress() + "\n";
                      }
  
                  }
  
              }
  
          } catch (SocketException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
              ip += "Something Wrong! " + e.toString() + "\n";
          }
  
          return ip;
      }
  }
  </code></pre>
  
  <p>Client code:</p>
  
  <pre><code>package com.example.androidclient;
  
  import java.io.ByteArrayOutputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.net.Socket;
  import java.net.UnknownHostException;
  
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.app.Activity;
  import android.view.View;
  import android.view.View.OnClickListener;
  import android.widget.Button;
  import android.widget.EditText;
  import android.widget.TextView;
  
  public class MainActivity extends Activity {
  
      TextView textResponse;
      EditText editTextAddress, editTextPort; 
      Button buttonConnect, buttonClear;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
  
          editTextAddress = (EditText)findViewById(R.id.address);
          editTextPort = (EditText)findViewById(R.id.port);
          buttonConnect = (Button)findViewById(R.id.connect);
          buttonClear = (Button)findViewById(R.id.clear);
          textResponse = (TextView)findViewById(R.id.response);
  
          buttonConnect.setOnClickListener(buttonConnectOnClickListener);
  
          buttonClear.setOnClickListener(new OnClickListener(){
  
              @Override
              public void onClick(View v) {
                  textResponse.setText("");
              }});
      }
  
      OnClickListener buttonConnectOnClickListener = 
              new OnClickListener(){
  
                  @Override
                  public void onClick(View arg0) {
                      MyClientTask myClientTask = new MyClientTask(
                              editTextAddress.getText().toString(),
                              Integer.parseInt(editTextPort.getText().toString()));
                      myClientTask.execute();
                  }};
  
      public class MyClientTask extends AsyncTask&lt;Void, Void, Void&gt; {
  
          String dstAddress;
          int dstPort;
          String response = "";
  
          MyClientTask(String addr, int port){
              dstAddress = addr;
              dstPort = port;
          }
  
          @Override
          protected Void doInBackground(Void... arg0) {
  
              Socket socket = null;
  
              try {
                  socket = new Socket(dstAddress, 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(Void result) {
              textResponse.setText(response);
              super.onPostExecute(result);
          }
  
      }
  
  }
  </code></pre>
  
  <p>I work with <strong>TWO emulators</strong> Android.
  When server starts it gets IP: <strong>10.0.2.15</strong></p>
  
  <p>And in Client window I set IP: <strong>10.0.2.15</strong> and PORT:<strong>8080</strong>.</p>
  
  <p>But I get exception: <strong>"Failed to connect to /10.0.2.15 (port 8080): connect failed: ECONNREFUSED (Connection refused)"</strong></p>
  
  <p>Why I can not connect?</p>