先说结论
问题: 明明执行的语句在socket.close
前, 却出现Exception in thread "main" java.net.SocketException: Socket is closed报错
结论: 在Java中关闭一个包装流会导致它的底层流也被关闭所以一般使用socket.shutdownOutput()
或socket.shutdownInput()
关闭对应的流
问题复现
最近在学习Socket, 做了一个"Client发送文件名, Server回复文件"的Demo, 并编写了一个将InpuStream转为String的工具类, 代码如下:
public static String streamToString(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
reader.close(); /* 罪魁祸首 */
return stringBuilder.toString();
}
在执行Server时, 收到Client传来的文件名(使用上面提到的工具类获取)后, 再次调用socket.getOutputStream()
出现了Socket is closed异常;
经过排查发现是在工具类中直接将BufferedReader关闭了, 由于BufferedReader是一个包装流, 导致关闭它时它的底层流也会被关闭, 就出现了Socket is closed异常.
- Socket quot SocketException Exception closedsocket quot socketexception exception 57757 quot socketexception端口 quot socketexception interrupted debugger 调试器quot socketexception端口 quot exception rabbitmq reason outofmemoryerror quot exception thread messagingexception quot exception connect bindingexception quot exception statement version unsupportedclassversionerror quot exception unsatisfiedlinkerror quot exception thread