Playframework 服务器发送的事件不';不能在游戏框架中工作
以下代码在Play framework 2.3中不起作用 controllers.NotificationHandler.sendNotification(): JS代码:Playframework 服务器发送的事件不';不能在游戏框架中工作,playframework,server-sent-events,playframework-2.3,Playframework,Server Sent Events,Playframework 2.3,以下代码在Play framework 2.3中不起作用 controllers.NotificationHandler.sendNotification(): JS代码: var event = new EventSource("@controllers.NotificationHandler.sendNotification()"); event.addEventListener('message', function( event ) { alert(event.data); }
var event = new EventSource("@controllers.NotificationHandler.sendNotification()");
event.addEventListener('message', function( event ) {
alert(event.data);
} );
您应该更改js部件以使用到控制器的路由,而不是控制器本身:
var event = new EventSource("@routes.NotificationHandler.sendNotification()");
event.addEventListener('message', function( event ) {
alert(event.data);
}
);
您的控制器似乎不需要SSE,因为它只发送一个值,更完整的示例是创建enumertaor并使用它发送SSE,如下所示:
def sendNotification = Action{
val producer = Enumerator.generateM[String](Promise.timeout(Some(Random.nextString(5)),3 second))
Ok.chunked(producer &> EventSource()).as("text/event-stream")
}
要在消息可用后发送消息,可以使用Concurrent.broadcast
val (producer,channel) = Concurrent.broadcast[String]
def sendNotification = Action{
Ok.chunked(producer &> EventSource()).as("text/event-stream")
}
然后使用channel.push(您的数据)将数据推送到浏览器。请注意,在此示例中,通道是一个全局对象
val (producer,channel) = Concurrent.broadcast[String]
def sendNotification = Action{
Ok.chunked(producer &> EventSource()).as("text/event-stream")
}