为什么spray-can服务器不响应http请求?

时间:2014-09-10 09:39:25

标签: scala spray

我尝试使用spray-can设置一个非常基本的HTTP服务器。如果我调用端点我已经设置了映射,我会超时(虽然使用调试器我可以看到演员收到消息)。

我的来源如下:

import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.io.IO
import spray.can.Http
import spray.http.{HttpMethods, HttpRequest, HttpResponse, Uri}

class App extends Actor {

  implicit val system = context.system

  override def receive = {
    case "start" =>
      val listener: ActorRef = system.actorOf(Props[HttpListener])
      IO(Http) ! Http.Bind(listener, interface = "localhost", port = 8080)
  }

}

class HttpListener extends Actor {

  def receive = {
    case _: Http.Connected =>
      sender() ! Http.Register(self)
    case HttpRequest(HttpMethods.GET, Uri.Path("/ping"), _, _, _) =>
      HttpResponse(entity = "PONG")
  }

}

object Main {

  def main(args: Array[String]) {
    val system = ActorSystem("my-actor-system")
    val app: ActorRef = system.actorOf(Props[App], "app")
    app ! "start"
  }

}

执行run显示:

> run
[info] Running Main
[INFO] [09/10/2014 21:33:38.839] [my-actor-system-akka.actor.default-dispatcher-3] [akka://my-actor-system/user/IO-HTTP/listener-0] Bound to localhost/127.0.0.1:8080

点击HTTP/1.1 500 Internal Server Error时显示以下http://localhost:8080/ping

➜  ~  curl --include http://localhost:8080/ping
HTTP/1.1 500 Internal Server Error
Server: spray-can/1.3.1
Date: Wed, 10 Sep 2014 19:34:08 GMT
Content-Type: text/plain; charset=UTF-8
Connection: close
Content-Length: 111

Ooops! The server was not able to produce a timely response to your request.
Please try again in a short while!

我的build.sbt看起来像是:

scalaVersion := "2.11.2"

resolvers += "spray repo" at "http://repo.spray.io"

libraryDependencies ++= Seq(
  "io.spray" %% "spray-can" % "1.3.1",
  "io.spray" %% "spray-routing" % "1.3.1",
  "com.typesafe.akka" %% "akka-actor" % "2.3.5"
)

关于我做错的任何想法?

1 个答案:

答案 0 :(得分:4)

case HttpRequest(HttpMethods.GET, Uri.Path("/ping"), _, _, _) =>
  HttpResponse(entity = "PONG")

应该是

case HttpRequest(HttpMethods.GET, Uri.Path("/ping"), _, _, _) =>
  sender ! HttpResponse(entity = "PONG")

您正在返回HttpResponse,而不是向发件人发送邮件。