【问题标题】:Basic Play framework routing and web sockets example基本 Play 框架路由和 Web 套接字示例
【发布时间】:2013-05-12 23:00:48
【问题描述】:

我正在尝试学习如何在 Play 2.1 中使用网络套接字,但我无法让网络套接字 URL 与我的应用程序的路由配置一起使用。我从一个新的 Play 应用程序和Play framework documentation on websockets开始。

这是我的conf/routes

# Home page
GET   /               controllers.Application.index

# Websocket test site
GET   /wstest         controllers.Application.wstest

然后我将wstest 函数添加到我的控制器类中:

object Application extends Controller {

  def index = Action {
    Ok(views.html.index("Websocket Test"))
  }

  def wstest = WebSocket.using[String] { request =>
    // Log events to the console
    val in = Iteratee.foreach[String](println).mapDone { _ =>
      Logger.info("Disconnected")
    }

    // Send a single 'Hello!' message
    val out = Enumerator("Hello!")

    (in, out)
  }
}

但是,到目前为止,我只能使用 URL ws://localhost:9000/wstest 访问 websocket(使用 websocket.org/echo.html 的示例代码)。我在看Play框架自带的sample/scala/websocket-chat应用,它使用路由配置文件来引用websocket,像这样:

var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var chatSocket = new WS("@routes.Application.chat(username).webSocketURL()")

我尝试用@routes.Application.wstest.webSocketURL()@routes.Application.wstest 替换我的websocket URL。第一个没有编译。第二个编译,但客户端和服务器不交换任何消息。

如何使用我的 Play 路由配置来访问这个 websocket?我在这里做错了什么?


编辑

这是我的编译错误截图,“Cannot find any HTTP Request Header here”:

【问题讨论】:

    标签: scala playframework websocket playframework-2.0


    【解决方案1】:

    如果没有编译器错误,很难猜测可能是什么问题。

    由于隐式请求,您必须使用括号,即@routes.Application.wstest().webSocketURL(),或者您在 webSocketURL 调用所需的范围内没有隐式请求。

    【讨论】:

    • 感谢您的提示。我添加了编译错误的截图。
    • 是的,在这种情况下,模板中缺少隐式请求,只需添加另一个带有(implicit request: RequestHeader)的参数列表。
    【解决方案2】:

    Marius 是正确的,范围内没有隐式请求。以下是如何将其纳入范围:

    更新控制器中的index函数:

    def index = Action { implicit request =>
      Ok(views.html.index("Websocket Test"))
    }
    

    将请求作为柯里化参数添加到index.scala.html

    @(message: String)(implicit request: RequestHeader)
    
    @main(message) {
    
    <script>
        var output;
        function init() {
            output = document.getElementById("output");
            testWebSocket();
        }
        function testWebSocket() {
            websocket = new WebSocket("@routes.Application.wstest.webSocketURL()");
        .
        .
        .
    

    现在RequestHeader 在范围内。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      • 2011-12-06
      • 1970-01-01
      相关资源
      最近更新 更多