我有一些用户文档,表明如何在此节点片段中使用websocket:
var socket = io(“HOST:PORT”);
socket.on('request-server', function() {
socket.emit('server-type', 'red')
});
Akka HTTP中的等效客户端代码是什么?
我从Akka文档中的示例中获得了以下内容。这不是我想写的,因为
request-server
事件。我不知道该怎么做TextMessages
中的Source
等同于`socket.emit('server-type','red')。它只打印“关闭”
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
import system.dispatcher
val incoming: Sink[Message, Future[Done]] = Sink.foreach[Message] {
case message: TextMessage.Strict => println(message.text)
case z => println(z)
}
val outgoing = Source(List(TextMessage("'server-type': 'red'")))
val webSocketFlow = Http().webSocketClientFlow(
WebSocketRequest("ws://localhost:3000/socket.io"))
val (upgradeResponse, closed) =
outgoing
.viaMat(webSocketFlow)(Keep.right)
.toMat(incoming)(Keep.both)
.run()
val connected = upgradeResponse.flatMap { upgrade =>
if (upgrade.response.status == StatusCodes.SwitchingProtocols) {
Future.successful(Done)
} else {
throw new RuntimeException(s"Connection failed: ${upgrade.response.status}")
}
}
connected.onComplete(println)
closed.foreach(_ => println("closed"))
与给定的socket.io代码等效的Akka客户端是什么?
答案 0 :(得分:1)
发送“传出”消息后,您的连接立即关闭。