How can I read from BufferedReader in Java without blocking?

I want to send a command to the server and find out if I got a response.

I am currently using the BufferedReader readline() function, which blocks until there is a response from the server, but all I want to do is check that there is actually a response from the server.

I tried using ready() or reset() to avoid this block, but that does not help.

This causes my program to get stuck waiting for a server response, which never happens. InputStreamReader seems to do the same, in my understanding of things.

Other questions I found here on this question did not answer my question, so please, if you answer my question, it will be great.

+4
source share
3 answers

Perhaps all you need is an InputStream without its wrapper in BufferedReader

 while (inputStream.available() > 0) { int i = inputStream.read(tmp, 0, 1024); if (i < 0) break; strBuff.append(new String(tmp, 0, i)); } 

Hope this helps.

+1
source

If you want to read answers asynchronously, I suggest starting a thread that reads BufferedReader. It is much simpler in code and easier to manage.

+3
source

I did something similar recently using CountDownLatch. There may be some better ways, but it is quite easy and seems to work quite well. You can customize the wait date of CountDownLatch to suit your needs.

 package com.whatever; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestRead { private static final Logger log = LoggerFactory.getLogger(TestRead.class); private CountDownLatch latch = new CountDownLatch(1); public void read() { URLReader urlReader = new URLReader(); Thread listener = new Thread(urlReader); listener.setDaemon(true); listener.start(); boolean success = false; try { success = latch.await(20000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { log.error("error", e); } log.info("success: {}", success); } class URLReader implements Runnable { public void run() { log.info("run..."); try { URL oracle = new URL("http://www.oracle.com/"); URLConnection yc = oracle.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); latch.countDown(); } catch (Exception ex) { log.error("error", ex); } log.info("consumer is done"); } } public static void main(String[] args) { TestRead testRead = new TestRead(); testRead.read(); } } 
0
source

All Articles