Groovy 中是否有等效于 Python 产量的行为?

n1c9

尝试学习 Groovy,到目前为止,这是一次有趣的冒险,只是有点令人困惑。我目前正在尝试做的是启动一个服务器,wget向它发出请求,当收到该请求时,执行某个操作 - 在这种情况下,只需创建一个新文件:

import java.net.http.HttpResponse

class ServerLogic {
    static def holdupServer() {
        println('Standing up server..\n')
        def socketServer = new ServerSocket(5000)
        // server is up
        socketServer.accept { socket ->
        // the lines below only execute when a connection is made to the server
        socket.withStreams { input, output ->
            println("[${new Date()}] HELLO\n")
            def newFile = new File("/home/nick/IdeaProjects/groovy_learning/resources/new.txt")
            newFile.createNewFile()
            newFile.text = 'Hello!!!'
            println("NEW FILE SHOULD HAVE BEEN CREATED.")
            println ">> READ: ${input.newReader().readLine()}"
        }
    }
        return HttpResponse
    }

}

ServerLogic.holdupServer()

使用上面的代码,当我执行 a 时wget http://localhost:5000,它“有效”,因为文件是按照我想要的方式创建的,但wget输出不满意:

--2021-07-17 15:42:32--  http://localhost:5000/
Resolving localhost (localhost)... 127.0.0.1
Connecting to localhost (localhost)|127.0.0.1|:5000... connected.
HTTP request sent, awaiting response... No data received.
Retrying.

--2021-07-17 15:42:33--  (try: 2)  http://localhost:5000/
Connecting to localhost (localhost)|127.0.0.1|:5000... failed: Connection refused.
Resolving localhost (localhost)... 127.0.0.1
Connecting to localhost (localhost)|127.0.0.1|:5000... failed: Connection refused.  
// these occur because the server has shut down after the last println call, when the `return HttpResponse` triggers

因此,我们可以推断出没有返回正确的响应,即使我有return HttpResponseaftersockerServer.accept ...逻辑。我对如何解决这个问题的想法(主要是因为我来自 Python 背景)是以某种方式模仿yieldPython 中的响应(基本上,在不破坏holdupServer()逻辑的情况下返回响应,从而中断服务器连接)。有没有办法在 Groovy 中实现这一点,或者有没有一种不同的方法可以用来基本上返回有效HttpResponse而不退出holdupServer()块?

麦孔毛里西奥

解释

您可以使用函数 callback,它在 Groovy 中转换为闭包回调。基本上,您将要返回的值传递给另一个延迟当前方法上的堆栈的函数/方法。这种方法基本上适用于所有语言。例如,在 java(不支持 lambda 的版本)中,您必须传递一个对象,稍后您将在其中调用方法。

例子

import java.net.http.HttpResponse

class ServerLogic {
    static def holdupServer(Closure closure) {
        (0..2).each {
            closure.call(HttpResponse)
        }
    }
}

ServerLogic.holdupServer { httpResponse ->
    println httpResponse
}

输出

interface java.net.http.HttpResponse
interface java.net.http.HttpResponse
interface java.net.http.HttpResponse

处理 OP 的评论

您必须提供一些标题。至少Content-Type并且Content-Length应该与正确格式化的数据和 HTTP 状态(在这种情况下为 HTTP/1.1 200)一起提供。此外,您应该将ServerSocket.accept调用包装在一个 while 循环中。

请参阅关于 HTTP的 MDN概述

代码

class ServerLogic {
    static HEADERS = [
      "HTTP/1.1 200",
      "Content-Type: text/html; charset=utf-8",
      "Connection: Keep-Alive",
      "Keep-Alive: timeout=5, max=1000",
      "Content-Length: %d\r\n",
      "%s"
    ].join("\r\n")

    static def holdupServer(Closure callback) {
      println('Standing up server..\n')
      def socketServer = new ServerSocket(5000)
        // server is up
      while(true) { // Continue to accept connections
        socketServer.accept { socket ->
        // the lines below only execute when a connection is made to the server
          callback.call(socket) // call function
      }
    }
  }
}

ServerLogic.holdupServer { Socket socket ->
  String data = "RESPONSE <--\n"
  def response = String.format(ServerLogic.HEADERS, data.size(), data)
  println response
  socket << response
}

客户端输出

RESPONSE <--

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

VBA中是否有等效于Python的pass语句?

Elixir中是否有等效于Python的dir()

在C#中是否有等效于Python的ImportError

是否有R函数等效于Python中的range?

是否有等效于python中的any方法的方法

在Python中是否有等效于RStudio的“ .rs.askForPassword”?

在Python中是否有等效于R apply函数的函数?

Elixir中是否有等效于Python的defaultdict的代码?

C ++中是否有任何等效于python中字典的get函数的函数?

在现代C ++中,是否有等效于python中基于范围的“枚举”循环?

Swift中是否有等效于Python中“过滤器”功能的Swift?

在rebol中是否有一个等效于“ continue”(python)的东西?

Matlab中是否有等效于Python的列表和附加功能?

在C ++ / STL中是否有等效于Python range()的紧凑型

在C ++ / STL中是否有等效于Python range()的紧凑型

在python / scipy,numpy,sympy中是否有等效于Mathematicas RootApproximant函数?

ES6中是否有等效于Python样式的类属性?

是否有等效于C语言的python中的“ in”关键字

是否有任何 python 等效于 haskell 的 "it" ,以获得 REPL 中的最后一个成功命令

是否有等效于python的maven / ivy依赖项管理?

是否有等效于Python的bootstrap.php?

是否有Python(3)本机等效于rlwrap调用脚本?

是否有一个等效于python virtualenv的GO?

c ++是否有等效于Python的'in'关键字?

是否有Dart等效于Python的all()方法?

是否有MatLab等效于Python matplotlib的tight_layout()?

是否有等效于 Python 的 pprint 的 C#?

R是否等效于Python的'*'?

Python产量与Ruby产量