How to stream messages through websockets in Akka HTTP?

(Ali A) #1

I’m trying to setup a relatively simple websockets system where clients connect, send a message, and the server processes it and periodically sends out messages to the client. Then, the server closes the connection.

I’m really stuck on the step for sending responses back to the client.

The documentation gives the following code for handling incoming messages, then just sending them back to the client:

val handler: Flow[Message, TextMessage, NotUsed] = Flow[Message].mapConcat {
    case msg: TextMessage =>
     //Incoming message, send it back as is
      TextMessage(Source.single(Hi:  ") ++ msg.textStream ) :: Nil
     //Snipped

But there is no documentation for how to send out messages without them being in response to existing messages from the client.

I think what I need is to return a source, which, rather than being Source.single(), is an indefinite source which doesn’t close. But I cannot figure out how to create one of those - Source() only takes an iterable which means it expects a finite set of values.

Any help would be appreciated.

1 Like
(Johan Andrén) #2

Flow.fromSinkAndSource or Flow.fromSinkAndSourceCoupled are your friends here, they allow an arbitrary/decoupled pair of Sink[Message, _] and Source[Message, _] to be combined into a flow you can handle the websocket connection with.