user4559332
user4559332

Reputation:

read from socket only when data available

I have a server app that while communicating with a client it reads input from the client and sends over to the client. Currently i am using the DataInputStream.read() method for reading the data from the client, however this method is blocking the process. If no data is coming in the process just waits and does not proceed. Here is my code for the class that created upon client connection:

public class Client implements Runnable{
private SSLSocket threadSocket;
private boolean running = true;
private DataOutputStream out;
private int nPort = 0;

//This constructor will be passed the socket
public ClientThread_control(SSLSocket socket, int port){
    threadSocket = socket;
    nPort = port;
}

public void run(){
    System.out.println("New connection at " + new Date() + "\n");
    try {
        DataInputStream in = new DataInputStream (threadSocket.getInputStream());
        out = new DataOutputStream (threadSocket.getOutputStream());
        while (running){
            // read input data
            byte[] one = new byte [1];
            in.read(one);
            int ln = in.available();
// do some stuff
            // parse in going message
            messageParsing(msg);

// do some stuff .... 

            // go to sleep
            Thread.sleep(1000);
        }
    } 
    catch (IOException ex) {ex.printStackTrace();} 
    catch (InterruptedException ex) {ex.printStackTrace();}
    finally {
        try {
            threadSocket.close();
            System.out.println("Connection closed.\n");
        } catch (IOException ex) {ex.printStackTrace();}
    }
}}

When no data is available it does not get past the in.read(one) line. My question is, can i some how now whether there is data or not, and if not then just skip this part and continue to the do some stuff part? If there is no way, that means that the client should always send something in order for the server app continue running smoothly?

Any help would be appreciated, thank you.

Upvotes: 0

Views: 1646

Answers (1)

user207421
user207421

Reputation: 310909

int ln = in.available();

In the circumstance you describe, ln will be zero, which you should test for and handle appropriately.

However this is a poor way to handle blocking I/O. The normal way is to dedicate a thread to reading the socket and handling whatever arrives on it.

If you don't want that, you should be using non-blocking NIO, or asynchronous I/O.

Upvotes: 1

Related Questions