转载

java – Play Framework – 是否可以在Play中结合使用Promise和WebSocket?

我正在使用Play 2.0.1和Java.

到目前为止,我已经使用Promise加载了一个显示数据库数据的页面.

这是最初的Controller代码:

public static Result index() {
    // Generate the page
    final MainPage page = new MainPage();

    Promise<MainPage> promiseMainPage = Akka.future(
            new Callable<MainPage>() {
                public MainPage call() throws Exception {
                    page.generate();
                    return page;
                }
            });

    return async(promiseMainPage.map(new Function<MainPage, Result>() {
            @Override
            public Result apply(MainPage mainPage) throws Throwable {
                return ok(views.html.index.render(mainPage));
            }
     }));
}

这一切都很好;承诺的页面发送到浏览器,而服务器不阻止数据库查询(在page.generate()中执行)完成.

但是,现在我想使用WebSocket来更新从数据库中检索到的新/修改信息的页面.

所以我使用Chat示例来做到这一点(甚至简化,因为我只想使用传出通道:服务器到客户端).我已将以下内容添加到index.scala.html的末尾:

<script type="text/javascript" charset="utf-8">

    $(function() {
    var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket;
    var socket = new WS("@(routes.Application.webSocket().webSocketURL(request))");

    var receiveEvent = function(event) {
        var data = JSON.parse(event.data);

        var connectionStatus = data["connectionStatus"];
        var connectionStatusHtml = '<font color="red">* Not connected</font>';
        if (connectionStatus != undefined) {
            connectionStatusHtml = '<font color="blue">' + connectionStatus + '</font>';
        }

        $('#connectionStatus').html(connectionStatusHtml);
    }

    socket.onmessage = receiveEvent;
    })

</script>

我已经更新了路由文件并为webSocket()请求创建了一个处理程序.

此时,当我尝试浏览页面时,我从播放中收到以下错误:

[error] play - Waiting for a promise, but got an error: null
java.lang.RuntimeException: null
    at play.libs.F$Promise$2.apply(F.java:113) ~[play_2.9.1.jar:2.0.1]
    at akka.dispatch.Future$$anonfun$map$1.liftedTree3$1(Future.scala:625) ~[akka-actor.jar:2.0.1]
    at akka.dispatch.Future$$anonfun$map$1.apply(Future.scala:624) ~[akka-actor.jar:2.0.1]
    at akka.dispatch.Future$$anonfun$map$1.apply(Future.scala:621) ~[akka-actor.jar:2.0.1]
    at akka.dispatch.DefaultPromise.akka$dispatch$DefaultPromise$$notifyCompleted(Future.scala:943) [akka-actor.jar:2.0.1]
    at akka.dispatch.DefaultPromise$$anonfun$tryComplete$1$$anonfun$apply$mcV$sp$4.apply(Future.scala:920) [akka-actor.jar:2.0.1]

这发生在返回ok(views.html.index.render(mainPage));.

从HTML文件中注释掉脚本可以解决这个问题,但当然不会打开WebSocket.

是否可以在Play中结合使用Promise和WebSocket?也许我想念用它?

原文  https://codeday.me/bug/20190110/504792.html
正文到此结束
Loading...