繁体   English   中英

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

[英]Best programming way to read streaming data

我正在从TCP流软件读取流数据。 我目前正在使用while循环来连续读取。 但是我不确定这是否是读取流数据的最佳技术。

以下是我当前使用的代码:

  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());
  }

建议plz ???

我目前正在使用while循环来连续读取。

那是读取流数据的最佳技术。 但是,您的循环必须测试流的结尾,这是通过在Java中将read()重新调整为-1来发出的。 您的“ a == b”测试毫无意义。 有几种可能的循环测试:

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

要么

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

其中“ c”是“ int”。

但是我不确定这是否是读取流数据的最佳技术。

为什么不?

该循环与while(true)相同,后者是连续的。 另外,我建议在线程中运行它。

初始化套接字和流后,我建议调用如下方法:

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();
}

我们将其放在线程中,这样循环不会占用客户端的其余代码。 (循环后不进行)

while循环serverInput在参数中初始化serverInput ,因此每次循环时,都会重新初始化serverInput因此不会始终循环发送第一个发送的数据。

当然,您必须将其放在括号中, while循环仅接受布尔参数(真/假)。 因此,在伪代码中,如果InputStream始终返回某些内容,则继续接收新的数据。

暂无
暂无

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

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