【发布时间】:2015-07-09 08:02:12
【问题描述】:
我正在从事套接字编程和实现自定义请求响应协议。同样,我在 Java 套接字 API 中使用了 ObjectInputstream 和 ObjectOutputstream。
我坚持的区域是检查数据(在我的情况下是对象)是否可以读取,为此我尝试使用ObjectInputstream.available(),但即使数据在流上可用,它也会返回 0 .
为什么会这样?
所以我想出了解决方案:使用异常并在无限循环中处理它们,所以即使发生异常(读取超时)它也会尝试再次读取。
我怀疑这样做是否是一种好习惯?或者,如果您有任何其他解决方案建议。
while (true){
try {
request = rpcClient.getRequest();
System.out.println(request);
// use threads to handle request for faster response(make use of request IDs)
rpcClient.sendResponse("test response");
} catch (SocketException e)
{// thrown when connection reset
System.out.println("Connection reset : Server is down.....");
break;
} catch (IOException e){
// thrown when read time out
System.out.println("read time out: listening again");
} catch (ClassNotFoundException e){
e.printStackTrace();
}
}
【问题讨论】:
-
我相信这回答了你的问题:stackoverflow.com/questions/26769428/…