java.io.EOFException when try to read from a socket

自闭症网瘾萝莉.ら 提交于 2019-12-05 17:42:40

DataInputStream.readByte API does not say it return -1 on EOS, it says

Returns:the next byte of this input stream as a signed 8-bit byte.

Throws: EOFException - if this input stream has reached the end.

It assumes that when working withh DataInputStream.readByte we know how many bytes are left in the stream. Otherwise we can use EOFException as an indicator of EOS.

BTW If you use read() you will get -1 on EOS without EOFException

From the DataInputStream Javadoc:

A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way.

I'm not sure whether you need that, but you can decide for yourself. In general, if you're just downloading data and writing to a file, you won't need it - just stick with the BufferedInputStream.

The readByte() method reads one byte (hence the name) and it will throw an EOFException when the stream reaches the end before reading all the bytes. It might sound a bit confusing, but the exception is thrown reading input, not writing the file. It is, in fact, the only way to determine whether the DataInputStream has ended.

But once again, consider using just the BufferedInputStream, as it is probably all you need.

You have already read the byte then why are you again reading it in the while? Plus your check at while is not correct, you wont get -1 for DIS.readByte. Try using read().

It depends when you use client - server implementation and client is "always up" and socket is keeping whole time.

if socket connection is up and you use for example ObjectInputStream so "EOFException" will appear when client close socket (socket.close) or "java.net.SocketException: Connection" reset will apper when socket.close() isnt check at finally for sure...

But if you keep client and socket connection up ObjectInputStream.readObject() will stay and listen what is what you want in this scenario. and yes when you call only read() you will get -1 and if client is killed and you are handling for one client one thread at server you will only get -1 and thread will live foreever (if you dont kill it manualy or kill whole server)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!