簡體   English   中英

從Java套接字讀取數據

[英]Read Data from a Java Socket

我有一個Socket在某個x端口上偵聽。

我可以從我的客戶端應用程序將數據發送到套接字但無法從服務器套接字獲得任何響應。

  BufferedReader bis = new BufferedReader(new 
  InputStreamReader(clientSocket.getInputStream()));
  String inputLine;
  while ((inputLine = bis.readLine()) != null)
  {
      instr.append(inputLine);    
  }

..此代碼部分從服務器讀取數據。

但除非服務器上的Socket關閉,否則我無法從服務器讀取任何內容。 服務器代碼不受我的控制,無法對其進行編輯。

如何從客戶端代碼中克服此問題。

謝謝

看起來服務器可能沒有發送換行符(這是readLine()正在尋找的)。 嘗試一些不依賴於此的東西。 這是一個使用緩沖區方法的示例:

    Socket clientSocket = new Socket("www.google.com", 80);
    InputStream is = clientSocket.getInputStream();
    PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());
    pw.println("GET / HTTP/1.0");
    pw.println();
    pw.flush();
    byte[] buffer = new byte[1024];
    int read;
    while((read = is.read(buffer)) != -1) {
        String output = new String(buffer, 0, read);
        System.out.print(output);
        System.out.flush();
    };
    clientSocket.close();

要在客戶端和服務器之間進行通信,需要很好地定義協議。

客戶端代碼阻塞,直到從服務器接收到一行,或者套接字關閉。 你說只有在套接字關閉后你才收到東西。 所以它可能意味着服務器不發送由EOL字符結束的文本行。 因此, readLine()方法將阻塞,直到在流中找到這樣的字符,或者套接字被關閉。 如果服務器不發送行,請不要使用readLine()。 使用適用於已定義協議的方法(我們不知道)。

對我來說,這段代碼很奇怪:

bis.readLine()

我記得,這會嘗試讀入緩沖區,直到找到'\\n' 但如果從未發送過怎么辦?

我的丑陋版本打破了任何設計模式和其他建議,但始終有效:

int bytesExpected = clientSocket.available(); //it is waiting here

int[] buffer = new int[bytesExpected];

int readCount = clientSocket.read(buffer);

您還應該添加錯誤和中斷處理的驗證。 有了webservices結果,這對我有用(2-10MB是最大的結果,我發送的)

這是我的實施

 clientSocket = new Socket(config.serverAddress, config.portNumber);
 BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

  while (clientSocket.isConnected()) {
    data = in.readLine();

    if (data != null) {
        logger.debug("data: {}", data);
    } 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM