Adam Hughes Adam Hughes - 25 days ago 7
Java Question

Read and write java socket without blocking

I have a simple Java IO TCP server/client protoype, where the server is writing heavily to the client, and the client writes occasionally to the server. Writing occurs a while loop, particularly in the

run()
method of a
Worker
thread, as is standard:

@Override
public void run() {
while (true) {
// Server writes to client
try {
socket.getOutputStream.write(writeArray);
} catch (Exception e) {
System.exit(1);
}
}


This is in a while loop, so if I also included a read operation, it would block.

@Override
public void run() {
while (true) {
// Server writes to client
try {
socket.getOutputStream.write(writeArray);
} catch (Exception e) {
System.exit(1);
}

// Server reads from client
try {
int read = socket.getInputStream.read();
} catch (Exception e) {
System.exit(1);
}
}


Is there a standard pattern on how to allow for occasional reads without blocking or heavily wasting CPU cycles?

Joe Joe
Answer

Take a look at the available() method: https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html#available--. Then you only need to read "if available".