我有一个非常简单的Akka WebSocket服务器,它将文件中的行推送到连接的客户端,每行间隔400毫秒。一切正常,除了Web服务器似乎在广播之前缓冲消息大约一分钟。
因此,当客户端连接时,我在服务器端看到每隔400ms读取一行并将其推送到Sink
,但在客户端,我什么都没得到一分钟,然后突然大约150消息(对应于一分钟的消息)。
是否有我忽略的设置?
object WebsocketServer extends App {
implicit val actorSystem = ActorSystem("WebsocketServer")
implicit val materializer = ActorMaterializer()
implicit val executionContext = actorSystem.dispatcher
val file = Paths.get("websocket-server/src/main/resources/EURUSD.txt")
val fileSource =
FileIO.fromPath(file)
.via(Framing.delimiter(ByteString("\n"), Int.MaxValue))
val delayedSource: Source[Strict, Future[IOResult]] =
fileSource
.map { line =>
Thread.sleep(400)
println(line.utf8String)
TextMessage(line.utf8String)
}
def route = path("") {
extractUpgradeToWebSocket { upgrade =>
complete(upgrade.handleMessagesWithSinkSource(
Sink.ignore,
delayedSource)
)
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
bindingFuture.onComplete {
case Success(binding) ⇒
println(s"Server is listening on ws://localhost:8080")
case Failure(e) ⇒
println(s"Binding failed with ${e.getMessage}")
actorSystem.terminate()
}
}
答案 0 :(得分:1)
所以使用Thread.sleep(400)
的方法是错误的。我应该在资源上使用.throttle
机制:
val delayedSource: Source[Strict, Future[IOResult]] =
fileSource
.throttle(elements = 1, per = 400.millis)
.map { line =>
println(line.utf8String)
TextMessage(line.utf8String)
}
这解决了这个问题。