简体   繁体   English

InputStream 非阻塞读操作

[英]InputStream Non Blocking read operation

I have the scenario where i need to confirm that either the server side socket closed the connection or not.So for this i am checking if(in.read() ==-1) if true,it means that server side closed the connection.我有一个场景,我需要确认服务器端套接字是否关闭了连接。所以为此我正在检查 if(in.read() ==-1) 是否为真,这意味着服务器端关闭了连接. But problem is that if it does not it blocks here as it is blocking call.i need such a solution where i can read non blocking in perticular time or cancel the reading if server end closed the connection.但问题是,如果它没有阻塞,因为它阻塞了调用。我需要这样的解决方案,我可以在特定时间读取非阻塞或在服务器端关闭连接时取消读取。 i am creating like我正在创造

socket = new Socket();
                 // if server is not available 3 seconds blocking call other wise Exception
                 socket.connect(new InetSocketAddress(serverAddress , serverPort),3000);

Any help would be appreciated.任何帮助,将不胜感激。

Regards, Aamir问候, 阿米尔

But problem is that if it does not it blocks here as it is blocking call.但问题是,如果它不在这里阻塞,因为它正在阻塞调用。

That's not the only problem.这不是唯一的问题。 There is a miuch bigger problem: it will throw away a byte of data if any data ever arrives.还有一个更大的问题:如果有任何数据到达,它会丢弃一个字节的数据。 You certainly cannot do that.你当然不能那样做。

What you need is a timed read.你需要的是定时阅读。 See Socket.setSoTimeout() .请参阅Socket.setSoTimeout()

Assuming this is for TCP, have you tried using myClientSocket.isClosed() ?假设这是针对 TCP,您是否尝试过使用myClientSocket.isClosed()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM