Java sockets without blocking reading

I am using DataInputStream to read characters / data from a socket.

I want to use .readUnsignedShort (); and try to throw an exception if you don't read 2 bytes. Should I subclass DataInputStream and override methods that add exceptions, or is there an easier way?

+3
source share
4 answers

If you want something fast and dirty, try inputStream.available () .

if (stream.available() < 2) {
    // throw it
}

If you need true non-blocking reads and callbacks when data is available, I think Pablo's answer is better.

+7
source

, Java NIO - . SocketChannel .

, , , , , .

+3
void readButDoNotBlockForALongTime(java.net.Socket socket) {
    int someTimeout = 1000;
    socket.setSoTimeout(someTimeout);
    try {
        // read as much as you want - blocks until timeout elapses
    } catch (java.net.SocketTimeoutException e) {
        // read timed out - you may throw an exception of your choice
    }
}

, .

setSoTimeout (int timeout): / SO_TIMEOUT . -, read() InputStream, Socket, . , java.net.SocketTimeoutException, Socket . , . - > 0. - -.

NIO.

+2
source

If the input ends before two bytes are supplied, it will throw an EOFException. If there is no input (), it will return zero, although it can also return zero if there is an input in some cases (for example, SSL).

0
source

Source: https://habr.com/ru/post/1761184/


All Articles