title: Two way socket communication: socket is closed
body: <p>I am trying to sending and receiving data between two mobile phones. Right now I can send data from one device (device 1) to another (device 2), however, when I am reading data in the same device (device 1) I am getting following error:</p>
  
  <pre><code>java.net.SocketException: Socket is closed
  </code></pre>
  
  <p>I am using the following code to read data:</p>
  
  <pre><code>SocketServerReadThread socketServerReadThread = new SocketServerReadThread(socket);
   socketServerReadThread.run();
  
   private class SocketServerReadThread extends Thread {
  
        private Socket mySocket;
  
        SocketServerReadThread(Socket socket) {
            mySocket = socket;
        }
  
        @Override
        public void run() {
  
  
          try {
              inputStream = mySocket.getInputStream();
              byte[] buffer = new byte[1024];
              byteArrayOutputStream = new ByteArrayOutputStream(1024);
              int bytesRead;
  
              while ((bytesRead = inputStream.read(buffer)) != -1){
                     byteArrayOutputStream.write(buffer, 0, bytesRead);
                     response += byteArrayOutputStream.toString("UTF-8");
                 }
  
              MainActivity.this.runOnUiThread(new Runnable() {
                   @Override
                   public void run() {
                       msgRead.setText(" Response: "+response);
                   }
                  });
  
  
          } catch (IOException e1) {
              // TODO Auto-generated catch block
  
              e1.printStackTrace();
              message += "Read Something wrong! " + e1.toString() + "\n";
          }
        }
  }
  </code></pre>
  
  <p>I would appreciate if anyone could help me to solve the problem.</p>