In order for the port listening option to work, you have to also use the -n
or -p
options.
Example:
// 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
$
EDIT:
Also, note that you are getting a single line from a socket, not a complete HTTP request. So in the case of a GET, you're going to get multiple lines to process for each request, looking something like this:
GET / HTTP/1.1
Host: localhost:8888
[a variable number of headers]
The whole request is terminated by a blank line. With a POST, it'll look something like this:
POST / HTTP/1.1
Host: localhost:8888
[a variable number of headers]
d=test
The request is the same, except after the blank line that terminates the GET, is the POST data. Unfortunately, the POST data is not terminated with a newline, and groovy is using line buffered input, so it just sits there waiting for a newline.
However, you can force it to proceed by closing your end of the socket. Try something like this:
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()
}
Then groovy will flush the buffer and finish closing other end, and you'll have your POST data.