2013-02-09 208 views
2

我試圖替換在終端中運行的Netcat命令,它將重置服務器上的一些數據。該netcat的命令如下:用Java通過TCP發送JSON對象

echo '{"id":1, "method":"object.deleteAll", "params":["subscriber"]} ' | nc x.x.x.x 3994 

我一直在努力實現它在Java中,因爲我希望能夠從我開發一個應用程序調用該命令。雖然我遇到了問題,但該命令從未在服務器上執行過。

這是我的Java代碼:

try { 
    Socket socket = new Socket("x.x.x.x", 3994); 
    String string = "{\"id\":1,\"method\":\"object.deleteAll\",\"params\":[\"subscriber\"]}"; 
    DataInputStream is = new DataInputStream(socket.getInputStream()); 
    DataOutputStream os = new DataOutputStream(socket.getOutputStream()); 
    os.write(string.getBytes()); 
    os.flush(); 

    BufferedReader in = new BufferedReader(new InputStreamReader(is)); 
    String inputLine; 
    while ((inputLine = in.readLine()) != null) 
     System.out.println(inputLine); 

    is.close(); 
    os.close(); 

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

代碼還掛在while循環應該讀InputStream,我不知道爲什麼。我一直在使用Wireshark來捕獲的數據包和即將出來的數據看起來是一樣的:

{"id":1,"method":"object.deleteAll","params":["subscriber"]} 

也許剩餘數據包以同樣的方式不是形,但我真的不明白爲什麼將會。也許我是以錯誤的方式寫入字符串到OutputStream?我不知道:(

注意,我張貼與此類似昨天的一個問題,當我沒有正確理解這個問題: Can't post JSON to server with HTTP Client in Java

編輯: 這些都是可能的結果我從運行nc得到命令,我希望得到同樣的消息到的InputStream如果OutputStream的以正確的方式將正確的數據:

錯誤論點:

{"id":1,"error":{"code":-32602,"message":"Invalid entity type: subscribe"}} 

好了,成功:

{"id":1,"result":100} 

沒有刪除:

{"id":1,"result":0} 

哇,我真的不知道。我嘗試過一些不同的作家,如「緩衝作家」和「打印作家」,看來PrintWriter是解決方案。儘管我不能使用PrintWriter.write()PrintWriter.print()方法。我不得不使用PrintWriter.println()

如果有人有答案,爲什麼其他作家不會工作,並解釋他們將如何影響發送到服務器的數據我會很樂意接受作爲解決方案。

try { 
     Socket socket = new Socket(InetAddress.getByName("x.x.x.x"), 3994); 
     String string = "{\"id\":1,\"method\":\"object.deleteAll\",\"params\":[\"subscriber\"]}"; 
     DataInputStream is = new DataInputStream(socket.getInputStream()); 
     DataOutputStream os = new DataOutputStream(socket.getOutputStream()); 
     PrintWriter pw = new PrintWriter(os); 
     pw.println(string); 
     pw.flush(); 

     BufferedReader in = new BufferedReader(new InputStreamReader(is)); 
     String inputLine; 
     while ((inputLine = in.readLine()) != null) 
      System.out.println(inputLine); 

     is.close(); 
     os.close(); 

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

目標x.x.x.x:3994是否響應任何數據?如果沒有,你的程序將掛起。 – harpun 2013-02-09 12:22:54

+0

我收到的數據包可以在wireshark中看到,但它們不包含任何數據。我只收到發送數據包的ACK,然後收到FIN/FIN ACK序列。當我在終端中運行nc命令時,如果語法錯誤,我會得到一個「錯誤」,如果不成功,則返回「result = 0」,如果成功執行,則返回「result = 1」。我正在使用應該出現在輸入流中的錯誤消息更新問題。 – span 2013-02-09 12:25:04

+0

因此,如果您不希望目標的任何輸出確認JSON數據傳輸,則可以跳過while循環。嘗試評論一下,看看這是否符合你的需求。 – harpun 2013-02-09 12:26:56

回答

1

我認爲服務器在消息結尾處期待換行符。嘗試使用write()的原始代碼並在末尾添加\n以確認此操作。

+0

是的,我完全同意這一點。我想知道爲什麼......它必須是服務器實現,使用一些代碼等待新線路來決定命令是否完整。這很奇怪,因爲除了完成bash命令之外,我不在nc命令中添加新行。 JSON對象後面沒有\ n。也許nc自己添加一個新行? – span 2013-02-09 22:57:24

+1

Wooops,它似乎它! http://stackoverflow.com/questions/11273999/new-line-issue-with-netcat – span 2013-02-09 22:58:56