2013-02-09 136 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