Akka HTTP WebSocket客户端相当于这个node.js

时间:2017-03-28 12:56:13

标签: websocket akka-http

我有一些用户文档,表明如何在此节点片段中使用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客户端是什么?

1 个答案:

答案 0 :(得分:1)

发送“传出”消息后,您的连接立即关闭。

在此处查看半封闭式网页http://doc.akka.io/docs/akka-http/10.0.0/scala/http/client-side/websocket-support.html#half-closed-websockets