简体   繁体   中英

Best programming way to read streaming data

I am reading a streaming data from an TCP streaming software. I'm currently using while loop to read continuously. But I am not sure that if this is the best technique to read streaming data.

Following is the code i'm currently using:

  Socket client=new Socket("169.254.99.2",1234);
  System.out.println("Client connected ");

//getting the o/p stream of that connection
  PrintStream out=new PrintStream(client.getOutputStream());
  out.print("Hello from client\n");
  out.flush();

//reading the response using input stream
BufferedReader in= new BufferedReader(new InputStreamReader(client.getInputStream()));
  int a = 1;
  int b= 1;

//
  while(a==b){
       // I'm just printing it out.
       System.out.println("Response" + in.read());
  }

Suggestions plz???

I'm currently using while loop to read continuously.

That is the best technique for reading streaming data. However your loop must test for end of stream, which is signalled by read() retuning -1 in Java. Your 'a==b' test is pointless. There are several possible loop tests:

while (true) // with a break when you detect EOS

Or

while ((c = in.read()) != -1)

where 'c' is an 'int'.

But I am not sure that if this is the best technique to read streaming data.

Why not?

That loop would be the same as while(true) , which is continuous. Also, I suggest running this in a thread.

After you init your socket and streams, I suggest calling a method like this:

Thread messageThread;

public void chatWithServer() {
    messageThread = new Thread(new Runnable() {
        public void run() {
            String serverInput;
            while((serverInput = in.readLine()) != null) {
                //do code here
            }
        }
    };

    messageThread.start();
}

We put it in a thread so the loop doesn't hold up the rest of the client's code. (does not progress after loop)

The while loop initilizes serverInput within the parameters, so each time it loops, it re-inits serverInput so it doesn't constantly loop with the very first sent piece of data.

You gotta put it in parenthesis, because of course, while loops only accept boolean parameters (true/false). So, in pseudocode, if the InputStream always returns something, continue with the new recieved data.

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