0

How to use WebSocket.acceptWithActor with BroadCast in Playframework2.3.7

I don't want to write Iteratee in Broadcasting. https://www.playframework.com/documentation/2.3.x/ScalaWebSockets

I want to push all clients when receive message from client.

@Singleton
class Application @Inject() (textGenerator:TextGenerator) extends Controller {

  def index = Action {
    Ok(views.html.index(textGenerator.welcomeText))


  }
  def socket = WebSocket.acceptWithActor[String, String] { request => out =>
    MyWebSocketActor.props(out)
  }

  object MyWebSocketActor {
    def props(out: ActorRef) = Props(new MyWebSocketActor(out))
  }

  class MyWebSocketActor(out: ActorRef) extends Actor {
    private[this] var (channel) = Concurrent.broadcast[String]
    override def receive = {
      case msg: String =>
        out ! msg
    }
    override def postStop() = {
      Logger.info("Disconnected!")
    }

  }
}

1 Answer 1

1

I would strongly recommend using LookupEventBus from akka framework instead. You can subscribe actors to specific channel and let event bus do the broadcasting job for you. Subscribing to channel named sample:

WebSocket.withActor((out) -> {
    eventBus.subscribe(out, "sample");
    return Props.create(SampleActor.class, out, eventBus);
});

eventBus - extension of LookupEventBus. SampleActor - extension of UntypedActor.

The only tricky part is to unsubscribe the actor from event bus which can be done in postStop() method of UntypedActor.

3
  • No problem. I leave implementations of extensions to you, however if you have any issues, let me know. Jan 26, 2015 at 11:27
  • Could you expand a bit of please.I don't know eventBus object.And I wish this scala version.
    – ozw_sei
    Jan 26, 2015 at 15:48
  • It is abstract class LookupEventBus from akka-actor 2.11. Jan 26, 2015 at 15:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.