1. 問題說明:
與服務器之間進行socket通信的時候,客戶端關閉socket之后,會拋出一個IOException,異常信息如下:
java.net.SocketException: recvfrom failed: EBADF (Bad file descriptor)
2. 問題分析:
根據異常分析,定位到這是關閉socket之后持續進行讀操作導致
private InputStream is;
private OutputStream out;
private Socket socket;
private int type;
// socket連接
private class CommandReceiver extends Thread {
@Override
public void run() {
try {
byte[] data;
if (socket != null && socket.isConnected() && !socket.isClosed()) {
is = socket.getInputStream();
while (true) {
//讀取數據
byte[] responseData = readOneFrame(is);
//......解析數據
//......解析數據
switch(type) {
case 1:
//業務處理
break;
case 2:
is.close();
os.close();
socket.close();
default:
break;
}
}
}
}
}
查看代碼得知,這里關閉socket之后,while循環並沒有結束,仍然還在進行讀操作。
3.問題解決
因此需要在socket關閉之后,同時關閉掉while循環,此處將while循環這里增加一個判斷的booean值即可。
private InputStream is;
private OutputStream out;
private Socket socket;
private int type;
private boolean hasRead = false;
// socket連接
private hasRead = true;
private class CommandReceiver extends Thread {
@Override
public void run() {
try {
byte[] data;
if (socket != null && socket.isConnected() && !socket.isClosed()) {
is = socket.getInputStream();
while (hasRead) {
//讀取數據
byte[] responseData = readOneFrame(is);
//......解析數據
//......解析數據
switch(type) {
case 1:
//業務處理
break;
case 2:
is.close();
os.close();
socket.close();
hasRead=false;
default:
break;
}
}
}
}
}
