2017-10-19 129 views
0

我們需要實現一個Socket客戶端,它應該連接到一個接受TCP連接的服務器。如果我通過netcap與服務器進行通信,我會立即得到它的響應(通過命令行)。Java通過Socket發送和接收多條消息

的工作流程是:

nc 99.0.99.84 20000 

然後我發送連接請求到服務器

*99*0## 

我得到的ACK響應返回

*#*1## 

我送我的要求

*#18*802*86## 

我得到的迴應回

*#18*802*86*222241400##*#*1## 

一切都是通過命令行非常快。

所以我試圖用這種方式

try { 

      Socket socket = new Socket("99.0.99.84", 20000); 

      PrintWriter out = new PrintWriter(socket.getOutputStream(), true); 
      BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
      System.out.println("Start"); 
      Thread.sleep(1000); 
      String connectionRequest ="*99*0##"; 
      System.out.println("Sending connection request " + connectionRequest); 
      out.println(connectionRequest); 
      String connResponse = in.readLine(); 

      System.out.println("Response to connection is " + connResponse); 
      Thread.sleep(500); 
      String payload ="*#18*802*86##"; 
      System.out.println("Sending " + payload); 
      out.println(payload); 
      String response = in.readLine(); 


      System.out.println("Response is " + response); 
      out.close(); 
      in.close(); 
      socket.close(); 

     } catch (UnknownHostException e) { 

      e.printStackTrace(); 
     } catch (IOException e) { 

      e.printStackTrace(); 
     } 
    } 

使用攝像機時,客戶端採用了大量的時間,然後與響應退出該連接響應= null與一個客戶端的Socket做到這一點

Sending connection request*99*0## 
Response to connection is *#*1##*#*1## 
Sending *#18*802*86## 
Response is null 

有什麼問題嗎?

+0

響應以'\ r','\ n'還是'\ r \ n'結尾? readLine將讀取直到該點,然後等待它。 – icabod

+0

沒有...沒有行尾元素... – besmart

+0

感謝您的評論我解決了使用讀取()通過讀取char每個字符 – besmart

回答

1

正如你可以在這裏看到:https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()

的readLine()將返回null如果到達行尾料如「\ n」或「\ r」前的數據流被終止。

就像你的情況一樣,你不發送EOL然後關閉流,從而返回null。

嘗試在msg的末尾添加'\ n'。

希望這有助於。

+0

謝謝,問題是我無法改變服務器如何發送它的消息。 – besmart

+1

在閱讀之前嘗試沖洗作者。 out.flush() –