播放框架2.5.0 Websockets示例

问题描述:

播放框架2.5.0 Websockets示例.

Play framework 2.5.0 Websockets example.

在播放2.5.0中,websockets代码已更改为支持akka流,但我找不到使用它的示例代码.

in play 2.5.0 websockets code is changed to support akka streams but I'm not able find a sample code to use it.

这将在2.5.1中正确记录,如下所示:

This will be properly documented in 2.5.1 as you can see here: https://github.com/playframework/playframework/issues/5057

同时,您可以查看Streams中有一部分的《迁移指南》: https://www.playframework.com/documentation/2.5.x/StreamsMigration25#Migrating-WebSockets-%28WebSocket%29

In the meantime you can take a look at the Migration Guide which has a part on Streams: https://www.playframework.com/documentation/2.5.x/StreamsMigration25#Migrating-WebSockets-%28WebSocket%29

您会注意到,重要的部分是WebSocket.MappedWebSocketAcceptor<In,Out>类.您可以用它告诉Play如何将Message帧转换为您自己的类型-如StringJson等.

You will notice that the important part is the WebSocket.MappedWebSocketAcceptor<In,Out> class. You use this one to tell Play how to convert Message frames to your own types - like String, Json, etc.

幸运的是,Play的Java API提供了一些预定义的实现.假设您要处理交换JSON数据的WebSocket连接.然后您将使用WebSocket.Json( https://github.com/playframework/playframework/blob/master/framework/src/play/src/main/java/play/mvc/WebSocket.java#L71 )

Fortunately the Java API of Play provides some predefined implementations. Let's say you want to handle WebSocket connections which exchange JSON data. Then you would use WebSocket.Json (https://github.com/playframework/playframework/blob/master/framework/src/play/src/main/java/play/mvc/WebSocket.java#L71)

return WebSocket.Json.accept(requestHeader -> {
  // returns a Flow<JsonNode, JsonNode, ?>
})