How to send a message in a reactive stream from a subscriber to a publisher in a network socket connection

My application has an Akka-Websocket interface. A web socket consists of an actor-subscriber and an actor’s publisher. The subscriber processes the teams, sending them to the corresponding player. The publisher listens to the stream of events and publishes update information in the stream (and finally to the client). It works well.

My question is: how can the Subscriber send the event back to the stream? For example, to confirm the execution of a received command.

public class WebSocketApp extends HttpApp { private static final Gson gson = new Gson(); @Override public Route createRoute() { return get( path("metrics").route(handleWebSocketMessages(metrics())) ); } private Flow<Message, Message, ?> metrics() { Sink<Message, ActorRef> metricsSink = Sink.actorSubscriber(WebSocketCommandSubscriber.props()); Source<Message, ActorRef> metricsSource = Source.actorPublisher(WebSocketDataPublisherActor.props()) .map((measurementData) -> TextMessage.create(gson.toJson(measurementData))); return Flow.fromSinkAndSource(metricsSink, metricsSource); } } 

A good solution would be if the signing actor (the WebSocketCommandSubscriber actor in the above code) could send a message back to the stream, for example sender().tell(...) ...

+5
source share
1 answer

No, this is impossible, not directly, at least. Streams are always unidirectional - all messages flow in one direction, and demand for them flows in the opposite direction. You need to send your confirmation messages from the receiver to the source so that the latter issues it back to the client, for example, registering the role of the source in the actor. It might look like this:

 Flow.fromSinkAndSourceMat(metricsSink, metricsSource, (sinkActor, sourceActor) -> { sinkActor.tell(new RegisterSource(sourceActor), null); }) 

Then, after your receiver receives the RegisterSource message, it can send confirmation messages to the provided ActorRef , which then forwards them to the output stream.

+4
source

All Articles