簡體   English   中英

使用Java通過TCP發送JSON對象

[英]Sending a JSON object over TCP with Java

我試圖替換在終端中運行的Netcat命令,該命令將重置服務器上的某些數據。 netcat命令如下所示:

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

代碼也掛在應該讀取InputStream的while循環上,我不知道為什么。 我一直在使用Wireshark捕獲數據包,並且輸出的數據看起來是相同的:

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

也許其余的包裝袋的形狀不同,但我真的不明白為什么會這樣。 也許我以錯誤的方式將字符串寫入OutputStream 我不知道 :(

請注意,當我沒有正確理解問題時,我發布了一個類似於昨天的問題: 無法使用Java中的HTTP Client將JSON發布到服務器

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

錯誤的論點:

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

好的,成功:

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

沒有要刪除的內容:

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

哇,我真的不知道。 我嘗試了一些不同的Writer,例如“ buffered writer”和“ print writer”,看來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();
    }

我認為服務器在消息末尾需要換行符。 嘗試將原始代碼與write()並在最后添加\\n進行確認。

暫無
暫無

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

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