双向插座通信:插座关闭

时间:2014-03-19 04:35:25

标签: android sockets

我正在尝试在两部手机之间发送和接收数据。现在我可以将数据从一个设备(设备1)发送到另一个设备(设备2),但是,当我在同一设备(设备1)中读取数据时,我收到以下错误:

java.net.SocketException: Socket is closed

我使用以下代码读取数据:

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";
        }
      }
}

如果有人能帮我解决问题,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

 private class SocketServerReadThread extends Thread {
 private Socket mySocket;

  SocketServerReadThread(Socket socket) {
      this.mySocket = socket;
  }

  BufferedReader input;
  input = new BufferedReader(new InputStreamReader(
                    this.mySocket.getInputStream()));


  @Override
  public void run() {
 while (!Thread.currentThread().isInterrupted()) {

            try {

                String read = input.readLine();
                System.out.printf("Message read is -> %s%n", read);
                if (read != null) {

msgRead.setText(" Response: "+response);   
}
}catch(Exception e){}}}}