Check input in Java Socket

I am writing a simple chat in Java and I want to check if there is any data waiting on BufferedReader. I read about NIO, but I did not quite understand this. Here is my code:

public void Send(String data)
{
    out.println(data);
}

public String Recv()
{
    if (dataIncomming)
    {
        try {
            return in.readLine();
        } catch (IOException e) {
            System.err.println("Send: Error on BufferedReader.readLine() - IOException");
        }
    }
    else return "";
}

I do not know what to fill in dataIncomming...

+7
source share
2 answers

Use the Stream.Available () method . You can also wait until the correct number of bytes is received, and wait for the thread to not run for 100% of the time.

while(Stream.Available() != 0); //block until there is data

try{  
    return in.readLine();  
} catch (IOException e) {  
    System.err.println("Send: Error on BufferedReader.readLine() - IOException");  
} 
+8
source

You can use the InputStream.available () method to check how many bytes are currently in the socket input stream.

public String Recv()
{
    if (in.available() > 0)
    {
        try {
            return in.readLine();
        } catch (IOException e) {
            System.err.println("Send: Error on BufferedReader.readLine() - IOException");
        }
    }
    else return "";
}
0
source

All Articles