简体   繁体   中英

Check for incoming data in Java Socket

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 ...

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");  
} 

You can use the InputStream.available() method to check how many bytes have currently arrived on the socket's 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 "";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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