Java while循环中的ObjectInputStream readObject

Java while循环中的ObjectInputStream readObject,java,compiler-errors,objectinputstream,Java,Compiler Errors,Objectinputstream,是否可以读取while循环中的ObjectInputStream,该循环将通过套接字超时引发的异常终止socket.setSoTimeout(4000) while(Object obj = ois.readObject()) { <-- Not Working //do something with object } while(objectobj=ois.readObject()){ 请注意,注释中建议测试readObject()返回值的null是不正确的。如果您编写了nu

是否可以读取while循环中的
ObjectInputStream
,该循环将通过套接字超时引发的异常终止
socket.setSoTimeout(4000)

while(Object obj = ois.readObject()) {  <-- Not Working
//do something with object    
}
while(objectobj=ois.readObject()){

请注意,注释中建议测试
readObject()
返回值的
null
是不正确的。如果您编写了
null

,它将只返回
null
,这是不起作用的,因为语句是在while()中编写的,而不是布尔表达式,因此我们可以这样编写:

Object obj = null;
while ((obj = ois.readObject()) != null) {
//do something with object  
}

@YassinHajaj你不认为如果socket是活动的,readObject会永远等待吗?我真的不知道。它应该被测试…好的readObject正在阻塞你能循环进去吗。readObject();然后它会多次读取同一个对象吗?@Lealo不,当然它不会多次返回同一个对象。这是什么读取方法?
try
{
    for (;;)
    {
        Object object = in.readObject();
        // ...
    }
}
catch (SocketTimeoutException exc)
{
    // you got the timeout
}
catch (EOFException exc)
{
    // end of stream
}
catch (IOException exc)
{
    // some other I/O error: print it, log it, etc.
    exc.printStackTrace(); // for example
}
Object obj = null;
while ((obj = ois.readObject()) != null) {
//do something with object  
}