Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for incoming data in Java Socket

Tags:

java

sockets

I'm writing a simple chat in Java, and I want to check if there is some data waiting on BufferedReader. I've read about NIO, but I didn't completely understand it. Here is some of 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 don't know what to fill into dataIncomming ...

like image 231
noisy cat Avatar asked Jan 13 '12 19:01

noisy cat


1 Answers

Use the Stream.Available() method. You might also want to wait until the right amount of bytes is received and wait so the Thread is not running 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");  
} 
like image 56
Brad Semrad Avatar answered Oct 27 '22 04:10

Brad Semrad