2014-09-10 149 views
2

我正在尝试使用spray-can来设置一个非常基本的HTTP服务器。如果我为端点设置了一个映射,我会得到一个超时(尽管使用调试器,我可以看到这个actor收到了这个消息)。为什么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" 
) 

关于我在做什么的错误?

回答

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

应该

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

您正在返回HttpResponse对象,而不是将消息发送给发件人。

+0

当然,这是问题 - 非常感谢! – manub 2014-09-10 10:07:05

+1

我不明白为什么Scala编译器没有抱怨HttpResponse在单元预期时返回。 – 2014-09-10 11:00:49

+1

当预期类型为Unit时,Ravi - Scala执行从任何值到Unit的隐式转换。 - 从规范:价值抛弃。如果e具有某种值类型,并且预期类型为Unit,则通过将e嵌入术语{e; ()} – Bryan 2014-09-10 20:35:12

相关问题