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?
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.
, Java NIO - . SocketChannel .
, , , , , .
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.
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).
Source: https://habr.com/ru/post/1761184/More articles:How to map a dataset and a typed dataset using Automapper? - .netSQL Server 2000: Field Length in 1/3 (or 2/3) Records - sortingFirebug - Break on Error - d - undefined - jqueryStuck with MySQL and GROUP BY - mysqlWhat is called this user interface element? for iphone - objective-cStrange error for declaring member function - c ++How to open rar file in java 1.4 - javaHow to initialize an array constant with the desired indexes - arraysTools for HTML 5 - javascriptR xy marking color - rAll Articles