How to receive a message using groovy listening on a port?

I wrote the following simple groovy code that processes the request.

if (init)
  data = ""

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

Then I ran it, doing groovy -l 8888 ServerTest.groovyhowever, it does not print any POST data. I test it by doing Does anyone know how to get this data in groovy?curl -d "d=test" http://localhost:8888/

+3
source share
1 answer

For the port listening feature to work, you must also use the -nor options -p.

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 one line from a socket, not a full HTTP request. Therefore, in the case of GET, you will get several lines for each request, looking something like this:

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.

+2

Source: https://habr.com/ru/post/1782950/


All Articles