使用 Java 通过 TCP 发送 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14788002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:23:57  来源:igfitidea点击:

Sending a JSON object over TCP with Java

javajsonsocketstcp

提问by span

I'm trying to replace a Netcat command that I'm running in my terminal that will reset some data on a server. The netcat command looks like this:

我正在尝试替换我在终端中运行的 Netcat 命令,该命令将重置服务器上的一些数据。netcat 命令如下所示:

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

I've been trying to implement it in Java since I would like to be able to call this command from an application I'm developing. I'm having issues with it though, the command is never executed on the server.

我一直在尝试用 Java 实现它,因为我希望能够从我正在开发的应用程序中调用这个命令。但是我遇到了问题,该命令从未在服务器上执行。

This is my java code:

这是我的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();
}

The code also hangs on the while loop that should read the InputStream, I have no idea why. I've been using Wireshark to capture the packets and the data that is going out looks the same:

该代码还挂在应该读取 的 while 循环中InputStream,我不知道为什么。我一直在使用 Wireshark 来捕获数据包,输出的数据看起来是一样的:

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

Perhaps the rest of the packets are not shaped in the same way but I really can't understand why that would be. Perhaps I am writing the string in a faulty way to the OutputStream? I have no idea :(

也许其余的数据包的形状不同,但我真的不明白为什么会这样。也许我正在以错误的方式将字符串写入OutputStream? 我不知道 :(

Note that I posted a question similar to this yesterday when I didn't properly understand the problem: Can't post JSON to server with HTTP Client in Java

请注意,当我没有正确理解问题时,我昨天发布了一个与此类似的问题: Can't post JSON to server with HTTP Client in Java

EDIT: These are the possible results I get from running the nccommand, I would expect to get the same messages to the InputStream if the OutputStream sends correct data in a correct way:

编辑:这些是我从运行nc命令中得到的可能结果,如果 OutputStream 以正确的方式发送正确的数据,我希望得到相同的消息到 InputStream:

Wrong arguments:

错误的论据:

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

Ok, successful:

好的,成功:

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

Nothing to delete:

没什么可删除的:

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


Wow, I really had no idea. I experimented with some different Writers like "buffered writer" and "print writer" and it seems the PrintWriterwas the solution. Although I couldn't use the PrintWriter.write()nor the PrintWriter.print()methods. I had to use PrintWriter.println().

哇,我真的不知道。我尝试了一些不同的作家,如“缓冲作家”和“印刷作家”,似乎PrintWriter是解决方案。虽然我不能使用PrintWriter.write()或者PrintWriter.print()方法。我不得不使用PrintWriter.println().

If someone has the answer to why other writers wouldn't work and explain how they would impact the data sent to the server I will gladly accept that as the solution.

如果有人回答了为什么其他作者不工作并解释了他们将如何影响发送到服务器的数据,我将很乐意接受它作为解决方案。

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

采纳答案by iTech

I think the server is expecting newline at the end of the message. Try to use your original code with write()and add \nat the end to confirm this.

我认为服务器在消息末尾等待换行符。尝试使用您的原始代码write()\n在末尾添加以确认这一点。