我需要通过网络有条件地发送一些数据。我遇到了一个奇怪的问题,即在发送整个数据之前,我的连接似乎已经关闭了。
服务器
String id = String.valueOf(dis.readLong());
String path = createPathToFile(id);
File image = getFile(path);
if (image == null) {
log.debug("No image for id {}", id);
dos.writeBoolean(false);
dos.flush();
return;
} else {
log.debug("Streaming #{}", image.getName());
如您所见,我想在关闭连接之前向客户端发送逻辑false
(套接字在finally
块中关闭
但是在客户端我有以下错误
19:40:29.914 [pool-1-thread-1] ERROR [l.choina.imagetransfer.client.Client] - Fatal:
java.io.EOFException: null
at java.io.DataInputStream.readBoolean(DataInputStream.java:244) ~[na:1.7.0_55]
at pl.choina.imagetransfer.client.Client$WorkerTask.run(Client.java:98) ~[image-transfer.jar:na]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [na:1.7.0_55]
at java.util.concurrent.FutureTask.run(FutureTask.java:262) [na:1.7.0_55]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_55]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_55]
at java.lang.Thread.run(Thread.java:745) [na:1.7.0_55]
看起来套接字在布尔值到达客户端sie之前就已关闭。
客户端
try (
Socket s = new Socket(params.getHost(), params.getPort());
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
) {
//connect to remote host
dos.writeLong(id);
dos.flush();
boolean result = dis.readBoolean(); // line 98 - throwing exception
if (result == false) {
log.info("Image #{} not available", id);
为什么会这样?我是否必须在服务器端关闭套接字,并且当我在客户端关闭套接字时是否会自动关闭?如果我离开它,一切正常,但是资源泄漏比什么呢?