如何通过groovy监听端口获取帖子内容?

时间:2010-12-31 18:08:04

标签: groovy command-line-interface

我编写了以下处理请求的简单groovy代码。

if (init)
  data = ""

if (line.size() > 0) {
  data += "--> " + line + "\n"
} else {
  println "HTTP/1.1 200 OK\n"
  println data
  println "----\n"
  return "success"
}

然后我通过执行groovy -l 8888 ServerTest.groovy来运行它但是,它似乎不打印任何POST数据。我正在测试它curl -d "d=test" http://localhost:8888/有人知道如何在groovy中获取数据吗?

1 个答案:

答案 0 :(得分:2)

为了使端口侦听选项有效,您还必须使用-n-p选项。

示例:

// test.groovy
println "Got $line from socket"

$ groovy -n -l8888 test.groovy &
groovy is listening on port 8888
$ echo hello | nc localhost 8888
Got hello from socket
$

编辑: 另请注意,您从套接字获取单行,而不是完整的HTTP请求。所以在GET的情况下,你将为每个请求获得多行代码,看起来像这样:

GET / HTTP/1.1
Host: localhost:8888
[a variable number of headers]

整个请求以空行终止。使用POST,它看起来像这样:

POST / HTTP/1.1
Host: localhost:8888
[a variable number of headers]

d=test

请求是相同的,除了终止GET的空行之后是POST数据。不幸的是,POST数据没有以换行符终止,并且groovy正在使用行缓冲输入,所以它只是在那里等待换行。

但是,您可以通过关闭套接字结束强制它继续。尝试这样的事情:

System.err.println(line) // log the incoming data to the console

if (line.size() == 0) {
    println "HTTP/1.1 200 OK\r\n\r\nhello"
    socket.shutdownOutput()
}

然后groovy将刷新缓冲区并完成关闭另一端,你将拥有你的POST数据。