0
我試圖在兩部手機之間發送和接收數據。現在,我可以從一個設備(設備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";
}
}
}
如果有人可以幫助我解決問題,我將不勝感激。
嗨拉傑,謝謝你的回覆。根據你的建議我改變了我的代碼。但是,我收到了同樣的錯誤。 – MKS
這裏有誤差修改: java.net.SocketException異常:套接字在java.net.PlainSocketImpl.checkNotClosed(PlainSocketImpl.java:134) 在java.net.PlainSocketImpl.getInputStream(PlainSocketImpl.java:216) 在封閉 java.net.Socket.getInputStream(Socket.java:344) at com.example.mytestserver.MainActivity $ SocketServerReadThread.run(MainActivity.java:218) at com.example.mytestserver.MainActivity $ SocketServerThread.run(MainActivity。 java:193) at java.lang.Thread.run(Thread.java:841) – MKS
將代碼更改爲另一方也因爲你不能讀取byteArrayInputStream與BufferedReader – raj