簡體   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