java.net.SocketException: recvfrom failed: EBADF (Bad file descriptor)
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; } } } } }