使用Java通过TCP发送JSON对象

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

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

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

这是我的java代码:

 try { Socket socket = new Socket("xxxx", 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客户端将JSON发布到服务器

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

错误的论点:

 {"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("xxxx"), 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来确认这一点。