2023年11月25日发(作者:)

ExceptionSocketclosed解决

如题,在socket编程中报错

Exception: Socket closed

1、理解错误含义

在数⼩时⽆能狂怒后于StackOverflow寻得箴⾔:

This exception means that you closed the socket, and then continued to try to use it.

你把socket关了,却还想继续⽤,就会报这个错

2、可能的原因

1. 关闭了IO流(最常见)

也就是说,在你发送、接收操作做完之前别关IO流,也许就能解决;

注意,你可能没有关闭IO流,或没有关掉socket

putStream()utStream()

但它可能被其他IO流关闭影响⽽⾃动关闭(见2

后来才知道 socket 只要在 ioclose的情况下 ⾃动关闭,意思就是你想边发送边接受最正确的⽅式就是发送和 接受的操作都做

完之后 再⼀起关闭IO 完美解决。

2. 我没有关基础的IO,为什么还是报了这个错?

常见于在socket中发送了对象的情况,也即使⽤了

ObjectOutputStream

出错原因:使⽤完毕的关闭时,会导致其包装的也⾃动关闭。

ObjectOutputStreamOutputStream

我的出错代码如下

try(OutputStream os = putStream();

InputStream is = utStream())

{

Resource resource = new Resource();

sendResourceObj(resource,os);

("exit".getBytes(_8));

}

} catch (Exception e) {

tackTrace();

}

其中的发送对象的函数如下(本意是为了解耦,把功能尽量模块化):

public static void sendResourceObj(Resource r,OutputStream os){

try(ObjectOutputStream oos = new ObjectOutputStream(os))

{

bject(r);

();

} catch (Exception e) {

tackTrace();

}

}

可以看到,在执⾏结束后,就关闭了;

sendResourceObjObjectOutputStream

修改⽅法:

⼀同,直接放到的声明语句中,待使⽤IO完毕后⼀起关闭即可

ObjectOutputStreamOutputStreamtry-with-resource

try(OutputStream os = putStream();

ObjectOutputStream oos = new ObjectOutputStream(os);

InputStream is = utStream())

{

Resource resource = new Resource();

bject(resource);

();

("exit".getBytes(_8));

}

} catch (Exception e) {

tackTrace();