Scala akka-http WebSocket:如何保存客户端连接并在需要时将消息推送到客户端?

时间:2016-07-01 16:11:41

标签: scala akka akka-http

如何将客户端(Web)连接保存在内存变量中,然后在需要时将外发消息发送到客户端(Web)?

我已经有一些简单的代码,用于在服务器从客户端接收消息后将消息推回客户端。如何为传出消息传递部分修改下面的代码?

implicit val actorSystem = ActorSystem("akka-system")
implicit val flowMaterializer = ActorMaterializer()
implicit val executionContext = actorSystem.dispatcher

val ip = "127.0.0.1"
val port = 32000

val route = get {
    pathEndOrSingleSlash {
        complete("Welcome to websocket server")
    }
} ~
path("hello") {
    get {
        handleWebSocketMessages(echoService)
    }
}

def sendMessageToClient(msg : String) {

    // *** How to implement this?
    // *** How to save the client connection when it is first connected?
    //     Then how to send message to this connection?

}

val echoService = Flow[Message].collect {

    // *** Here the server push back messages when receiving msg from client

    case tm : TextMessage => TextMessage(Source.single("Hello ") ++ tm.textStream)
    case _ => TextMessage("Message type unsupported")
}

val binding = Http().bindAndHandle(route, ip, port)

1 个答案:

答案 0 :(得分:1)

您可以通过.map调用来查看对汇流的流水线操作。在.map调用内,您可以捕获该值,然后返回相同的消息。例如:

  Flow[Message].collect {
    case tm : TextMessage =>
      TextMessage(Source.single("Hello ") ++ tm.textStream.via(
        Flow[String].map((message) => {println(message) /* capture value here*/; message})))
    case _ => TextMessage("Message type unsupported")
  }

现在,如果您打算处理这些值并稍后发送值,那么您想要的不是单个源到接收流,而是用于接收器和源的两个单独的流,您可以使用{{1例如

Flow.fromSinkAndSource

很可能,这个来源可以用图形DSL构建,也可以是手工制作的演员,或者你可以考虑使用Flow.fromSinkAndSource[Message, Message]( Flow[Message].collect { /* capture values */}, // Or send stream to other sink for more processing source ) 这样的可重复使用的助手。