简体   繁体   English

读取流数据的最佳编程方式

[英]Best programming way to read streaming data

I am reading a streaming data from an TCP streaming software. 我正在从TCP流软件读取流数据。 I'm currently using while loop to read continuously. 我目前正在使用while循环来连续读取。 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??? 建议plz ???

I'm currently using while loop to read continuously. 我目前正在使用while循环来连续读取。

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. 但是,您的循环必须测试流的结尾,这是通过在Java中将read()重新调整为-1来发出的。 Your 'a==b' test is pointless. 您的“ a == b”测试毫无意义。 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'. 其中“ c”是“ 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. 该循环与while(true)相同,后者是连续的。 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. while循环serverInput在参数中初始化serverInput ,因此每次循环时,都会重新初始化serverInput因此不会始终循环发送第一个发送的数据。

You gotta put it in parenthesis, because of course, while loops only accept boolean parameters (true/false). 当然,您必须将其放在括号中, while循环仅接受布尔参数(真/假)。 So, in pseudocode, if the InputStream always returns something, continue with the new recieved data. 因此,在伪代码中,如果InputStream始终返回某些内容,则继续接收新的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM